1

I am creating a game with pygame & python 3.10.0 using VSCode everything is working fine but this if statement stops working after sometime and the font doesn't draw but I can't pinpoint the problem for that , for the if statement it usually runs till 10 or 11 score but it can be quicker like 2:

 if player.rect.colliderect(food):
    pygame.sprite.Sprite.kill(food)
    food.rect.x = random.randrange(20, 1700)
    food.rect.y = random.randrange(20, 860)
    all_sprites_list.add(food)
    score += 1
    print(score)

whole code:

import pygame
import sys
import time
import random
import ctypes

from ctypes import wintypes
from pygame import sprite
from pygame.draw import rect
from pygame.event import pump, wait
from pygame import font
pygame.font.init()

myappid = 'elementalstudios.snake.Alpha 0_1' # arbitrary string
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)


#------ Initialize Variables------#
# Player
player_width = 20
player_height = 20
# Food
food_width = 10
food_height = 10
# Colours
seafoam_gr = (159, 226, 191)
black = (0, 0, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
green = (0, 255, 0)
white = (255, 255, 255)
# Score 
score = 0

#------ Score Font Initialize ------#
font = pygame.font.Font(None, 50)
text = font.render("Score:", False, white, None)

#------Sprites Class------#
class Sprite(pygame.sprite.Sprite):
    def __init__(self, color, height, width):
        super().__init__()

        self.image = pygame.Surface([width, height])
        self.image.fill(seafoam_gr)
        self.image.set_colorkey(black)

        pygame.draw.rect(self.image,
                         color,
                         pygame.Rect(0, 0, width, height))
  
        self.rect = self.image.get_rect()

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

    def moveUp(self, speed):
        self.rect.y -= speed * speed / 5

    def moveDown(self, speed):
        self.rect.y += speed * speed / 5

#------ Font Class ------#
def create_font(t,s = 24, colour_font = white, bold = False, italic = False):
    font = pygame.font.Font("prstart.ttf", s, bold, italic)
    text = font.render(t, True, colour_font)
    return text

#------ Initialize Pygame and Window------#
pygame.init()

icon = pygame.image.load('Icon.ico')
pygame.display.set_icon(icon)
gameDisplay = pygame.display.set_mode((1920,1080), pygame.FULLSCREEN)
#rect = pygame.Rect( * gameDisplay.get_rect().center, 0, 0).inflate(100, 100)
pygame.display.set_caption("Blocky")
gameDisplay.fill(black)
clock = pygame.time.Clock()
running = True

#------Initialize Sprites------#
all_sprites_list = pygame.sprite.Group()
player = Sprite(seafoam_gr, player_height, player_width)
food = Sprite(red, food_height, food_width)
player.rect.x = 960
player.rect.y = 540
food.rect.x = 20 #random.randrange(20, 1800)
food.rect.y = 30 #random.randrange(20, 1050)

#------Add Sprites to sprite list------#
all_sprites_list.add(player)
all_sprites_list.add(food)

clock = pygame.time.Clock()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    #------Eating------#
    if player.rect.colliderect(food):
        pygame.sprite.Sprite.kill(food)
        food.rect.x = random.randrange(20, 1700)
        food.rect.y = random.randrange(20, 860)
        all_sprites_list.add(food)
        score += 1
        print(score)

    #------ Score Draw ------#
    text_rect = text.get_rect()
    text_rect.center = (100, 150)

    gameDisplay.blit(text, text_rect)
    #------Key Movement------#
    keys = pygame.key.get_pressed()
    # Move Left
    if keys[pygame.K_a]:
        player.moveLeft(3)
        if keys[pygame.K_LCTRL]:
            player.moveLeft(5)
    if keys[pygame.K_LEFT]:
        player.moveLeft(3)
        if keys[pygame.K_LCTRL]:
            player.moveLeft(5)
    # Move Right
    if keys[pygame.K_d]:
        player.moveRight(5)
        if keys[pygame.K_LCTRL]:
            player.moveRight(5)
    if keys[pygame.K_RIGHT]:
        player.moveRight(3)
        if keys[pygame.K_LCTRL]:
            player.moveRight(5)
    # Move Down
    if keys[pygame.K_s]:
        player.moveDown(3)
        if keys[pygame.K_LCTRL]:
            player.moveDown(5)
    if keys[pygame.K_DOWN]:
        player.moveDown(3)
        if keys[pygame.K_LCTRL]:
            player.moveDown(5)
    # Move Up
    if keys[pygame.K_w]:
        player.moveUp(3)
        if keys[pygame.K_LCTRL]:
            player.moveUp(5)
    if keys[pygame.K_UP]:
        player.moveUp(3)
        if keys[pygame.K_LCTRL]:
            player.moveUp(5)

    all_sprites_list.update()
    gameDisplay.fill(black)
    all_sprites_list.draw(gameDisplay)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

1

It is not necessary to kill the food object. It is sufficient to change the position of the food. pygame.sprite.Sprite.kill just removes the Sprite object from all Gorups. So there is no point in calling kill and then adding the object back to the Group.

The text does not show up, because you draw it before you clear the display. pygame.Surface.fill fills the Surface with a solid color. Everything that was previously drawn will be cleared. blit the text after fill.
You will have to render the text Surface again if the score has changed.

I recommend simplifying the code that moves the player. See How can I make a sprite move when key is held down.

class Sprite(pygame.sprite.Sprite):
    def __init__(self, color, x, y, height, width):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.image.set_colorkey(black)
        self.rect = self.image.get_rect(topleft = (x, y))
        self.x, self.y = self.rect.x, self.rect.y

    def move(self, move_x, move_y, speed_up):
        if move_x or move_y:
            direction = pygame.math.Vector2(move_x, move_y)
            direction.scale_to_length(5 if speed_up else 3)
            self.x += direction.x
            self.y += direction.y
            self.rect.x, self.rect.y = round(self.x), round(self.y)
player = Sprite(seafoam_gr, 400, 300, player_height, player_width)
food = Sprite(red, 20, 30, food_height, food_width)
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    if player.rect.colliderect(food):
        food.rect.x = random.randrange(20, 780)
        food.rect.y = random.randrange(20, 580)
        score += 1

        # render text
        text = font.render("Score: " + str(score), False, white, None)

    keys = pygame.key.get_pressed()
    move_x = ((keys[pygame.K_d] or keys[pygame.K_RIGHT]) - (keys[pygame.K_a] or keys[pygame.K_LEFT]))
    move_y = ((keys[pygame.K_s] or keys[pygame.K_DOWN]) - (keys[pygame.K_w] or keys[pygame.K_UP]))
    player.move(move_x, move_y, keys[pygame.K_LCTRL])

    all_sprites_list.update()
    
    gameDisplay.fill(black)

    # draw text
    gameDisplay.blit(text, text.get_rect(center = (100, 150)))
    
    all_sprites_list.draw(gameDisplay)
    pygame.display.flip()

    clock.tick(60)

pygame.quit()
quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174