apples723
Posts: 80
Joined: Sat Jun 22, 2013 3:13 pm

replay game pygame and raspberry snake

Thu Jul 18, 2013 2:03 pm

Ok so i got the book that teaches you the game raspberry snake and i wrote and add some of my own twist(you can see it in the code). but now i want to add one more twist i want to add the option to have a pop up come up and ask if they want to play again if someone could point me in the right direction that would be great. heres my current code:

Code: Select all

import pygame, sys, time, random
from pygame.locals import *
import easygui as eg
pygame.init()
eg.msgbox("""
Game starts fast!
Get your hands on the arrorw keys and hit enter to start!
Press ESC to quit the game.
""")
fpsClock = pygame.time.Clock()

playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Raspberry Snake')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction

def gameOver():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
    gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
    gameOverRect = gameOverSurf.get_rect()
    gameOverRect.midtop = (320, 10)
    playSurface.blit(gameOverSurf, gameOverRect)
    pygame.display.flip()
    time.sleep(5)
    pygame.quit()
    sys.exit()

while True:
   
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
        elif event.type == KEYDOWN:
            if event.key == K_RIGHT or event.key == ord('d'):
                changeDirection = 'right'
            if event.key == K_LEFT or event.key == ord('a'):
                changeDirection = 'left'
            if event.key == K_UP or event.key == ord('w'):
                changeDirection = 'up'
            if event.key == K_DOWN or event.key == ord('s'):
                changeDirection = 'down'
            if event.key == K_ESCAPE:
                pygame.event.post(pygame.event.Event(QUIT))
    if changeDirection == 'right' and not direction == 'left':
        direction = changeDirection
    if changeDirection == 'left' and not direction == 'right':
        direction = changeDirection
    if changeDirection == 'up' and not direction == 'down':
        direction = changeDirection
    if changeDirection == 'down' and not direction == 'up':
        direction = changeDirection
    if direction == 'right':
        snakePosition[0] += 20
    if direction == 'left':
        snakePosition[0] -= 20
    if direction == 'up':
        snakePosition[1] -= 20
    if direction == 'down':
        snakePosition[1] += 20
    snakeSegments.insert(0,list(snakePosition))
    if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
        raspberrySpawned = 0
    else:
        snakeSegments.pop()
    if raspberrySpawned == 0:
        x = random.randrange(1,32)
        y = random.randrange(1,24)
        raspberryPosition = [int(x*20),int(y*20)]
    raspberrySpawned = 1
    playSurface.fill(blackColour)
    for position in snakeSegments:
        pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
    pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
    pygame.display.flip()
    if snakePosition[0] > 620 or snakePosition[0] < 0:
        gameOver()
    if snakePosition[1] > 460 or snakePosition[1] < 0:
        gameOver()
    for snakeBody in snakeSegments[1:]:
        if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
            gameOver()
    fpsClock.tick(30)

User avatar
davef21370
Posts: 897
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: replay game pygame and raspberry snake

Thu Jul 18, 2013 5:16 pm

Change your gameOver() function to read something like this (I haven't tested this but it can't be far off). When this function is called from your main loop, if the player hits Y or y it will return to your main loop, if so reset your snake and carry on.

Dave.

(Not sure the K_Y and K_N bits are correct but you get the gist.)

Code: Select all

def gameOver():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
    gameOverSurf = gameOverFont.render('Game Over - Play Again? (Y/N)', True, greyColour)
    gameOverRect = gameOverSurf.get_rect()
    gameOverRect.midtop = (320, 10)
    playSurface.blit(gameOverSurf, gameOverRect)
    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
            elif event.type == KEYDOWN:
                if event.key == K_Y or event.key == K_y:
                   return
                if event.key == K_N or event.key == K_n:
                   break
    pygame.quit()
    sys.exit()
Apple say... Monkey do !!

apples723
Posts: 80
Joined: Sat Jun 22, 2013 3:13 pm

Re: replay game pygame and raspberry snake

Thu Jul 18, 2013 6:17 pm

i get this error have tried multiple ways but when using any of them i get errors i tried yours and get this error

Code: Select all

Traceback (most recent call last):
  File "C:\Python27\game2.py", line 111, in <module>
    gameOver()
  File "C:\Python27\game2.py", line 58, in gameOver
    if event.key == K_Y or event.key == K_y:
NameError: global name 'K_Y' is not defined

User avatar
davef21370
Posts: 897
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: replay game pygame and raspberry snake

Thu Jul 18, 2013 8:00 pm

Just checked the docs, try getting rid of the K_Y bit and just using K_y, same for the N part, apparently PyGame doesn't distinguish between upper and lower case.

Dave.
Apple say... Monkey do !!

apples723
Posts: 80
Joined: Sat Jun 22, 2013 3:13 pm

Re: replay game pygame and raspberry snake

Thu Jul 18, 2013 8:57 pm

now it just doesnt do anything after i die no errors no nothing if you click yes the white worm moves like an inch but nothing else im running in idle does that matter?

User avatar
davef21370
Posts: 897
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: replay game pygame and raspberry snake

Fri Jul 19, 2013 12:31 pm

You may need to re-initialise the snakePosition, snakeSegments, etc before returning from the yes/no part.
I'm not in a position to test anything until this Sunday but try anyway and keep us posted.

Dave.
Apple say... Monkey do !!

megazoic
Posts: 3
Joined: Fri Jul 19, 2013 5:49 pm

Re: replay game pygame and raspberry snake

Mon Jul 22, 2013 9:36 pm

Working with some high school kids at a summer 'funshop' in the US, we came up with this solution based on the above recommendations by previous replies to this question. It just involves adding to the gameOver() function.

Code: Select all

def gameOver():
global snakePosition, snakeSegments, raspberryPosition, raspberrySpawned, direction, changeDirection
...
time.sleep(5)
gameOverSurf = gameOverFont.render('Play Another?', True, redColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 60)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
while True:
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			#wait for key input
		elif event.type == KEYDOWN:
			if event.key == K_y:
				playSurface.fill(blackColour)
				pygame.display.flip()
				gameOverSurf = gameOverFont.render('Get Ready ;>()', True, greyColour)
				playSurface.blit(gameOverSurf, gameOverRect)
				pygame.display.flip()
				time.sleep(3)
				snakePosition = [100,100]
				snakeSegments = [[100,100],[80,100],[60,100]]
				raspberryPosition = [300,300]
				raspberrySpawned = 1
				direction = 'right'
				changeDirection = direction
				playSurface.fill(blackColour)
				pygame.display.flip()
				return
			else:
				pygame.quit()
				sys.exit()

apples723
Posts: 80
Joined: Sat Jun 22, 2013 3:13 pm

Re: replay game pygame and raspberry snake

Mon Jul 22, 2013 11:05 pm

megazoic wrote:Working with some high school kids at a summer 'funshop' in the US, we came up with this solution based on the above recommendations by previous replies to this question. It just involves adding to the gameOver() function.

Code: Select all

def gameOver():
global snakePosition, snakeSegments, raspberryPosition, raspberrySpawned, direction, changeDirection
...
time.sleep(5)
gameOverSurf = gameOverFont.render('Play Another?', True, redColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 60)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
while True:
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			#wait for key input
		elif event.type == KEYDOWN:
			if event.key == K_y:
				playSurface.fill(blackColour)
				pygame.display.flip()
				gameOverSurf = gameOverFont.render('Get Ready ;>()', True, greyColour)
				playSurface.blit(gameOverSurf, gameOverRect)
				pygame.display.flip()
				time.sleep(3)
				snakePosition = [100,100]
				snakeSegments = [[100,100],[80,100],[60,100]]
				raspberryPosition = [300,300]
				raspberrySpawned = 1
				direction = 'right'
				changeDirection = direction
				playSurface.fill(blackColour)
				pygame.display.flip()
				return
			else:
				pygame.quit()
				sys.exit()
did you test it because if i click y it just says get ready and doesnt do any thing here is my updated code

Code: Select all

import pygame, sys, time, random
from pygame.locals import *
import easygui as eg
from subprocess import call
import pygame as pg
pygame.init()
eg.msgbox("""
Game starts fast!
Get your hands on the arrorw keys and hit enter to start!
Press ESC to quit the game.
""")
fpsClock = pygame.time.Clock()

playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Raspberry Snake')
screen = (500, 300)
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction


def gameOver():
    gameOverFont = pygame.font.Font('freesansbold.ttf', 35)
    gameOverSurf = gameOverFont.render('Game Over - Play Again? (Y/N)', True, greyColour)
    gameOverRect = gameOverSurf.get_rect()
    gameOverRect.midtop = (320, 10)
    playSurface.blit(gameOverSurf, gameOverRect)
    pygame.display.flip()
    keys = pygame.key.get_pressed()
    while True:
       for event in pygame.event.get():
          if event.type == QUIT:
             pygame.quit()
             #wait for key input
          elif event.type == KEYDOWN:
             if event.key == K_y:
                playSurface.fill(blackColour)
                pygame.display.flip()
                gameOverSurf = gameOverFont.render('Get Ready ;>()', True, greyColour)
                playSurface.blit(gameOverSurf, gameOverRect)
                pygame.display.flip()
                time.sleep(3)
                snakePosition = [100,100]
                snakeSegments = [[100,100],[80,100],[60,100]]
                raspberryPosition = [300,300]
                raspberrySpawned = 1
                direction = 'right'
                changeDirection = direction
                playSurface.fill(blackColour)
                pygame.display.flip()
                return
             else:
                pygame.quit()
                sys.exit()

while True:
       
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
            elif event.type == KEYDOWN:
                if event.key == K_RIGHT or event.key == ord('d'):
                    changeDirection = 'right'
                if event.key == K_LEFT or event.key == ord('a'):
                    changeDirection = 'left'
                if event.key == K_UP or event.key == ord('w'):
                    changeDirection = 'up'
                if event.key == K_DOWN or event.key == ord('s'):
                    changeDirection = 'down'
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
        if changeDirection == 'right' and not direction == 'left':
            direction = changeDirection
        if changeDirection == 'left' and not direction == 'right':
            direction = changeDirection
        if changeDirection == 'up' and not direction == 'down':
            direction = changeDirection
        if changeDirection == 'down' and not direction == 'up':
            direction = changeDirection
        if direction == 'right':
            snakePosition[0] += 20
        if direction == 'left':
            snakePosition[0] -= 20
        if direction == 'up':
            snakePosition[1] -= 20
        if direction == 'down':
            snakePosition[1] += 20
        snakeSegments.insert(0,list(snakePosition))
        if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
            raspberrySpawned = 0
        else:
            snakeSegments.pop()
        if raspberrySpawned == 0:
            x = random.randrange(1,32)
            y = random.randrange(1,24)
            raspberryPosition = [int(x*20),int(y*20)]
        raspberrySpawned = 1
        playSurface.fill(blackColour)
        for position in snakeSegments:
            pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
        pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
        pygame.display.flip()
        if snakePosition[0] > 620 or snakePosition[0] < 0:
            gameOver()
        if snakePosition[1] > 460 or snakePosition[1] < 0:
            gameOver()
        for snakeBody in snakeSegments[1:]:
            if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
                gameOver()
        fpsClock.tick(30)

megazoic
Posts: 3
Joined: Fri Jul 19, 2013 5:49 pm

Re: replay game pygame and raspberry snake

Tue Jul 23, 2013 5:37 pm

I am not a Python programmer and I have reformatted my pi's SD card for a different purpose so it will take a bit of time to get to the original configuration. I just tested the code I posted on my Mac and it works fine. I'm not sure about the extra code that you've added but noticed that you didn't include the 'global... ' at the beginning of the gameOver() def. Could it be that the variables that you are writing to inside the gameOver() are local and not the ones the game needs when returning from the gameOver() function (after responding with a 'y') to the main while loop?

Here's the code in it's entirety (mostly taken from the Users Guide)

Code: Select all

#!/usr/bin/env python

# Raspberry Snake
# Written by Gareth Halfacree for the Raspberry Pi User Guide

import pygame, sys, time, random
from pygame.locals import *

pygame.init()

fpsClock = pygame.time.Clock()

playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Raspberry Snake')

redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction

def gameOver():
	global snakePosition, snakeSegments, raspberryPosition, raspberrySpawned, direction, changeDirection
	gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
	gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
	gameOverRect = gameOverSurf.get_rect()
	gameOverRect.midtop = (320, 10)
	playSurface.blit(gameOverSurf, gameOverRect)
	pygame.display.flip()
	time.sleep(3)
	gameOverSurf = gameOverFont.render('Play Another?', True, redColour)
	gameOverRect = gameOverSurf.get_rect()
	gameOverRect.midtop = (320, 60)
	playSurface.blit(gameOverSurf, gameOverRect)
	pygame.display.flip()
	while True:
		for event in pygame.event.get():
			if event.type == QUIT:
				pygame.quit()
				#wait for key input
			elif event.type == KEYDOWN:
				if event.key == K_y:
					playSurface.fill(blackColour)
					pygame.display.flip()
					gameOverSurf = gameOverFont.render('Get Ready ;>()', True, greyColour)
					playSurface.blit(gameOverSurf, gameOverRect)
					pygame.display.flip()
					time.sleep(3)
					snakePosition = [100,100]
					snakeSegments = [[100,100],[80,100],[60,100]]
					raspberryPosition = [300,300]
					raspberrySpawned = 1
					direction = 'right'
					changeDirection = direction
					playSurface.fill(blackColour)
					pygame.display.flip()
					return
				else:
					pygame.quit()
					sys.exit()
while True:
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
		elif event.type == KEYDOWN:
			if event.key == K_RIGHT or event.key == ord('d'):
				changeDirection = 'right'
			if event.key == K_LEFT or event.key == ord('a'):
				changeDirection = 'left'
			if event.key == K_UP or event.key == ord('w'):
				changeDirection = 'up'
			if event.key == K_DOWN or event.key == ord('s'):
				changeDirection = 'down'
			if event.key == K_ESCAPE:
				pygame.event.post(pygame.event.Event(QUIT))
	if changeDirection == 'right' and not direction == 'left':
		direction = changeDirection
	if changeDirection == 'left' and not direction == 'right':
		direction = changeDirection
	if changeDirection == 'up' and not direction == 'down':
		direction = changeDirection
	if changeDirection == 'down' and not direction == 'up':
		direction = changeDirection
	if direction == 'right':
		snakePosition[0] += 20
	if direction == 'left':
		snakePosition[0] -= 20
	if direction == 'up':
		snakePosition[1] -= 20
	if direction == 'down':
		snakePosition[1] += 20
	snakeSegments.insert(0,list(snakePosition))
	if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
		raspberrySpawned = 0
	else:
		snakeSegments.pop()
	if raspberrySpawned == 0:
		x = random.randrange(1,32)
		y = random.randrange(1,24)
		raspberryPosition = [int(x*20),int(y*20)]
	raspberrySpawned = 1
	playSurface.fill(blackColour)
	for position in snakeSegments:
		pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
	pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
	pygame.display.flip()
	if snakePosition[0] > 620 or snakePosition[0] < 0:
		gameOver()
	if snakePosition[1] > 460 or snakePosition[1] < 0:
		gameOver()
	for snakeBody in snakeSegments[1:]:
		if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
			gameOver()
	fpsClock.tick(20)

megazoic
Posts: 3
Joined: Fri Jul 19, 2013 5:49 pm

Re: replay game pygame and raspberry snake

Tue Jul 23, 2013 5:49 pm

Another note, I just noticed that the pygame.event may still retain a keypress from the previous game and this would trigger the pygame.guit() immediately when gameOver() is called. This happens when you press and hold a key past the call to gameOver(). An easy fix is to clear the event queue by calling pygame.event.get() right after time.sleep(3) in the above program.

Return to “Python”