Python Forum
[PyGame] Cannot display anything inside pygame window
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Cannot display anything inside pygame window
#1
Hello,

Long story short...I'm on my trip to learn programming. Recently I've bought a python book as a starting point. I've got some basics covered and at the end of the course plan was to write "snake" game - the same game as we know from Nokia 3310.
The code below is taken straight from the book.

Below is the code:

import pygame

pygame.init()

CUBE_SIZE = 25
CUBES_NUM = 20
WIDTH = CUBE_SIZE * CUBES_NUM
screen = pygame.display.set_mode((WIDTH, WIDTH))   # here's the size of pygame window

GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
screen.fill(WHITE)
pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()


def draw_snake_part(x, y):
    position = (x * CUBE_SIZE, y * CUBE_SIZE, CUBE_SIZE, CUBE_SIZE)  # at this line I get error "This code is unreachable"
    pygame.draw.rect(screen, GREEN, position)
    pygame.display.update()


draw_snake_part(0, 0)
draw_snake_part(13, 16)
At this point my program should've opened pygame window with two squares displayed, instead blank white window is opened.

Could you take a look and suggest what's wrong with this code? Thanks in advance
Reply
#2
You never get here:
draw_snake_part(0, 0)
draw_snake_part(13, 16)
because you are stuck looping here:
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
If you reverse the order you should see something.

But this is not how you make a pygame. Instead of writeing functions like draw_snake_part() you should create a Sprite class that is a snake part, create multiple sprites to make a snake, collect all the snake parts in a group, and write a function that moves the sprites in a coordinated way. Pygame will do take care of drawing the parts for you.

There are many examples of how to do this on the internet. Like this:

https://www.geeksforgeeks.org/pygame-creating-sprites/

And there are a ton of videos.
Reply
#3
Does it matter if a function is defined in the while loop? My preference has always been to define them outside of loops.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#4
The function is not defined in the while loop, it is defined below the while loop. It is a convention to put the functions at the top of a module, but python doesn't care. Functions are compiled when the file is imported the first time, not during runtime, so it wouldn't matter if the function was defined in a loop.

Here's an example of how a snake game might be structured:
import pygame
from random import randint
 
CUBE_SIZE = 25
CUBES_NUM = 20
WIDTH = CUBE_SIZE * CUBES_NUM
 
 
class Segment(pygame.sprite.Sprite):
    """A segment of a snake"""
    def __init__(self, pos=(0, 0), color="green"):
        super().__init__()
        self.rect = pygame.Rect(0, 0, CUBE_SIZE, CUBE_SIZE)
        self.image = pygame.surface.Surface(self.rect.size)
        self.image.fill(color)
        self.at(list(pos))
 
    def at(self, position):
        """Set my grid location."""
        self.pos = position
        self.rect.x = self.pos[0] * CUBE_SIZE
        self.rect.y = self.pos[1] * CUBE_SIZE
 
    def draw(self, screen):
        """Draw self on screen."""
        screen.blit(self.image, self.rect)
 
 
class Food(Segment):
    """Something to eat."""
    def __init__(self):
        """I randomly place myself on the screen."""
        super().__init__([randint(1, CUBES_NUM - 2), randint(1, CUBES_NUM - 2)], "blue")
 
 
class Snake(pygame.sprite.Group):
    """A group of segments that moves in a coordinated fasion."""
    directions = ((1, 0), (0, 1), (-1, 0), (0, -1))
    colors = ("green", "yellow")
 
    def __init__(self, segments):
        """Initialize the sname.  segments is list of grid coordinates."""
        super().__init__()
        color = "red"
        for i, segment in enumerate(segments, start=1):
            self.add(Segment(segment, color))
            color = self.colors[i % len(self.colors)]
        self.head = self.sprites()[0]
        self.direction = 0
        self.add_segment = False
        self.score = 0
 
    def turn(self, turn):
        """Turn the snake left (-1) or right (1)."""
        self.direction = (self.direction + turn) % len(self.directions)
 
    def update(self):
        """Update all the segment positions."""
        segments = self.sprites()[::-1]
        if self.add_segment:
            # New segment is at the tail end of the snake.
            self.add_segment = False
            self.add(Segment(segments[0].pos, self.colors[len(segments) % 2]))
 
        # Move all the snake sgments.  Starting at the tail each segment moves
        # to the previous location of the next segment.
        for a, b in zip(segments, segments[1:]):
            a.at(b.pos)
        delta = self.directions[self.direction]
        self.head.at([self.head.pos[0] + delta[0], self.head.pos[1] + delta[1]])
 
        # Check if the snake hit a wall
        pos = snake.head.pos
        if min(pos) < 0 or max(pos) >= CUBES_NUM:
            self.kill()
            return
 
        # Check if snake bit itself.
        for segment in segments[:-1]:
            if segment.pos == pos:
                self.kill()
                return
 
    def eats(self, food):
        """Return True if snake eats food."""
        if len(self) > 0 and self.head.pos == food.pos:
            self.score += 1
            food.kill()
            self.add_segment = True  # Snake grows longer when it eats.
            return True
        return False
 
    def kill(self):
        """Kill all the segments."""
        for segment in self.sprites():
            segment.kill()
 
 
pygame.init()
screen = pygame.display.set_mode((WIDTH, WIDTH))
clock = pygame.time.Clock()
snake = Snake([(x, 10) for x in range(10, 16)])
snake.direction = 2
food = Food()
speed = 4
while len(snake) > 0:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            snake.kill()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                snake.turn(-1)
            elif event.key == pygame.K_RIGHT:
                snake.turn(1)
 
    snake.update()
    if snake.eats(food):
        speed += 1
        food = Food()
 
    screen.fill("white")
    food.draw(screen)
    snake.draw(screen)
    pygame.display.update()
    clock.tick(speed)

print("Your score =", snake.score)
I left out all the challenging parts like multiple plays and leaderboards, but it is enough to give you an idea about how a snake like game can be designed. You don't have to use sprites and groups, but I think programming a game is much simpler if you do.
Reply
#5
Hello again,

thank you very much guys for your help. To be honest I want to follow instructions in my tutorial and do it the way it is suggested by the author.

@deanhystad changing order the way you suggested actually allowed program to display "squares" on the board. What you said about being stuck in the loop seems logical at this point. At the moment I will be moving on with the tutorial. What I also noticed there is a suggestion to swap squares with real sprites, and that's what I will try to do next after the game is up and running. "Rome wasn't built in a day" :)
Reply
#6
Is it important whether a function is defined in the while loop? I've always preferred to specify things outside of loops.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] drawing images onto pygame window djwilson0495 1 3,508 Feb-22-2021, 05:39 PM
Last Post: nilamo
  [split] How to display isometric maps with pygame? mattwins 6 6,296 Nov-17-2020, 12:54 PM
Last Post: mattwins
  pygame get window position vskarica 3 5,952 Oct-18-2020, 05:14 PM
Last Post: nilamo
  Unable to exit Pygame window Hesper 2 3,904 Mar-30-2020, 08:59 AM
Last Post: Hesper
  [PyGame] How to Display pygame on SSD1351 screen kalihotname 0 1,893 Nov-11-2019, 07:32 AM
Last Post: kalihotname
  [pyGame] More Text in one Window, example needed ! JamieVanCadsand 1 3,554 Oct-03-2017, 03:42 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020