'Snake on PyGame, does not eat food
Hello
The main part
I'm trying to make a snake on Python.I am trying to make it so that when my snake (square) passes through the food. The food should disappear and be redrawn, but this does not happen.
Help me fix this. This is my first question here, I hope I asked it correctly.
import pygame
import random
import time
pygame.init()
W=800
H=600
red=(255,0,0)
zvet=(20,100,200)
screen=pygame.display.set_mode((W,H))
pygame.display.set_caption('Аоаоа')
WH=(255,255,255)
Ab=(0,200,200)
snake_bl=30
clok=pygame.time.Clock()
speed=5
x = W // 2
y = H // 2
#координаты еды
foodx = 100
foody = 100
move = 0
movey = 0
font=pygame.font.SysFont(None,50)
comand=True
def mes(msg):
mseg=font.render(msg,True,red)
screen.blit(mseg,[200,200])
while comand:
for event in pygame.event.get():
if event.type==pygame.QUIT:
quit()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_RIGHT:
move=speed
movey=0
elif event.key==pygame.K_LEFT:
move=-speed
movey=0
elif event.key==pygame.K_DOWN:
movey=speed
move=0
elif event.key == pygame.K_UP:
movey = -speed
move=0
if x<0 or x>W or y<0 or y>H:
comand=False
x+=move
y+=movey
screen.fill(Ab)
pygame.draw.rect(screen,WH,(foodx,foody,snake_bl,snake_bl))
pygame.draw.rect(screen,WH,(x,y,snake_bl,snake_bl))
pygame.display.update()
#There seems to be something wrong here
if x==foodx and y==foody:
foodx = round(random.randint(100, 500))
foody = round(random.randint(100, 500))
clok.tick(60)
mes('ТЫ проиграл')
pygame.display.update()
time.sleep(1)
pygame.quit()
Solution 1:[1]
You need to adapt your if-condition. Currently your testing if the x and y coordinates of the food and the snake are exactly equal. However, you need to test wether both rectangles collide and therefore take the width and height of the food / snake into account.
You can do this if you replace the if condition if x==foodx and y==foody: with this block of code:
food_rect = pygame.Rect(foodx, foody, snake_bl, snake_bl)
snake_rect = pygame.Rect(x,y,snake_bl,snake_bl)
if food_rect.colliderect(snake_rect):
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sven |
