Juan Jaramillo
Juan Jaramillo

Reputation: 67

How would I incorporate colliderect into a Snake Game?

Let me start off by saying I'm not an amazing coder so the code is not the prettiest. I'm working on a really basic version of snake right now. Currently I'm stumped on the collision between the snake and the food. (x,y for snake and foodx, foody for the food). The Collision Detection is just flat out not working right now and I can't figure out what is wrong with it. Thanks in advance for any help. Please keep it as simple as possible, don't want to get into any classes as I have no idea how to use those yet.

Edit: Sorry, English is not my first language. The code is functional right now. The collision and food generation after the collision with the food is not working.

import pygame
import sys
import random
import math
import time

pygame.init()
screen=pygame.display.set_mode((500,500))

red=(255,0,0)
blue=(0,0,255)
green=(0,255,0)
black=(0,0,0)

block1=1
block2=0

count=0

screen.fill(black)


randStart=random.randint(0,25)

x=randStart*20
y=randStart*20
xd=20
yd=0

foodx=random.randint(0,480)
foody=random.randint(0,480)

snakecol=pygame.Rect(x,y,20,20)
foodcol=pygame.Rect(foodx,foody,20,20)




done=False
while not done:
    screen.fill(black)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True


#controls

    if block1==1:
        if(pygame.key.get_pressed()[pygame.K_a]):
            yd=0
            xd=-20
            block1=0
            block2=1

    if block1==1:
        if(pygame.key.get_pressed()[pygame.K_d]):
            yd=0
            xd=20
            block1=0
            block2=1
    if block2==1:        
        if(pygame.key.get_pressed()[pygame.K_w]):
            xd=0
            yd=-20
            block1=1
            block2=0
    if block2==1:
        if(pygame.key.get_pressed()[pygame.K_s]):
            xd=0
            yd=20
            block1=1
            block2=0


#stop moving paddle

    if x<-20:
        x=500
    if x>500:
        x=-20
    if y<-20:
        y=500
    if y>500:
        y=-20

#food
    if snakecol.colliderect(foodcol):
        foodx=random.randint(0,480)
        foody=random.randint(0,480)





    x=x+xd
    y=y+yd



    pygame.draw.rect(screen,(255,255,255),(foodx,foody,20,20),0)
    pygame.draw.rect(screen,(255,255,255),(x,y,20,20),0)
    pygame.display.flip()



    time.sleep(0.4)
    count+=1
pygame.quit()

Upvotes: 0

Views: 81

Answers (1)

marienbad
marienbad

Reputation: 1453

Change x=x+xd to snakecol.x += xd and the same for the y part. Then in the draw part use snakecol as the rect rather than x,y,20,20 as now. The problem is that you never update the snake rect position. Sorry for formatting, am at work and on tablet.

Upvotes: 1

Related Questions