i am new to python programming and now starting to write simple "Snake" game. i am trying to make the head of the snake move around the screen in a way that when an arrow key is pressed, the head should move in that direction non-stop, until a perpendicular arrow is pressed. i cant make the head of the snake ( a rectangle) to move non stop in single direction slowly. i tried to use time.sleep() --> it made the whole code stuck. i tried to use for loop --> it just made the rectangle to transport to the other direction fast.
this is my main function:
while not GameOver:
#create time delay of 10 milliseconds
pygame.time.delay(10)
# Get all of the events on the game's screen [all of the user's input]
# Loop on the user's activity and look for exit button pressing.
for event in pygame.event.get():
# If the user presses the X button:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Define a shortcut name to "get_pressed" method in pygame:
keys = pygame.key.get_pressed()
# defining x location
x = head_position[0]
y = head_position[1]
# if he pressed left key
if keys[pygame.K_LEFT]:
# reducing location by constant
head_position[0] -= head_speed
elif keys[pygame.K_RIGHT]:
# increacing location by constant
head_position[0] += head_speed
elif keys[pygame.K_UP]:
# increacing location by constant
head_position[1] -= head_speed
elif keys[pygame.K_DOWN]:
# increacing location by constant
head_position[1] += head_speed
#If the head passes the screen Boundaries, it would pop in the other side.
if head_position[0] >= WIDTH:
head_position[0] = 0
elif head_position[0] < 0:
head_position[0] = WIDTH-head_size
elif head_position[1] >= HEIGHT:
head_position[1] = 0
elif head_position[1] < 0:
head_position[1] = HEIGHT-head_size
Use the
pygame.timemodule to control the frames per second. Generate apygame.time.Clockobject. If you pass the optional framerate argument topygame.time.Clock.tick, the function will delay to keep the game running slower than the given ticks per second: