我正在尝试做我的第一个游戏,所以我认为蛇游戏将是一个很好的可行的挑战(猜我错了)开始。你知道吗
问题似乎是,当我将蛇的一部分附加到包含所有部分的body列表时,它似乎会多次附加它。这使得所有的部分在同一个位置,它失去了“蛇”身体的整个休息。我该如何解决这个问题,或者代码有其他问题。你知道吗
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。你知道吗
相反,应该在
__init__
函数中初始化这些变量,如下所示:结果
相关问题 更多 >
编程相关推荐