好吧,运行代码会画出蛇,但我根本无法移动它。努力让蛇在开始移动时不会停下来。一般来说,我是编程新手,很抱歉,如果我很愚蠢,但看在上帝的份上,我不知道如何使这项工作有效,请帮忙。网格函数工作得很好,但移动函数根本不起作用。
这是代码
# Snake game
import pygame
pygame.init()
pygame.display.set_caption("Snake Game and AI")
WIDTH = 24
HEIGHT = 24
SCREEN = pygame.display.set_mode((500, 500))
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 128, 0)
WHITE = (255, 255, 255)
SPEED = 25
x_head = 251
y_head = 251
keys = pygame.key.get_pressed()
direction = None
def grid():
for x in range(25, 500, 25):
pygame.draw.rect(SCREEN, WHITE, (x, 25, 1, 450))
for y in range(25, 500, 25):
pygame.draw.rect(SCREEN, WHITE, (25, y, 450, 1))
def press_key():
global direction
global keys
if keys[pygame.K_RIGHT] and direction != 'left':
direction = 'right'
if keys[pygame.K_LEFT] and direction != 'right':
direction = 'left'
if keys[pygame.K_UP] and direction != 'down':
direction = 'up'
if keys[pygame.K_DOWN] and direction != 'up':
direction = 'down'
def move_snake():
global x_head
global y_head
global SCREEN
global WIDTH
global HEIGHT
while direction == 'right':
x_head += SPEED
while direction == 'left':
x_head -= SPEED
while direction == 'up':
y_head -= SPEED
while direction == 'down':
y_head += SPEED
pygame.draw.rect(SCREEN, GREEN, (x_head, y_head, WIDTH, HEIGHT))
is_running = True
while is_running:
pygame.time.delay(150)
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_running = False
press_key()
SCREEN.fill(BLACK)
grid()
move_snake()
pygame.display.update()
pygame.quit()
最佳答案
pygame.key.get_pressed()
返回键盘上每个键的状态列表。您必须检索每一帧中按键的当前状态:
is_running = True
while is_running:
pygame.time.delay(150)
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_running = False
# get current key states
keys = pygame.key.get_pressed() # <-----
press_key()
# [...]
此外,move_snake
在主应用程序循环中被调用。您根本不需要 move_snake
中的无限循环。将 while
循环更改为选择 (if
)。蛇在每一帧中迈出一步,具体取决于方向
的状态:
def move_snake():
global x_head
global y_head
global SCREEN
global WIDTH
global HEIGHT
if direction == 'right':
x_head += SPEED
if direction == 'left':
x_head -= SPEED
if direction == 'up':
y_head -= SPEED
if direction == 'down':
y_head += SPEED
关于python - python中的snake使用pygame模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59939602/