我正在尝试在 pygame (python 3) 中重新创建蛇,我想做的是每一帧,通过检查按键来检查蛇的速度,但它很少意识到我正在按下一个键,我做错了什么/我应该怎么做(代码在下面),我不明白为什么这不起作用,因为其他所有东西都可以立即运行,例如 clear 函数,甚至 handle() 做的事情非常相似,所以它使得我不知道为什么它不起作用
import pygame
from pygame.locals import *
import math
import random
pygame.init()
display = pygame.display.set_mode((512, 512))
pygame.display.set_caption("Snake")
display.fill((255, 255, 255))
def handle():
global x, y
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
def make_apple():
x, y = random.randint(0, 502), random.randint(0, 502)
pygame.draw.rect(display, (255, 0, 0), (x, y, 10, 10))
return x, y
# -- COLLISION DETECTION -- #
def r(fox, foy, cR, sox, soy):
dx = abs(fox - sox)
dy = abs(foy - soy)
if dx < cR and dy < cR:
return True
else:
return False
def clear(aX, aY):
global x, y
display.fill((255, 255, 255))
pygame.draw.rect(display, (255, 0, 0), (aX, aY, 10, 10))
draw_snake(x, y)
def draw_snake(x, y):
pygame.draw.rect(display, (0, 255, 0), (x, y, 10, 10))
def set_vel():
for event in pygame.event.get():
if event.type == KEYDOWN:
print("KEY")
if event.key == K_LEFT:
yVel = 0
xVel = -1
elif event.key == K_RIGHT:
yVel = 0
xVel = 1
elif event.key == K_UP:
yVel = -1
xVel = 0
elif event.key == K_DOWN:
yVel = 1
xVel = 0
return xVel, yVel
return 0, 0
def update_pos(x, y, xV, yV):
x += xV
y += yV
return x, y
aX, aY = make_apple()
x, y = 256, 256
length = 1
eaten = False
while True:
velX, velY = set_vel()
clear(aX, aY)
handle()
x, y = update_pos(x, y, velX, velY)
if eaten:
aX, aY = make_apple()
eaten = False
pygame.display.update()
if r(x, y, 3, aX, aY):
display.fill((255, 255, 255))
eaten = True
暮色呼如
紫衣仙女
相关分类