我想实现一个Snake游戏。该程序运行良好,直到蛇与食物碰撞并产生新的身体部位为止。我正在尝试通过以下步骤使此身体部位跟随我的玩家控制的蛇头(在代码中称为player
)
bodypart是在与头部相同的方向和速度的世界(屏幕)中创建并绘制的,位于头部的侧面(取决于蛇的来源)。这部分有效。
当检测到键盘输入时,将蛇的x和y位置记录在列表中,然后改变方向。这也可以。
身体部位继续移动,直到蛇的x和y坐标==身体部位的x和y坐标为止。在这种情况下,身体部位应改变方向并跟随蛇移动。这部分不起作用。 (身体部位继续移动超过记录的x / y坐标点,直到离开屏幕才改变方向)
'''
setup
'''
import pygame
import random
import sys
import os
lefta = pygame.K_LEFT
leftk = ord("a")
Black = [0,0,0]
counter = 0
bodypartspawn = "False"
player_locationx = []
player_locationy = []
worldx = 1600
worldy = 900
fps = 5
ani = 100
clock = pygame.time.Clock()
pygame.init()
world = pygame.display.set_mode([worldx, worldy])
class BodyPart(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.movex = player.movex
self.movey = player.movey
self.frame = 0
self.images = []
img = pygame.image.load(os.path.join('images','white_block.png')).convert()
self.images.append(img)
self.image = self.images[0]
self.image = pygame.transform.scale(self.image, (50, 50))
self.rect = self.image.get_rect()
def controlbodypart(self):
global counter
if self.rect.x == player_locationx[counter] and self.rect.y == player_locationy[counter]:
counter = counter +1
if direction == "left":
self.movex = -10
self.movey = 0
if direction == "right":
self.movex = 10
self.movey = 0
if direction == "up":
self.movex = 0
self.movey = -10
if direction == "down":
self. movex = 0
self.movey = 10
def updateofbodypart(self):
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
'''
Main Loop
'''
Main = True
while Main == True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if leftk == event.key and direction !="right" or lefta == event.key and direction !="right":
#this if statement is repeated for all four directions
direction = "left"
if bodypartspawn == "True":
player_locationx.append(player.rect.x) #player class is defined in my code, but i did not copy it here
player_locationy.append(player.rect.y)
#print (player_locationx) and
#print (player_locationy) were used to test if the lists work. They show the correct coordinates.
bodypart.controlbodypart()
player.control(-10, 0) #this changes direction of the snake head
if player.rect.colliderect(food.rect): #food class is defined in my code, but i have not copied it here
food.kill()
food = Food()
food.rect.x = random.randint(80, 1500)
food.rect.y = random.randint(80, 800)
player_list.add(food)
if direction == "left":
bodypart = BodyPart()
bodypart.rect.x = player.rect.x+50 #snake head and body are 50 pixels large, thats why i move it this distance to the side
bodypart.rect.y = player.rect.y
bodypartspawn = "True"
player.updateofplayer()
if bodypartspawn =="True":
player_list.add(bodypart)
bodypart.updateofbodypart()
world.fill (Black)
player_list.draw(world)
pygame.display.flip()
clock.tick(fps)
我尽力删除了与该问题无关的所有内容,但是我的代码相当复杂且杂乱无章,因此我可能已删除了一些对您的理解至关重要的内容。如果是这样,请告诉我,我会编辑。
再次:我没有收到任何错误消息,除了上述问题,其他所有东西都很好。