1

I'm trying to experiment with pygame and I am creating a simple prototype game.

I need some help with collision for a player rect and a "food" rect. I am trying to make a simple game that has a player and a food object. the food object's location is randomized when the game starts

class Food(Player):
    def __init__(self):
        super().__init__()
        self.rand_x = random.randint(0, width)
        self.rand_y = random.randint(0, height)
        self.food = pg.Rect(self.rand_x,
                            self.rand_y,
                            15, 15)
    ...

this food class contains a function that handles the collision of the player and food, if the player collides with the food, the location of the food changes again

    def playerCollision(self):
        if self.sprite.colliderect(self.food) or self.food.colliderect(self.sprite):
            self.food.x = self.rand_x
            self.food.y = self.rand_y

Here's my player class

class Player:
    def __init__(self):
        self.sprite = pg.Rect(x, y, 50, 50)

    def handle_keys(self):
        keys = pg.key.get_pressed()
        if keys[pg.K_w]:
            self.sprite.move_ip(0, -velocity)
        elif keys[pg.K_a]:
            self.sprite.move_ip(-velocity, 0)
        elif keys[pg.K_s]:
            self.sprite.move_ip(0, velocity)
        elif keys[pg.K_d]:
            self.sprite.move_ip(velocity, 0)

    def draw(self, surface):
        pg.draw.rect(surface, spriteColors[0], self.sprite)

and heres the full food class

class Food(Player):
    def __init__(self):
        super().__init__()
        self.rand_x = random.randint(0, width)
        self.rand_y = random.randint(0, height)
        self.food = pg.Rect(self.rand_x,
                            self.rand_y,
                            15, 15)

    def randomize_pos(self):  # debugger function to test randomized food locations
        self.food.x = random.randint(0, width)
        self.food.y = random.randint(0, height)
        self.drawFood(screen)

    def playerCollision(self):
        if self.sprite.colliderect(self.food) or self.food.colliderect(self.sprite):
            self.food.x = self.rand_x
            self.food.y = self.rand_y

    def drawFood(self, surface):
        pg.draw.rect(surface, spriteColors[1], self.food)

I've looked everywhere for solutions and implementing solutions into my code but none work.

Heres the full code if you all need it

import pygame as pg
from pygame.locals import *
import sys, random

pg.init()

# Setup and screen properties
pg.display.set_caption("prototype \u2014 game")
width, height = (800, 600)
screen = pg.display.set_mode([width, height])
spriteColors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]  # Red, Green, Blue

x = 25
y = 25
velocity = 5

class Player:
    def __init__(self):
        self.sprite = pg.Rect(x, y, 50, 50)

    def handle_keys(self):
        keys = pg.key.get_pressed()
        if keys[pg.K_w]:
            self.sprite.move_ip(0, -velocity)
        elif keys[pg.K_a]:
            self.sprite.move_ip(-velocity, 0)
        elif keys[pg.K_s]:
            self.sprite.move_ip(0, velocity)
        elif keys[pg.K_d]:
            self.sprite.move_ip(velocity, 0)

    def draw(self, surface):
        pg.draw.rect(surface, spriteColors[0], self.sprite)

class Food(Player):
    def __init__(self):
        super().__init__()
        self.rand_x = random.randint(0, width)
        self.rand_y = random.randint(0, height)
        self.food = pg.Rect(self.rand_x,
                            self.rand_y,
                            15, 15)

    def randomize_pos(self):  # debugger function to test randomized food locations
        self.food.x = random.randint(0, width)
        self.food.y = random.randint(0, height)
        self.drawFood(screen)

    def playerCollision(self):
        if self.sprite.colliderect(self.food) or self.food.colliderect(self.sprite):
            self.food.x = self.rand_x
            self.food.y = self.rand_y

    def drawFood(self, surface):
        pg.draw.rect(surface, spriteColors[1], self.food)


# Initialize Player and Food Object
player = Player()
food = Food()
clock = pg.time.Clock()

# Game Loop
while True:
    for event in pg.event.get():
        if event.type == QUIT:
            pg.quit()
            sys.exit()

        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                pg.quit()
                sys.exit()

    screen.fill((0, 0, 0))

    player.handle_keys()
    player.draw(screen)
    food.drawFood(screen)
    food.playerCollision()
    pg.display.update()

    clock.tick(60)
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
drxjason
  • 13
  • 2

1 Answers1

0

I recommend reading How do I detect collision in pygame?. In your particular code, player and food are different objects. player.sprite is not the same as food.sprite. The inheritance from Player in Food is useless, remove it. You must pass the player object to the playerCollision method of the food object:

class Food():
    def __init__(self):
        self.food = pg.Rect(0, 0, 15, 15)
        self.randomize_pos()

    def randomize_pos(self):
        self.food.x = random.randint(0, width)
        self.food.y = random.randint(0, height)

    def playerCollision(self, player):
        if player.sprite.colliderect(self.food):
            self.randomize_pos()

    def drawFood(self, surface):
        pg.draw.rect(surface, spriteColors[1], self.food)
# Initialize Player and Food Object
player = Player()
food = Food()
clock = pg.time.Clock()

# Game Loop
while True:
    for event in pg.event.get():
        if event.type == QUIT:
            pg.quit()
            sys.exit()

        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                pg.quit()
                sys.exit()

    screen.fill((0, 0, 0))

    player.handle_keys()
    player.draw(screen)
    food.drawFood(screen)
    food.playerCollision(player)     # <-- detect collision between food and player 
    pg.display.update()

    clock.tick(60)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • that seemed to work just perfectly, I just imagined I would use inheritance to try to make it work but I was wrong, thanks for your help – drxjason Mar 13 '22 at 20:09