如何让小蛇越过屏幕,它会return到屏幕的另一边

how to make the snake go beyond the screen, it will return to the other side of the screen

嘿伙计们,我刚刚编写了贪吃蛇游戏,但我想当 x=0(我的蛇在位置 0)时立即 x=600,就像它没有碰撞墙挡住它一样,我怎么能做吗?

编程语言:Python

我使用的库是pygame

这是我的代码

import pygame, time

pygame.init()
clock = pygame.time.Clock()
#màu
black = (0, 0, 0)
white = (255,252,252)
red = (176, 59, 19)

screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption('Snake game by Vinhsieucapvjppro')

x = 300
y = 300
x_size = 10
y_size = 10
x1_change = 0       
y1_change = 0
vel = 5

game = True
while game:
    print(screen)
    screen.fill(black)
    pygame.draw.rect(screen,red,(x,y,x_size,y_size))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game = False
    #di chuyển
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x1_change = -5
        y1_change = 0 
    if keys[pygame.K_RIGHT]:
        x1_change = 5
        y1_change = 0
    if keys[pygame.K_UP]:
        y1_change = -5
        x1_change = 0
    if keys[pygame.K_DOWN]:
        y1_change = 5
        x1_change = 0

    x += x1_change
    y += y1_change
    if x == 0:  #<---- ở đây có lỗi
        x = 600
    if x == 600:
        x = 0
    if y == 0:  #<---- ở đây có lỗi
        y = 600 
    if y == 600:
        y = 0
    pygame.display.flip()
    pygame.display.update()
    clock.tick(120)
    pygame.quit()

使用 %(取模)运算符。模块运算符计算整数除法的余数:

x = (x + x1_change) % 600
y = (y + y1_change) % 600

您代码中的实际问题是您设置了 x = 600,但您在下一行

测试了 x == 600
if x == 0: 
   x = 600
if x == 600:
   x = 0

如果要有条件的实现,就得用if-elif:

x += x1_change
y += y1_change

if x <= 0:
    x = 600
elif x >= 600:
    x = 0
    
if y <= 0:
    y = 600 
elif y >= 600:
    y = 0