Answer the question
In order to leave comments, you need to log in
Why does the pygame snake move diagonally?
Why does the snake move diagonally and not horizontally?
import pygame
pygame.init()
# display settings
width = 650
height = 480
display = pygame.display.set_mode((width, height))
pygame.display.update()
pygame.display.set_caption("Snake Game")
# run loop
run = True
# snake settings
snake_pos = {
"x": width/2-5,
"y": height/2-5,
"x_change": 0,
"y_change": 0
}
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
snake_pos["x_change"] = 10
snake_pos["y_change"] = 0
elif event.key == pygame.K_w:
snake_pos["x_change"] = -10
snake_pos["y_change"] = 0
elif event.key == pygame.K_s:
snake_pos["x_change"] = 0
snake_pos["y_change"] = 10
elif event.key == pygame.K_w:
snake_pos["x_change"] = 0
snake_pos["y_change"] = -10
# snake location
snake_pos["x"] += snake_pos["x_change"]
snake_pos["y"] += snake_pos["x_change"]
# draw snake
pygame.draw.rect(display, (0, 255, 0), [snake_pos["x"], snake_pos["y"], 10, 10])
pygame.display.update()
# exit in every occasion
pygame.quit()
Answer the question
In order to leave comments, you need to log in
Why not do so?
import pygame
pygame.init()
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# display settings
width = 650
height = 480
display = pygame.display.set_mode((width, height))
pygame.display.update()
pygame.display.set_caption("Snake Game")
FPS = 60
clock = pygame.time.Clock()
# run loop
run = True
# snake settings
x = 240
y = 325
speed = 5
flR = flL = flUp = fldown = False
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
flR = True
flL = flUp = fldown = False
elif event.key == pygame.K_w:
flUp = True
flR = flL = fldown = False
elif event.key == pygame.K_s:
fldown = True
flR = flUp = flL = False
elif event.key == pygame.K_a:
flL = True
flR = flUp = fldown = False
# snake location
if (flL) and (x > 0):
x -= speed
elif (flR) and (x < width):
x += speed
elif (flUp) and (y > 0):
y -= speed
elif (fldown) and (y < height):
y += speed
display.fill(WHITE)
# draw snake
pygame.draw.rect(display, (0, 255, 0),
(x, y, 10, 10))
pygame.display.update()
clock.tick(FPS)
# exit in every occasion
pygame.quit()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question