如何解决蛇壁传送的bug

zac*_*zac 6 python pygame collision-detection

我正在做一个蛇游戏,我遇到了一个我不知道如何解决的错误,我想让我的蛇传送槽墙,当蛇与墙壁碰撞时,它以相反的速度和位置传送到另一个墙壁,就像经典游戏一样,但是使用我的代码,当蛇靠近墙壁时,它会复制到对面的墙壁,但它甚至应该还没有检测到碰撞这幅画所显示的方式

重要的是:在网格中,蛇在墙的一侧,像这样

SSSS
WWWW
Run Code Online (Sandbox Code Playgroud)

而不是这样:

SSSS
NNNN
WWWW
Run Code Online (Sandbox Code Playgroud)

当S代表蛇,W代表墙,N代表无。

编辑:整个代码

SSSS
WWWW
Run Code Online (Sandbox Code Playgroud)

编辑:红点是食物/苹果

Rab*_*d76 4

您想要实现一个传送器。因此,一旦蛇越过窗户边缘,你就必须传送到另一边。您的窗口大小为 1020x585。如果x == -15y == -15x == 1020y == 585 ,蛇就在窗外,因此你必须执行以下传送:

  • 如果x = 1020传送到x = 0
  • 如果x = -15传送到x = 1005
  • 如果y = 585传送到y = 0
  • 如果y = -15传送到y = 570
_pos = None
if snake[0][0] == -15:
    _pos = (1005, snake[0][1])
elif snake[0][1] == -15:
    _pos = (snake[0][0], 570)
elif snake[0][0] == 1020:
    _pos = (0, snake[0][1])
elif snake[0][1] == 585:
    _pos = (snake[0][0], 0)
if _pos:
    snake = [_pos] + snake
    del snake[-1]
Run Code Online (Sandbox Code Playgroud)

另一个最简单的解决方案是使用%(模)运算符:

x1 = (x1 + x1_change) % dis_width
y1 = (y1 + y1_change) % dis_height
Run Code Online (Sandbox Code Playgroud)
>>> width = 100
>>> 101 % width
1
>>> -1 % width
99
>>>
Run Code Online (Sandbox Code Playgroud)

最小的例子: repl.it/@Rabbid76/PyGame-ContinuousMovement

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            print(pygame.key.name(event.key))

    keys = pygame.key.get_pressed()
    
    dx = (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
    dy = (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
        
    rect.centerx = (rect.centerx + dx) % window.get_width()
    rect.centery = (rect.centery + dy) % window.get_height()

    window.fill(0)
    pygame.draw.rect(window, (255, 0, 0), rect)
    pygame.display.flip()

pygame.quit()
exit()
Run Code Online (Sandbox Code Playgroud)

笔记:

>>> width = 100
>>> 101 % width
1
>>> -1 % width
99
>>>
Run Code Online (Sandbox Code Playgroud)