添加到列表中的Snake游戏问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了添加到列表中的Snake游戏问题相关的知识,希望对你有一定的参考价值。
我正在尝试制作我的第一款游戏,所以我认为蛇游戏是一个很好的可行挑战(猜想我错了)。
问题似乎是,当我将蛇形部分附加到包含所有部分的身体列表时,似乎要多次附加。这使得所有零件都处于同一位置,并且失去了整个“蛇形”主体的其余部分。我将如何解决此问题,或者代码中还有其他问题。
import pygame
pygame.init()
class Cube():
pos = [0, 0]
def __init__(self, x, y, color=(255, 0, 0)):
self.color = color
self.pos[0] = x
self.pos[1] = y
def draw(self):
x = (self.pos[0] * xSizeBtwn) + 2
y = (self.pos[1] * ySizeBtwn) + 2
pygame.draw.rect(win, self.color, (x, y, xSizeBtwn - 2, ySizeBtwn - 2))
pygame.display.update()
class Snake():
body = []
pos = []
def __init__(self, color=(255, 0, 0)):
self.color = color
self.dirx = 1
self.diry = 0
self.length = 10
self.pos = [3, 3]
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.dirx = -1
self.diry = 0
print("moved a")
elif keys[pygame.K_d]:
self.dirx = 1
self.diry = 0
print("moved d")
elif keys[pygame.K_w]:
self.diry = -1
self.dirx = 0
print("moved s")
elif keys[pygame.K_s]:
self.diry = 1
self.dirx = 0
print("moved s")
self.newPosX = self.pos[0] + self.dirx
self.newPosY = self.pos[1] + self.diry
self.pos[0] = self.newPosX
self.pos[1] = self.newPosY
present = True
for b in self.body:
print(b.pos, self.newPosX, self.newPosY)
if b.pos[0] == self.newPosX and b.pos[1] == self.newPosY:
print("true")
present = False
# the problem is right here (i think)
if present:
self.body.append(Cube(self.newPosX, self.newPosY, self.color))
if len(self.body) > self.length:
self.body.pop(0)
def draw(self):
for b in self.body:
b.draw()
print(b.pos)
def drawAll():
win.fill((30, 30, 30))
drawGrid()
pygame.display.update()
def drawGrid():
x = 0
y = 0
for n in range(rows - 1):
y += ySizeBtwn
pygame.draw.line(win, (255, 255, 255), (0, (int)(y)), (gameHeight, (int)(y)))
for n in range(columns - 1):
x += xSizeBtwn
pygame.draw.line(win, (255, 255, 255), ((int)(x), 0), ((int)(x), gameWidth))
def main():
global gameWidth, gameHeight, columns, rows, xSizeBtwn, ySizeBtwn, win
gameWidth = 500
gameHeight = 500
columns = 15
rows = 15
xSizeBtwn = gameWidth / columns
ySizeBtwn = gameHeight / rows
win = pygame.display.set_mode((gameWidth, gameHeight))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
run = True
snake = Snake()
while run:
pygame.time.delay(100)
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
drawAll()
snake.move()
snake.draw()
main()
pygame.quit()
抱歉,代码混乱,我才开始编程。
此外,如果您有任何提示,那将非常有帮助。
答案
以下初始化可能未按照您认为的方式执行:these variables will be shared across classes。
class Cube():
pos = [0, 0]
...
class Snake():
body = []
pos = []
...
相反,您应该按如下所示在__init__
函数中初始化这些变量:
class Cube:
def __init__(self, x, y, color=(255, 0, 0)):
self.pos = [0, 0]
self.color = color
self.pos[0] = x
self.pos[1] = y
...
class Snake:
def __init__(self, color=(255, 0, 0)):
self.color = color
self.dirx = 1
self.diry = 0
self.length = 10
self.pos = [3, 3]
self.body = []
结果
以上是关于添加到列表中的Snake游戏问题的主要内容,如果未能解决你的问题,请参考以下文章