我现在正在Pygame中制作蛇。我的想法是让ir增长,我会列出他的所有位置,每当他吃苹果时,我会附加另一个pygame.Surface,并在最后一个位置后面的坐标上显示它。我遇到了一只奇怪的虫子,它使蛇的速度比以前快了一倍。你能帮助我吗? 这是我的代码:
import pygame, math, random
pygame.init()
screen = pygame.display.set_mode((640,640))
pygame.display.set_caption('Snake')
score = 0
x, y = 320,320
dx,dy = 32,32
running = True
dirUp, dirDown = False, False
dirLeft, dirRight = False, True
body = [(x,y)]
pos = []
squares = []
for i in range(640):
if i % 32 == 0:
squares.append(i)
food = pygame.image.load('fruit.png')
foodx,foody = random.choice(squares), random.choice(squares)
def isCollision(obsX, obsY, x, y):
return math.sqrt(math.pow(obsX - x, 2) + math.pow(obsY - y, 2)) <= 0
def show_text():
score_font = pygame.font.Font('freesansbold.ttf',32)
score_text = score_font.render('Score: {}'.format(score), True, (255,255,255))
screen.blit(score_text, (0,0))
def remove_duplicates(listy):
new_listy = []
for item in listy:
if item not in new_listy:
new_listy.append(item)
return new_listy
def move():
global x,y
if dirUp:
y -= dy
elif dirDown:
y += dy
elif dirRight:
x += dx
elif dirLeft:
x -= dx
clock = pygame.time.Clock()
while running:
clock.tick(10)
screen.fill((0,128,0))
body[0] = (x,y)
snakeImg = [pygame.image.load('snakeblock.png') for i in range(len(body))]
if x > 608 or x < 0:
running = False
elif y > 608 or y < 0:
running = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
dirUp = True
dirLeft = dirDown = dirRight = False
if event.key == pygame.K_DOWN:
dirDown = True
dirUp = dirLeft = dirRight = False
if event.key == pygame.K_RIGHT:
dirRight = True
dirUp = dirDown = dirLeft = False
if event.key == pygame.K_LEFT:
dirLeft = True
dirUp = dirDown = dirRight = False
for i in range(len(body)):
if isCollision(foodx,foody,body[i][0],body[i][1]):
foodx, foody = random.choice(squares), random.choice(squares)
score += 1
body.insert(0,pos[-2])
move()
pos.append((x,y))
screen.blit(food, (foodx, foody))
screen.blit(snakeImg[i], (body[i][0], body[i][1]))
pos = remove_duplicates(pos)
show_text()
pygame.display.update()
让其他人知道如何让蛇撞到墙上和他自己:
您的代码还将遇到其他问题,如不测试边缘碰撞和蛇形块碰撞。但这是一个起点
你的问题是,每当你有一个以上的块时,你都会在每个循环中多次移动起始块
下面是带注释的完整代码
相关问题 更多 >
编程相关推荐