我正在使用pygame库编写简单的蛇游戏。现在,我正在编写checkPosition()函数。它使用来自pygame的contains()方法。问题在于,它将坐标舞会作为循环的开始,并且没有更新。我该如何重置这些变量或进行更新?整个代码在这里:
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Snake Game using Pygame")
#colors (RGB code)
blue = (3, 119, 252)
yellow = [251, 255, 36]
gray = [48, 48, 47]
# Variables for control
# Speed of movement
vel = 10
# Snake width and height
width = 35
height = 35
#Snake spawn position
x = 25
y = 25
clock = pygame.time.Clock()
# Random coordinates for spawning snake "snack"
randomSnackX = random.randrange(0, 500, 20)
randomSnackY = random.randrange(0, 500, 20)
# Snack width and height - thickness
snackThickness = 10
# Variable for initial game loop
run = True
# Draw snack and snake
def drawInitialElements():
# Draw raadom snak position from variables
snack = pygame.draw.rect(screen, (255, 255, 255), [randomSnackX,randomSnackY,snackThickness,snackThickness])
#Draw snake
snake = pygame.draw.rect(screen, (255, 255, 255), (x, y, width, height))
return snake, snack
snake, snack = drawInitialElements()
def checkPosition():
if (snake.contains(snack)) == True:
print("Eated snack")
#Initial game loop
while run:
pygame.time.delay(100)
screen.fill((0, 0, 0))
# If quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#Controls
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
drawInitialElements()
checkPosition()
pygame.display.update()
pygame.quit()
感谢您的帮助,汤姆。
[要验证pygame.Rect
对象是否发生碰撞,必须使用pygame.Rect
:
colliderect
colliderect
返回一个包含蛇形矩形和小吃的元组。在全局名称空间中为返回值分配变量def checkPosition():
if snake.colliderect(snack):
print("Eated snack")
和drawInitialElements
:
snake
完整的应用程序代码:
snack