I have started to learn pygame these days, and I have some questions when I uses pygame.event.get(). Hope someone can help me figure out the concept behind it.
Below is my simple code:
import pygame
# initialize pygame
pygame.init()
# create a window
screen = pygame.display.set_mode((800,600))
# load player (image) into pygame
player_img = pygame.image.load("aircraft.png")
player_pos_x = 400
player_pos_y = 500
player_pos_x_change = 0
# remove and redraw image in screen: move the object
def PlayerPosition(x,y):
screen.blit(player_img, (x,y))
# go inside game loop
running = True
while running:
# receive any event
for event in pygame.event.get():
# handle QUIT event
if event.type == pygame.QUIT:
running = False
# handle KEYDOWN event
if event.type == pygame.KEYDOWN:
# decide left key or right key is pressed
if event.key == pygame.K_LEFT:
if player_pos_x > 0:
player_pos_x_change = -0.1
else:
player_pos_x_change = 0
if event.key == pygame.K_RIGHT:
player_pos_x_change = 0.1
# handle KEYUP event
if event.type == pygame.KEYUP:
player_pos_x_change = 0
# set background color :
screen.fill((0, 0, 0))
# update player's x position
player_pos_x += player_pos_x_change
# call function to remove and redraw image in screen
PlayerPosition(player_pos_x, player_pos_y)
pygame.display.update()
Inside the while loop, program will receive event with pygame.event.get(). If detect "left key" is pressed, set x_change to negative, so the object in screen will go left, vice versa.
Now, I want to make boundary for my screen, the object cannot go outside the screen. Hence, I add a condition in if event.key == pygame.K_LEFT::
if player_pos_x > 0:
player_pos_x_change = -0.1
else:
player_pos_x_change = 0
However, when I hold the left key continuously, the object still go outside the screen. I cannot understand why will it happen ?
I'm very thank for your reply and comment.
setPostViews(get_the_ID());outside of the loop and still get this to work, probably in the correct manner. - Faham Shaikh$counthas any value stored in it and set it to '0' or increment and then callupdate_post_metaas it internally callsadd_post_metaif the meta data doesn't exist or update it if meta data does exists. - Faham Shaikh