Python Forum
[PyGame] Problem With Entering Game Loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Problem With Entering Game Loop
#1
I"m currently working on a small project for a computer class, in which we need to make a basic game. I'm using Thonny as well as the PyGame module.

The problem I'm facing is that the program starts fine, however when I click the "Play" button on the start menu (not in editor), instead of entering into the main game loop, the program closes instead.

Feedback would be appreciated, as even the teacher had no solution.

Thank you!

Code:

#-------------------------
#Snake Game Final Project
#Steven Bailey
#January 8th 2020
#-------------------------

#-------------------------
#Snake Game Final Project
#Steven Bailey
#January 8th 2020
#-------------------------

import pygame
import time
import random
#game initilization

pygame.init()
pygame.font.init()

clock = pygame.time.Clock()

def text_objects(text, font,):
    textSurface = font.render(text, True, white)
    return textSurface, textSurface.get_rect()

# Screen size
size = width, height = 500,500
win = pygame.display.set_mode((size))
pygame.display.set_caption("Snake by Steven Bailey")

#how to make the colours I want to use
red = pygame.Color(255, 0, 0)
bright_green = pygame.Color(0, 255, 0)
white = pygame.Color(255, 255, 255)
black = pygame.Color(0, 0, 0)
green = pygame.Color(0, 200, 0)
brown = pygame.Color(165, 42, 42)

#how to make a start menu
def game_intro():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        win.fill(black)
        largeText = pygame.font.Font('freesansbold.ttf',115)
        textSurf, textRect = text_objects("Snake", largeText)
        win.blit(textSurf, textRect)
        button("Start",150,250,100,50,green,bright_green,"play")  
        pygame.display.update()
        clock.tick(15)

#how to make a start button
def button(msg, x,y,w,h,ic,ac,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    print(click)
    if x+w > mouse[0] > x and x and y+h > mouse[1] > y:
        pygame.draw.rect(win, ac, (x,y,w,h))
        if click[0] == 1 and action != None:
            if action == "play":
                game_loop()
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(win, ac, (x,y,w,h))
    else:
        pygame.draw.rect(win, ic, (x,y,w,h))
    smallText = pygame.font.Font("freesansbold.ttf",20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ( (x + (w/2)), y+(h/2) )
    win.blit(textSurf, textRect)
       
#game over font and gameover function
def game_over():
    gameoverText = pygame.font.Font('freesansbold.ttf',75)
    textSurf, textRect = text_objects("GAME OVER", gameoverText,)
    win.blit(textSurf, textRect)
    time.sleep(4)
    pygame.quit()
    exit()

   
#how to show the score
def show_score(choice=1):
    pygame.font.init()
    SFont = pygame.font.SysFont('freesansbold.ttf', 32)
    Ssurf = SFont.render("Score  :  {0}".format(score), True, black)
    Srect = Ssurf.get_rect()
    if choice == 1:
        Srect.midtop = (80, 10)
    else:
        Srect.midtop = (320, 100)
    win.blit(Ssurf, Srect)
   
# FPS controller, controls the frames per second of the game
fpsController = pygame.time.Clock()

# Game settings
delta = 10
snakePos = [100, 50]
snakeBody = [[100, 50], [90, 50], [80, 50]]
foodPos = [400, 50]
foodSpawn = True
change_to = ''
direction = 'RIGHT'
score = 0
def game_loop():
    win.fill(black)
    while True:
        pygame.init()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()          
            elif event.type == pygame.KEYDOWN:
                changeto = ''
                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    change_to = 'RIGHT'
                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    change_to = 'LEFT'
                if event.key == pygame.K_UP or event.key == pygame.K_w:
                    change_to = 'UP'
                if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                    change_to = 'DOWN'
                if event.key == pygame.K_ESCAPE:
                    pygame.event.post(pygame.event.Event(pygame.QUIT))

    # Validate direction
        change_to = ''
        direction = 'RIGHT'
        if change_to == 'RIGHT' and direction != 'LEFT':
            direction = changeto
        if change_to == 'LEFT' and direction != 'RIGHT':
            direction = changeto
        if change_to == 'UP' and direction != 'DOWN':
            direction = changeto
        if change_to == 'DOWN' and direction != 'UP':
            direction = change_to

    # Update snake position
        delta = 10
        snakePos = [100, 50]
        if direction == 'RIGHT':
            snakePos[0] += delta
        if direction == 'LEFT':
            snakePos[0] -= delta
        if direction == 'DOWN':
            snakePos[1] += delta
        if direction == 'UP':
            snakePos[1] -= delta

    # Snake body mechanism
        snakeBody = [[100, 50], [90, 50], [80, 50]]
        snakePos = [100, 50]
        foodSpawn = True
        foodPos = [400, 50]
        snakeBody.insert(0, list(snakePos))
        if snakePos == foodPos:
            foodSpawn = False
            score += 1
        else:
            snakeBody.pop()
        if foodSpawn == False:
            foodPos = [random.randrange(1, width // 10) * delta, random.randrange(1, height // 10) * delta]
            foodSpawn = True
        for pos in snakeBody:
            pygame.draw.rect(win, green, pygame.Rect(pos[0], pos[1], delta, delta))
        pygame.draw.rect(win, brown, pygame.Rect(foodPos[0], foodPos[1], delta, delta))
        show_score
    # Bounds
        if snakePos[0] >= width or snakePos[0] < 0:
            game_over()
        if snakePos[1] >= height or snakePos[1] < 0:
            game_over()

    # Self hit
        for block in snakeBody[1:]:
            if snakePos == block:
                game_over()
        fpsController.tick(20)
game_intro()
game_loop()
Reply
#2
It's going straight to the game_over() on 174.
Reply
#3
(Jan-18-2020, 09:50 AM)michael1789 Wrote: It's going straight to the game_over() on 174.

Thanks for your response. How would I go about fixing this issue?
Reply
#4
On 137 AND on 149 you set snakePos = [100, 50]. This is also the same as your snakeBody, so
 for block in snakeBody[1:]:
            if snakePos == block:
will always be the case. And your snake can't move because every frame you set snakePos and snakeBody to the same thing. So the first thing to fix would be to not do this. I've never made a snake game, but my first impulse is to define these variables before the game loop starts, and not have your snake's head in the snakeBody list. The head can't collide with itself anyway, so there is no need for it there. As long as it's in there you'll trigger game over. I'm a newb to all this too, so the solution isn't immediately obvious to me, but I'm pretty sure this is the problem to solve.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Pygame display problem video game Paul_Maillet 1 612 Feb-20-2024, 07:50 PM
Last Post: Bronjer
  If 2nd input in the game is correct, replace with 1st input and loop the game tylerdurdane 11 4,030 Jul-17-2022, 04:55 AM
Last Post: deanhystad
  [PyGame] Problem when moving game window michael1789 15 8,594 Jan-17-2020, 01:40 PM
Last Post: metulburr
  Snake Game - obstacle problem Samira 3 5,426 Oct-31-2019, 02:58 PM
Last Post: Samira
  [PyGame] Game Logic problem with a "The Game of Life" Replication Coda 2 3,094 Dec-24-2018, 09:26 AM
Last Post: Coda
  [PyGame] Pong game key.event problem erickDarko 2 4,130 Dec-12-2018, 03:17 PM
Last Post: erickDarko
  [Tkinter] Loop help in game Kgranulo1 1 3,258 Feb-28-2017, 08:02 AM
Last Post: wavic

Forum Jump:

User Panel Messages

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