Reputation: 35
hey guys i just programmed the snake game but i want when x=0(my snake is in position 0) then immediately x=600 like it doesn't have a collision wall getting in its way, how can i do it?
programming language: Python
the library i use is pygame
this is my code
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()
Upvotes: 2
Views: 527
Reputation: 210968
Use the %
(modulo) operator. The module operator computes the remainder of an integral division:
x = (x + x1_change) % 600
y = (y + y1_change) % 600
The actual problem in your code is that you set x = 600
, but you test x == 600
on the following line
if x == 0: x = 600 if x == 600: x = 0
If you want to implement it with conditions, you have to use 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
Upvotes: 2