问题
I am doing a snake game(there is two snakes on the game) with pygame and i want to detect when the snake head collides with the another snake body, do that for both and a special case when the both heads collides, im doing currently the collision between the snake head and the other snake body, it works fine if one of the snakes is frozen and the other is moving, but if both is moving the collision just dont work heres the code that moves the snakes:
new_pos = None
if direction == 'DOWN':
new_pos = (snake[0][0], snake[0][1] + size)
if direction == 'UP':
new_pos = (snake[0][0], snake[0][1] - size)
if direction == 'LEFT':
new_pos = (snake[0][0] - size, snake[0][1])
if direction == 'RIGHT':
new_pos = (snake[0][0] + size, snake[0][1])
if new_pos:
snake = [new_pos] + snake
del snake[-1]
keep in mind that the code that movements the other snake is the same but snake turns into snake2, new_pos into new_pos2, etc
collision code:
if snake2[0] in snake[1:]:
gameOverBlue()
if snake2[0] in snake[1:]:
gameOverRed()
edit: i figured I should put the code that makes the snake too:
#snake
size = 15
s_pos = 60
snake = [(s_pos + size * 2, s_pos),(s_pos + size, s_pos),(s_pos, s_pos)]
s_skin = pygame.Surface((size, size))
s_skin.fill((82,128,208))
#snake2
size2 = 15
s2_pos = 195
snake2 = [(s2_pos + size2 * 2, s2_pos),(s2_pos + size2, s2_pos),(s2_pos, s2_pos)]
s2_skin = pygame.Surface((size2, size2))
s2_skin.fill((208,128,82))
回答1:
You need to evaluate whether the head of snake
is in the list snake2
, including the head of snake2
:
if snake[0] in snake2:
gameOverBlue()
and if the head of snake2
is in snake
:
if snake2[0] in snake:
gameOverRed()
If you want to detect if the heads of the snakes are colliding the you have to compare snake[0]
and snake2[0]
separately:
if snake[0] == snake2[0]:
print("heads are colliding")
if snake[0] in snake2[1:]:
gameOverBlue()
if snake2[0] in snake[1:]:
gameOverRed()
来源:https://stackoverflow.com/questions/64539458/why-collision-between-two-moving-objects-on-pygame-dont-work