我正在尝试使用pygame在python中制作一个蛇游戏...一个可以移动并吃东西的蛇游戏。但是,无论何时“蛇”在它上面移动,我似乎都无法移动Cookie。
我试图建立一个不等式来比较食物的位置和蛇的位置,但是它不起作用...
xls = pd.ExcelFile(fileIn)
df = xls.parse(tab)
df['Citation'] = df['Citation'].fillna(value='tbd')
df.Citation = df.Citation.map(unicode)
我再次希望蛇在曲奇上方移动时可以移动到另一个位置
答案 0 :(得分:1)
如评论中所述,Pygame具有用于detecting collision between rectangles的方法。幸运的是,您可以使用blit方法returns a Rect object。这意味着,当您在屏幕上绘制蛇面和食物图像时,可以保留这些返回值,并使用它们来检测蛇和食物之间的碰撞。
这里有一个简短的代码片段来说明我在说什么。
您可以将主循环中的绘图代码更改为此:
gameDisplay.fill((0,0,0))
snakeRect = gameDisplay.blit(snakeFace,(x, y))
food1Rect = gameDisplay.blit(food1, (foodPositions[0], foodPositions[1]))
food2Rect = gameDisplay.blit(food2, (foodPositions[2], foodPositions[3]))
food3Rect = gameDisplay.blit(food3, (foodPositions[4], foodPositions[5]))
checkForConsumption() # Note: It is important that you check for consumption after the food and snake have been drawn, as drawing updates their rectangles
pygame.display.update()
然后,您的checkForConsumption
方法变得更加简单:
def checkForConsumption():
if snakeRect.coliderect(food1Rect):
# Recalculate the new position of the food just as you did
foodPositions[0] = random.randrange(1, 40, 1) * 10
foodPositions[1] = random.randrange(1, 40, 1) * 10
# Additionally, redraw the food at its new location
gameDisplay.blit(food1, (foodPositions[0], foodPositions[1]))
# Check each of the other pieces of food just as you did the first
此方法使您可以利用Pygame内置的方法,这样就不必在碰撞检测方法的实现细节中迷失方向,同时仍将自定义图像用于蛇头和食物。尽管可以(虽然不太困难)编写自己的碰撞检测方法,但这种方法更加简洁,并使用了Pygame提供的工具。
答案 1 :(得分:0)
我已经在我的项目中做到了:
def collision_check(enemy_list, player_pos):
for enemy_pos in enemy_list:
if detect_collision(enemy_pos, player_pos):
return True
return False
def detect_collision(player_pos, enemy_pos):
p_x = player_pos[0]
p_y = player_pos[1]
e_x = enemy_pos[0]
e_y = enemy_pos[1]
if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x + enemy_size)):
if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y + enemy_size)):
return True
return False