Pygame makes the game unplayable with lag - python

I am making a game where you just click on the circles, and i just got it working when i noticed the game really laggs out sometimes. It just would not generate new position. This is my code:
import pygame
from pygame.font import SysFont
from pygame.display import flip
from random import randint, choice
# Bools
r = True
title = True
game = False
# Floats
# Ints
points = 0
deletewhat = [True, False]
# Strings
# Lists
spots = []
pointchoice = [1,1,1,2]
# Colors
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
YELLOW = (255,255,0)
GRAY = (20,20,20)
# Pygame init
pygame.init()
pygame.font.init()
# Pygame userevents
delete = pygame.USEREVENT
# Pygame timers
pygame.time.set_timer(delete, 1000)
# Pygame Fonts
titlefont = SysFont("Arial", 70)
headfont = SysFont("Arial", 20)
startfont = SysFont("Arial", 80)
pointsfont = SysFont("Arial", 25)
# Pygame font one-time render
titletext = titlefont.render("The Spot Spotter", False, BLACK)
headtext = headfont.render("Click the spots and earn points!", False, BLACK)
starttext = startfont.render("START", False, RED)
# Other Pygame things
screen = pygame.display.set_mode((900,750))
class Spot:
def __init__(self, x, y, points):
global WHITE, GRAY
self.x = x
self.y = y
self.points = points
if self.points == 1:
self.spotcolor = WHITE
else:
self.spotcolor = GRAY
def draw(self):
pygame.draw.ellipse(screen, self.spotcolor, (self.x, self.y, 50,50))
def get_pos(self):
return self.x, self.y
def get_points(self):
return self.points
spot = Spot
while r:
for event in pygame.event.get():
if event.type == pygame.QUIT:
r = False
if event.type == delete and game:
deleteone = choice(deletewhat)
if deleteone:
spot1 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot1ready = True
spot2 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot2ready = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = pygame.mouse.get_pos()
if mouse[0] > 249 and mouse[0] < 801:
if mouse[1] > 299 and mouse[1] < 426:
if title:
title = False
game = True
try:
spot1.get_pos()
except NameError:
pass
else:
spot1pos = spot1.get_pos()
if mouse[0] > (spot1pos[0] - 1) and mouse[0] < (spot1pos[0] + 51):
if mouse[1] > (spot1pos[1] - 1) and mouse[1] < (spot1pos[1] + 51):
if spot1ready:
spot1ready = False
points += spot1.get_points()
try:
spot2.get_pos()
except NameError:
pass
else:
spot2pos = spot2.get_pos()
if mouse[0] > (spot2pos[0] - 1) and mouse[0] < (spot2pos[0] + 51):
if mouse[1] > (spot2pos[1] - 1) and mouse[1] < (spot2pos[1] + 51):
if spot2ready:
spot2ready = False
points += spot2.get_points()
if title:
screen.fill(WHITE)
screen.blit(titletext, (250, 0))
screen.blit(headtext, (350, 100))
pygame.draw.rect(screen, YELLOW, (200, 300, 550, 125)) # Start Button
screen.blit(starttext, (375, 315))
flip()
elif game:
pointstext = pointsfont.render(f"Points: {points}", False, BLACK)
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, (0, 600, 900, 150))
screen.blit(pointstext, (20, 610))
try:
spot1.draw()
except NameError:
pass
else:
spot1.draw()
try:
spot2.draw()
except NameError:
pass
else:
spot2.draw()
flip()
pygame.quit()
If you are wondering, the bools game and title are both for detecting which tab needs to be rendered. if game is true and title is false then the game knows hey, i need to render the game.
Also please note that i am not that good in pygame.

The problem is the line deleteone = choice(deletewhat). This may generate multiple False in a row.
Add a variable wait_delete. Decrement the variable when the delete event occurs. Set a new random value with randint if wait_delete is 0.
wait_delete = 1
spot = Spot
while r:
for event in pygame.event.get():
if event.type == pygame.QUIT:
r = False
if event.type == delete and game:
wait_delete -= 1
if wait_delete == 0:
wait_delete = randint(1, 3)
spot1 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot1ready = True
spot2 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot2ready = True
# [...]

Related

Why isn't the count for lives going down my pygame code?

So I am doing a project where I have to make a game that gives the user three lives and each time the beamrect's rectangle collides with the player's, it subtracts a life and puts them in the original position. When lives == 0: there will be a death screen displayed. But for some reason, the death screen isn't being displayed even though I made sure that every time the player rect (being zonicrect) and the beamrect collided, it would subtract 1 from the life variable.
# Your header should go here, each comment should be initialed -DK
import pygame, sys
import os
# https://youtu.be/jO6qQDNa2UY
pygame.init()
FPS = 60
# Useful Variables
# Size
size = height, width = 900, 500
zonhw = zheight, zwidth = 70, 70
scale2 = height2, width2 = 600, 300
lscale = lheight, lwidth = 80, 80
beamsz = bheight, bwidth = 50,25
platz = pheight, pwidth = 10, 70
# RGB
white = (255, 255, 255)
black = (0,0,0)
blue = (0, 0, 128)
green = (0, 255, 0)
brown = (165,42,42)
# Speed
VEL = 5
beamspeed = 3
# Position
laserpos = posx, posy = 500,250
#other
i = 0
life = 3
score = 0
# graphics
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Zonic bootleg")
font = pygame.font.Font('freesansbold.ttf', 32)
zonic = pygame.image.load(os.path.join("image","zonic.gif"))
zonic = pygame.transform.scale(zonic, zonhw)
bg = pygame.image.load(os.path.join("image","sonic-back.jpg"))
bg = pygame.transform.scale(bg, size)
gg = pygame.image.load(os.path.join("image","gg.jpg"))
gg= pygame.transform.scale(gg, size)
lazerz = pygame.image.load(os.path.join("image","Lazerz.gif"))
lazerz = pygame.transform.scale(lazerz, lscale)
beam = pygame.image.load(os.path.join("image","laserbeam.jpg"))
beam = pygame.transform.scale(beam, beamsz)
lives = pygame.image.load(os.path.join("image","health.png"))
lives = pygame.transform.scale(lives,(40,40))
# zoncz = pygame.image.load(os.path.join("image","zoncz.png"))
# zoncz = pygame.transform.scale(zoncz, scale2)
#coalitions
def collider(life,beamrect,zonicrect,lazerect):
beamrect.x -= beamspeed
if zonicrect.colliderect(beamrect):
beamrect.x = lazerect.x+21
zonicrect.x = 0
if beamrect.x <-60:
#screen.blit(beam, (posx, posy))
beamrect.x += 550
def updating(score, beamrect):
if beamrect.x == 0:
score += 1
#Death
def death():
while life <= 0:
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death,(250, 250))
# zonic movement
def KWS(keyvar, zonicrect,flip):
if keyvar[pygame.K_RIGHT]: # right
zonicrect.x += VEL
flip = False
if zonicrect.x > 500:
zonicrect.x -= VEL
if keyvar[pygame.K_LEFT] and zonicrect.x + VEL > 0: # left
zonicrect.x -= VEL
flip = True
def flipx(flip,zonicrect):
if flip:
screen.blit(pygame.transform.flip(zonic,True,False),(zonicrect.x,zonicrect.y))
if flip == False:
screen.blit(pygame.transform.flip(zonic,False,False),(zonicrect.x,zonicrect.y))
# text = font.render('Lives: {0}'.format(life), True, green, blue)
def heart(beamrect,zonicrect,lazerect):
x = 1
i = -33
while life >= x:
x +=1
i+=32
screen.blit(lives, (2+i,0))
# draw
def drawingfunc(zonicrect,lazerect, beamrect,flip, zonczrect):
#screen.blit(death,(0,0))
screen.blit(bg, (0, 0))
heart(beamrect,zonicrect,lazerect)
flipx(flip,zonicrect)
#screen.blit(zonic,(zonicrect.x, zonicrect.y))
screen.blit(beam, (beamrect.x, beamrect.y+15))
screen.blit(lazerz, (lazerect.x+21,lazerect.y))
# score = font.render('Score: ')
# screen.blit(zonic, (zonczrect.x, zonczrect.y))
sore = font.render("Score: {0}".format(score), True, black, white)
screen.blit(sore, (30, 70))
pygame.draw.rect(screen, brown, pygame.Rect(200, 200, 100, 50))
pygame.display.update()
# mainloop and refresh rate
def main():
jump = False
jumpCount = 0
jumpMax = 15
flip = False
zonicrect = pygame.Rect(10, 250, zheight, zwidth)
lazerect = pygame.Rect(posx, posy, lheight, lwidth)
beamrect = pygame.Rect(posx, posy, bheight, bwidth)
zonczrect = pygame.Rect(50, 25, height2, width2)
# (30,0,32,32)
# livesrect = pygame.Rect(0,0,10,10)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
death()
collider(life,beamrect,zonicrect,lazerect)
keyspressed = pygame.key.get_pressed()
KWS(keyspressed, zonicrect,flip)
updating(score, beamrect)
drawingfunc(zonicrect,lazerect, beamrect,flip, zonczrect)
flipx(flip, zonicrect)
if jump:
zonicrect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
pygame.quit()
# calling function NOTE: needs to always be at the end of file
if __name__ == "__main__":
main()
Solution
In your death function, you forgot to call pygame.display.update() at the bottom of your loop. That's why you cannot see the death screen even when life is less than or equal to zero. Also, you need to add an event loop in your death function, so that the window will keep responding to events while the loop is running.
So change this:
def death():
while life <= 0:
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death, (250, 250))
To this:
def death():
while life <= 0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death, (250, 250))
pygame.display.update()
Full Modified Code
# Your header should go here, each comment should be initialed -DK
import pygame, sys
import os
# https://youtu.be/jO6qQDNa2UY
pygame.init()
FPS = 60
# Useful Variables
# Size
size = height, width = 900, 500
zonhw = zheight, zwidth = 70, 70
scale2 = height2, width2 = 600, 300
lscale = lheight, lwidth = 80, 80
beamsz = bheight, bwidth = 50, 25
platz = pheight, pwidth = 10, 70
# RGB
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 128)
green = (0, 255, 0)
brown = (165, 42, 42)
# Speed
VEL = 5
beamspeed = 3
# Position
laserpos = posx, posy = 500, 250
# other
i = 0
life = 3
score = 0
# graphics
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Zonic bootleg")
font = pygame.font.Font('freesansbold.ttf', 32)
zonic = pygame.image.load(os.path.join("image", "zonic.gif"))
zonic = pygame.transform.scale(zonic, zonhw)
bg = pygame.image.load(os.path.join("image", "sonic-back.jpg"))
bg = pygame.transform.scale(bg, size)
gg = pygame.image.load(os.path.join("image", "gg.jpg"))
gg = pygame.transform.scale(gg, size)
lazerz = pygame.image.load(os.path.join("image", "Lazerz.gif"))
lazerz = pygame.transform.scale(lazerz, lscale)
beam = pygame.image.load(os.path.join("image", "laserbeam.jpg"))
beam = pygame.transform.scale(beam, beamsz)
lives = pygame.image.load(os.path.join("image", "health.png"))
lives = pygame.transform.scale(lives, (40, 40))
# zoncz = pygame.image.load(os.path.join("image","zoncz.png"))
# zoncz = pygame.transform.scale(zoncz, scale2)
# coalitions
def collider(life, beamrect, zonicrect, lazerect):
beamrect.x -= beamspeed
if zonicrect.colliderect(beamrect):
beamrect.x = lazerect.x + 21
zonicrect.x = 0
if beamrect.x < -60:
# screen.blit(beam, (posx, posy))
beamrect.x += 550
def updating(score, beamrect):
if beamrect.x == 0:
score += 1
# Death
def death():
while life <= 0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death, (250, 250))
pygame.display.update()
# zonic movement
def KWS(keyvar, zonicrect, flip):
if keyvar[pygame.K_RIGHT]: # right
zonicrect.x += VEL
flip = False
if zonicrect.x > 500:
zonicrect.x -= VEL
if keyvar[pygame.K_LEFT] and zonicrect.x + VEL > 0: # left
zonicrect.x -= VEL
flip = True
def flipx(flip, zonicrect):
if flip:
screen.blit(pygame.transform.flip(zonic, True, False), (zonicrect.x, zonicrect.y))
if flip == False:
screen.blit(pygame.transform.flip(zonic, False, False), (zonicrect.x, zonicrect.y))
# text = font.render('Lives: {0}'.format(life), True, green, blue)
def heart(beamrect, zonicrect, lazerect):
x = 1
i = -33
while life >= x:
x += 1
i += 32
screen.blit(lives, (2 + i, 0))
# draw
def drawingfunc(zonicrect, lazerect, beamrect, flip, zonczrect):
# screen.blit(death,(0,0))
screen.blit(bg, (0, 0))
heart(beamrect, zonicrect, lazerect)
flipx(flip, zonicrect)
# screen.blit(zonic,(zonicrect.x, zonicrect.y))
screen.blit(beam, (beamrect.x, beamrect.y + 15))
screen.blit(lazerz, (lazerect.x + 21, lazerect.y))
# score = font.render('Score: ')
# screen.blit(zonic, (zonczrect.x, zonczrect.y))
sore = font.render("Score: {0}".format(score), True, black, white)
screen.blit(sore, (30, 70))
pygame.draw.rect(screen, brown, pygame.Rect(200, 200, 100, 50))
pygame.display.update()
# mainloop and refresh rate
def main():
jump = False
jumpCount = 0
jumpMax = 15
flip = False
zonicrect = pygame.Rect(10, 250, zheight, zwidth)
lazerect = pygame.Rect(posx, posy, lheight, lwidth)
beamrect = pygame.Rect(posx, posy, bheight, bwidth)
zonczrect = pygame.Rect(50, 25, height2, width2)
# (30,0,32,32)
# livesrect = pygame.Rect(0,0,10,10)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
death()
collider(life, beamrect, zonicrect, lazerect)
keyspressed = pygame.key.get_pressed()
KWS(keyspressed, zonicrect, flip)
updating(score, beamrect)
drawingfunc(zonicrect, lazerect, beamrect, flip, zonczrect)
flipx(flip, zonicrect)
if jump:
zonicrect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
pygame.quit()
sys.exit(0)
# calling function NOTE: needs to always be at the end of file
if __name__ == "__main__":
main()

Game crashes when reaching "while creating:" loop [duplicate]

This question already has answers here:
Pygame unresponsive display
(1 answer)
Pygame window not responding after a few seconds
(3 answers)
Closed 2 years ago.
The Title says it all.
import pygame
import os
pygame.init()
displayWidth = 1280
displayHeight = 720
black = (0,0,0)
white = (255,255,255)
# Defining variables that determine what points the code has reached.
Running = True
intro = True
menu = True
gender = True
charactercreation = True
genderpicked = False
mcgender = "Null"
displaycharactercreation = True # Defining a loop so that the character creation screen doesn't jitter, blitting multiple times.
creating_character = True
creating = True
event = pygame.event.wait()
key = pygame.key.get_pressed()
n = 1
# Defining a textbox maker
def text_objects(text, font, colour):
textSurface = font.render(text, True, colour)
return textSurface, textSurface.get_rect()
# Defining a fade function
def fade(direction):
if direction == "Out":
black = (0, 0, 0)
fade_opacity = 0
fading = True
while fading:
fade_opacity += 1
fadeshape = pygame.Surface((1280, 720))
fadeshape.set_alpha(fade_opacity)
fadeshape.fill(black)
display.blit(fadeshape, (0,0))
pygame.display.update()
if fade_opacity == 100:
fading = False
elif direction == "In":
black = (0, 0, 0)
fade_opacity = 255
fading = True
while fading:
fade_opacity -= 1
fadeshape = pygame.Surface((1280,720))
fadeshape.set_alpha(fade_opacity)
fadeshape.fill(black)
display.blit(fadeshape, (0,0))
pygame.display.update()
if fade_opacity == 0:
fading = False
# Creating window and defining images
display = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption("Blazing Badge")
clock = pygame.time.Clock()
warriorImage = pygame.image.load("warrior.png")
grassImage = pygame.image.load("grass.png")
playButton = pygame.image.load("play button.png")
durandal = pygame.image.load("durandal.png")
mainscreen = pygame.image.load("mainmenu.jpg")
logo = pygame.image.load("logo.png")
arrow = pygame.image.load(os.path.join("graphics", "left_arrow.png"))
pygame.display.set_icon(durandal) # Setting the Window Icon
while Running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print(event)
mouse = pygame.mouse.get_pos()
pressed = pygame.mouse.get_pressed()
# Main menu follows ----------------
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
display.fill(white)
largeText = pygame.font.Font("The Fighter.otf", 115)
TextSurf, TextRect = text_objects("Tech Demo", largeText, black)
TextSurf = pygame.transform.rotate(TextSurf, 15)
TextRect.center = ((displayWidth*0.68), (displayHeight*0.4))
playpos = (((displayWidth/2)-100), (displayHeight)*0.7)
durandalpos = (((displayWidth/2)-280), (displayHeight*0.2))
display.blit(mainscreen, (0,0))
display.blit(playButton, playpos)
durandalresized = pygame.transform.scale(durandal, (561, 333))
display.blit(durandalresized, durandalpos)
display.blit(logo, ((displayWidth*0.2), (displayHeight*0.35)))
display.blit(TextSurf, TextRect)
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(click)
print(mouse)
if 580 < mouse[0] < 710 and 532 < mouse[1] < 674:
if click[0] == 1:
print("Start Game")
fade(direction="Out")
menu = False
pygame.display.update()
clock.tick(15)
print("I have broken out of the main menu loop.")
while charactercreation:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gender_symbols = pygame.image.load(os.path.join("graphics\Character Creation", "Gender Symbols.png"))
creation_background = pygame.image.load(os.path.join("graphics\Character Creation", "creationbackground.jpg"))
TextSurf, TextRect = text_objects("Choose your gender", pygame.font.Font("The Fighter.otf", 115), white)
display.blit(creation_background, (0, 0))
display.blit(TextSurf, (((1280 / 2) - 500), displayHeight * 0.1))
display.blit(gender_symbols, (340, (displayHeight * 0.6)))
pygame.display.update()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
charactercreation = False
print("I have broken out of the character creation loop.")
while genderpicked == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print(event)
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if 365 < mouse[0] < 602 and 457 < mouse[1] < 702 and click[0] == 1:
mcgender = "Female"
genderpicked = True
print(mcgender)
elif 457 < mouse[1] < 702 and 677 < mouse[0] < 916 and click[0] == 1:
mcgender = "Male"
genderpicked = True
print(mcgender)
print("I have broken out of the gender picking loop.")
while displaycharactercreation:
display.blit(creation_background, (0, 0))
pygame.display.update()
print(mcgender)
if mcgender == "Male":
gendercolour = (0, 128, 255)
elif mcgender == "Female":
gendercolour = (255, 0, 127)
else:
gendercolour = white
# Creating the prompts for the creation screen.
LetterQ1, LetterQ2 = text_objects("<- Q", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterQ1, (100, 50))
LetterE1, LetterE2 = text_objects("E->", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterE1, (1080, 50))
LetterA1, LetterA2 = text_objects("<- A", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterA1,(100, 310))
LetterD1, LetterD2 = text_objects("D ->", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterD1, (1080, 310))
LetterZ1, LetterZ2 = text_objects("<- Z", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterZ1, (100, 570))
LetterC1, LetterC2 = text_objects("C ->", pygame.font.Font("The Fighter.otf", 115), gendercolour)
display.blit(LetterC1, (1080, 570))
pygame.display.update() # Applying all of the prompts
displaycharactercreation = False
print("I have stopped displaying the prompts for character creation")
while creating_character:
if mcgender == "Male":
print("I have reached male")
while creating:
print("I have reached creation loop male")
key = pygame.key.get_pressed()
if key[pygame.K_q]:
if n == 1:
n = 8
else:
n -= 1
print(n)
if key[pygame.K_e]:
if n == 8:
n = 1
else:
n += 1
print(n)
This is the code so far, running python and pygame. Sorry if the code is just a bit all over the place, it's how I'm used to coding,
When reaching this point:
while creating_character:
if mcgender == "Male":
print("I have reached male")
while creating:
print("I have reached creation loop male")
key = pygame.key.get_pressed()
if key[pygame.K_q]:
if n == 1:
n = 8
else:
n -= 1
print(n)
if key[pygame.K_e]:
if n == 8:
n = 1
else:
n += 1
print(n)
if key[pygame.K_RETURN]:
creating = False
creating_character = False
The code crashes and the window begins not responding past the point of while creating: I still get the interpreter returning "I have reached creation loop male", over and over again.
The code does not crash, but it is not responding, because the event handling is missing.
The array of key states, which is returned by pygame.key.get_pressed(), is evaluated when the events are handled by either pygame.event.pump() or pygame.event.get(). When a keyboard event occurse, then the internal states of the key is updated and pygame.key.get_pressed() can return the new states.
Call pygame.event.pump() in the inner loop:
while creating:
# handle events
pygame.event.pump()
print("I have reached creation loop male")
# get the current key states
key = pygame.key.get_pressed()
if key[pygame.K_q]:
if n == 1:
n = 8
else:
n -= 1
print(n)
if key[pygame.K_e]:
if n == 8:
n = 1
else:
n += 1
print(n)
if key[pygame.K_RETURN]:
creating = False
creating_character = False
your variable "creating" contains true and isn't changed anywhere, so you have an infinite while true loop.

Update one sprite among a group of sprites [Pygame]

First post here. So I am trying to implement a Civilization type of movement game. At the moment, I have one sprite in a cell. I can click it and then if I click another grid, the sprite moves there. What I now want is to spawn 5-6 such sprites, and then do the same thing. Click on a sprite and then click another grid, and that specific sprite moves there without affecting the other sprites. I cannot seem to do that. I can spawn 5-6 random sprites at different grids, but when I click on one of them and then click another grid, all the other sprites are gone. The code is below (not the best as I am learning Pygame). I understand that I have to somehow only update the sprite that was clicked, but I am not sure how to do that.
import pygame
import random
WIDTH = 900
HEIGHT = 700
FPS = 2
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
TURN = "TeamOne"
def main():
# Pygame sprite Example
global x_lines
global y_lines
x_lines = [WIDTH-i*WIDTH/20 for i in range(20,0, -1)]
y_lines = [HEIGHT-j*HEIGHT/20 for j in range(20,0, -1)]
class TeamOne(pygame.sprite.Sprite):
# sprite for the Player
def __init__(self):
# this line is required to properly create the sprite
pygame.sprite.Sprite.__init__(self)
# create a plain rectangle for the sprite image
self.image = pygame.Surface((WIDTH / 20, HEIGHT / 20))
self.image.fill(GREEN)
# find the rectangle that encloses the image
self.rect = self.image.get_rect()
# center the sprite on the screen
self.rect.center = ((random.randint(1,19)*2+1)* WIDTH/ 40, (random.randint(1,19)*2+1)*HEIGHT/40)
def update(self, position):
# any code here will happen every time the game loop updates
(a, b) = position
for index, i in enumerate(x_lines):
if i > a:
self.rect.x = x_lines[index-1]
break
for index, j in enumerate(y_lines):
if j > b:
self.rect.y = y_lines[index-1]
break
# initialize pygame and create window
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("A Game")
clock = pygame.time.Clock()
clicked_sprites = pygame.sprite.Group()
teamone_sprites = pygame.sprite.Group()
for i in range(5):
mob1 = TeamOne()
teamone_sprites.add(mob1)
# Game loop
running = True
j=0
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and j == 0:
pos = pygame.mouse.get_pos()
for s in teamone_sprites:
if s.rect.collidepoint(pos):
#teamone_sprites.add(s)
clicked_sprites.add(s)
print (clicked_sprites)
j = 1
elif event.type == pygame.MOUSEBUTTONDOWN and j == 1:
new_pos = pygame.mouse.get_pos()
#teamone_sprites.update(new_pos)
clicked_sprites.update(new_pos)
j = 0
# Update
# Draw / render
## screen.fill(BLACK)
## draw_grid(screen)
##
## teamone_sprites.draw(screen)
##
##
##
## # *after* drawing everything, flip the display
## pygame.display.flip()
# Draw / render
screen.fill(BLACK)
draw_grid(screen)
teamone_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
def draw_grid(screen):
for i in range(1, HEIGHT, int(HEIGHT/20)):
pygame.draw.line(screen, GREEN, (1,i) ,(WIDTH,i), 2)
for j in range(1, WIDTH, int(WIDTH/20)):
pygame.draw.line(screen, GREEN, (j,1) ,(j,HEIGHT), 2)
if __name__ == '__main__':
main()
Some tips for you:
Keep your main loop clean
Put logic where it belongs
Only call pygame.display.flip()/pygame.display.update() once
Don't use variable names like j
Since your game is grid based, you should have a way to translate between grid coordinates and screen coordinates
Here's a simple runnable example I hacked together (see the comments for some explanations):
import pygame
import random
WIDTH = 900
HEIGHT = 700
ROWS = 20
COLUMNS = 20
TILE_SIZE = WIDTH / COLUMNS, HEIGHT / ROWS
TILE_W, TILE_H = TILE_SIZE
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
TURN = "TeamOne"
# some functions to translate grid <-> screen coordinates
def posToScreen(pos):
column, row = pos
return column * TILE_W, row * TILE_H
def screenToPos(pos):
column, row = pos
return column / TILE_W, row / TILE_H
def draw_grid(screen):
for i in range(1, HEIGHT, TILE_H):
pygame.draw.line(screen, GREEN, (1,i) ,(WIDTH,i), 2)
for j in range(1, WIDTH, TILE_W):
pygame.draw.line(screen, GREEN, (j,1) ,(j,HEIGHT), 2)
# a class that handles selecting units
class Cursor(pygame.sprite.Sprite):
def __init__(self, units, *groups):
pygame.sprite.Sprite.__init__(self, *groups)
# group of the units that can be controlled
self.units = units
# we create two images
# to indicate if we are selecting or moving
self.image = pygame.Surface(TILE_SIZE)
self.image.set_colorkey((43,43,43))
self.image.fill((43,43,43))
self.rect = self.image.get_rect()
self.selected_image = self.image.copy()
pygame.draw.rect(self.image, pygame.Color('red'), self.image.get_rect(), 4)
pygame.draw.rect(self.selected_image, pygame.Color('purple'), self.image.get_rect(), 4)
self.base_image = self.image
self.selected = None
def update(self):
# let's draw the rect on the grid, based on the mouse position
pos = pygame.mouse.get_pos()
self.rect.topleft = posToScreen(screenToPos(pos))
def handle_click(self, pos):
if not self.selected:
# if we have not selected a unit, do it now
for s in pygame.sprite.spritecollide(self, self.units, False):
self.selected = s
self.image = self.selected_image
else:
# if we have a unit selected, just set its target attribute, so it will move on its own
self.selected.target = posToScreen(screenToPos(pos))
self.image = self.base_image
self.selected = None
class TeamOne(pygame.sprite.Sprite):
def __init__(self, *groups):
pygame.sprite.Sprite.__init__(self, *groups)
self.image = pygame.Surface(TILE_SIZE)
self.image.fill(GREEN)
self.pos = random.randint(0, COLUMNS), random.randint(0, ROWS)
self.rect = self.image.get_rect(topleft = posToScreen(self.pos))
self.target = None
def update(self):
# do nothing until target is set
# (maybe unset it if we reached our target)
if self.target:
if self.rect.x < self.target[0]:
self.rect.move_ip(1, 0)
elif self.rect.x > self.target[0]:
self.rect.move_ip(-1, 0)
elif self.rect.y < self.target[1]:
self.rect.move_ip(0, 1)
elif self.rect.y > self.target[1]:
self.rect.move_ip(0, -1)
self.pos = screenToPos(self.rect.topleft)
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("A Game")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.LayeredUpdates()
team_ones = pygame.sprite.Group()
for i in range(5):
TeamOne(all_sprites, team_ones)
cursor = Cursor(team_ones, all_sprites)
# a nice, simple, clean main loop
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# we could also pass all events to all sprites
# so we would not need this special clause for the cursor...
if event.type == pygame.MOUSEBUTTONDOWN:
cursor.handle_click(event.pos)
all_sprites.update()
screen.fill(BLACK)
draw_grid(screen)
all_sprites.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
I have pretty much the same Problem i have a healthbar for my enemie but i want all enemys to have one so its a spritegroup now if i want to change an attribute of one object out of my spritegroup i dont know how to properly access it. The Problem lays in the Healthbaranimation function. I tried self.healthbar.sprites() self.healthbar.sprites and spritedict nothing really semms to work. Is there an easy way to fix this? P.s sorry for my bad code It is my first real attempt making a small game
from os import path
import pygame
from elements.ammo import AMMO
from elements.bigenemy import BIGENEMY
from elements.enemy import ENEMY
from elements.player import PLAYER
from .base import BaseState
from elements.healthbar import HEALTHBAR
class Gameplay(BaseState):
def __init__(self):
super(Gameplay, self).__init__()
self.next_state = "GAME_OVER"
self.x, self.y = 100, 1030
self.playersprite = PLAYER((self.x, self.y))
self.bigenemy = pygame.sprite.GroupSingle(BIGENEMY())
self.bottomrect = pygame.Rect((0, 1030), (1920, 50))
self.enemysprite = ENEMY()
self.ammosprite = AMMO()
self.healthbar = pygame.sprite.Group(HEALTHBAR())
self.displayedimage = self.playersprite.image
self.displayedrect = self.playersprite.rect
self.highscore = self.load_data()
self.points = 0
self.scoretext = f"SCORE: {self.points}"
self.scoresurf = self.font.render(self.scoretext, True, "red")
self.nhstext = "NEW HIGHSCORE!"
self.nhssurf = self.font.render(self.nhstext, True, "red")
self.ammotext = f"AMMO:{self.playersprite.ammunition}"
self.ammosurf = self.font.render(self.ammotext, True, "red")
self.bulletgroup = pygame.sprite.Group()
self.time_active = 0
self.bigenemyexisting = True
def get_event(self, event):
if event.type == pygame.QUIT:
self.quit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LCTRL:
self.playersprite.crouching = True
elif event.key == pygame.K_SPACE:
self.playersprite.jumping = True
elif event.key == pygame.K_q and self.playersprite.ammunition != 0:
self.playersprite.shooting = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
self.done = True
elif event.key == pygame.K_LCTRL:
self.playersprite.crouching = False
elif event.key == pygame.K_q:
self.playersprite.shooting = False
def draw(self, surface):
surface.fill(pygame.Color("black"))
pygame.draw.rect(surface, "red", self.bottomrect)
surface.blit(self.displayedimage, (self.displayedrect))
surface.blit(self.enemysprite.image, (self.enemysprite.rect))
surface.blit(self.ammosprite.image, (self.ammosprite.rect))
self.healthbar.draw(surface)
self.bigenemy.draw(surface)
self.bulletgroup.draw(surface)
surface.blit(self.scoresurf, (0, 0))
surface.blit(self.ammosurf, (0, 1000))
if self.points > self.highscore: surface.blit(self.nhssurf, (1920 / 2 - 100, 1080 / 2))
def lost(self):
self.enemysprite.startposx = 1920
self.enemysprite.startposy = self.enemysprite.gettypeenemy()
self.enemysprite.speed = 10
self.highscorefunc()
self.points = 0
self.playersprite.ammunition = 30
def collidecheck(self):
self.playermask = pygame.mask.from_surface(self.displayedimage)
self.enemymask = pygame.mask.from_surface(self.enemysprite.image)
offsetx = self.enemysprite.rect.left - self.displayedrect.left
offsety = self.enemysprite.rect.top - self.displayedrect.top
if self.displayedrect.colliderect(self.enemysprite.rect):
if self.playermask.overlap(self.enemymask, (offsetx, offsety)):
self.lost()
self.done = True
elif self.enemysprite.rect.x < 0 and self.enemysprite.speed < 25:
self.points += 1
self.enemysprite.speed += 1
elif self.enemysprite.speed > 25:
self.enemysprite.speed += .5
elif self.displayedrect.colliderect(self.ammosprite.rect):
self.ammosprite.startposx = 2300
self.playersprite.ammunition += 30
elif pygame.sprite.groupcollide(self.bigenemy,self.bulletgroup,False,True):
self.bigenemy.sprite.health -= 10
def shooting(self, dt):
if self.playersprite.ammunition != 0:
if self.playersprite.shooting and not self.playersprite.jumping and not self.playersprite.crouching:
self.time_active += dt
if self.time_active >= 100:
self.bulletgroup.add(self.playersprite.createbullet())
self.time_active = 0
self.playersprite.ammunition -= 1
else:
self.playersprite.shooting = False
def highscorefunc(self):
if self.points > self.highscore:
self.highscore = self.points
with open(path.join(self.dir, self.HS_FILE), 'w') as f:
f.write(str(self.highscore))
def animation(self):
if not self.playersprite.shooting and not self.playersprite.jumping and not self.playersprite.crouching:
if self.playersprite.index >= len(self.playersprite.basicanimation):
self.playersprite.index = 0
self.displayedimage = self.playersprite.basicanimation[int(self.playersprite.index)]
self.playersprite.index += .1
elif self.playersprite.shooting and not self.playersprite.jumping:
if self.playersprite.index >= len(self.playersprite.shootanimation):
self.playersprite.index = 0
self.displayedimage = self.playersprite.shootanimation[int(self.playersprite.index)]
self.playersprite.index += .1
elif self.playersprite.jumping:
self.displayedimage = self.playersprite.imagejump
elif self.playersprite.crouching:
self.displayedimage = self.playersprite.slidingimage
def healthbaranimation(self):
if self.bigenemy.sprite.health < 90:
self.healthbar.spritedict.index = 1
if self.bigenemy.sprite.health < 80:
self.healthbar.sprite.index = 2
if self.bigenemy.sprite.health < 70:
self.healthbar.sprite.index = 3
if self.bigenemy.sprite.health < 60:
self.healthbar.sprite.index = 4
if self.bigenemy.sprite.health < 50:
self.healthbar.sprite.index = 5
if self.bigenemy.sprite.health < 40:
self.healthbar.sprite.index = 6
if self.bigenemy.sprite.health < 30:
self.healthbar.sprite.index = 7
if self.bigenemy.sprite.health < 20:
self.healthbar.sprite.index = 8
if self.bigenemy.sprite.health < 10:
self.healthbar.sprite.index = 9
def spawnbigenemies(self):
if self.bigenemyexisting:
if self.bigenemy.sprite.health < 3:
self.bigenemy.add(BIGENEMY())
self.bigenemyexisting = True
def update(self, dt):
try:
self.bigenemy.sprite.update()
except:
pass
self.healthbaranimation()
self.healthbar.update()
self.playersprite.jump()
self.animation()
self.shooting(dt)
self.bulletgroup.update()
self.enemysprite.update()
self.ammosprite.update()
self.collidecheck()
self.spawnbigenemies()
self.scoretext = f"SCORE: {self.points}"
self.scoresurf = self.font.render(self.scoretext, True, "black")
self.ammotext = f"AMMO:{self.playersprite.ammunition}"
self.ammosurf = self.font.render(self.ammotext, True, "red")

How can I create an interactive object in pygame?

In a pygame program I am creating, I have need for an interactive object on the screen that will call a function when the player character moves onto it and presses the enter key. Here is the code I have so far:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5
screen.fill((0, 0, 0))
color = (0, 128, 255)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Start the experiment simulator", 1, (255,255,255))
screen.blit(label, (100, 100))
label2 = myfont.render("Start the quiz", 1, (255,255,255))
screen.blit(label2, (550, 100))
label3 = myfont.render("Quit game", 1, (255,255,255))
screen.blit(label3, (350, 400))
pygame.draw.rect(screen, red, pygame.Rect(600, 125, 30, 30))
pygame.draw.rect(screen, red, pygame.Rect(225, 125, 30, 30))
pygame.draw.rect(screen, red, pygame.Rect(375, 425, 30, 30))
pygame.display.flip()
clock.tick(60)
At the moment, the object is just a test so would be best to be a small red rectangle, about half the size of the player, that I can replace with an icon later on. This rectangle should be placed below the 'quit game' label on the pygame window and quit the game when interacted with. This is one method that I have tried so far:
if pressed[pygame.K_RETURN] and x >= 375 or x <= 405 and y >=425 or y <= 455:
pygame.display.quit()
pygame.quit()
sys.exit()
Where theoretically the system checks if the user is in a specific area and has pressed the enter key before performing the command.
You can check for collision, using pygame's colliderect
First, create three rects that will represent your three option rects :
simulator_rect = pygame.Rect(600, 125, 30, 30)
quiz_rect = pygame.Rect(225, 125, 30, 30)
quit_rect = pygame.Rect(375, 425, 30, 30)
Next, we'll create a rect that will represent the blue selector rect :
selector_rect = pygame.Rect(50, 50, 60, 60)
So now you've got rects that are created only once, instead of unnamed rects that are created every time
Now, for the actual collision detection :
# Check to see if the user presses the enter key
if pressed[pygame.K_RETURN]:
# Check to see if the selection rect
# collides with any other rect
for rect in option_rects:
if selector_rect.colliderect(rect):
if rect == simulator_rect:
# Do simulations stuff!
print('Simulating!')
elif rect == quiz_rect:
# Do quizzing stuff!
print('Quizzing!')
elif rect == quit_rect:
# Quit!
done = True
Final code :
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30
clock = pygame.time.Clock()
# RGB values for red
red = (255, 0 ,0)
# Your three button rects :
simulator_rect = pygame.Rect(225, 125, 30, 30)
quiz_rect = pygame.Rect(600, 125, 30, 30)
quit_rect = pygame.Rect(375, 425, 30, 30)
# These represent your three option rects
option_rects = [simulator_rect, quiz_rect, quit_rect]
# Your blue selector rect
selector_rect = pygame.Rect(50, 50, 60, 60)
# The 50, 50 xy coords are temporary
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5
# Set the slector rect's coords to x/y
selector_rect.x, selector_rect.y = x, y
screen.fill((0, 0, 0))
color = (0, 128, 255)
pygame.draw.rect(screen, color, selector_rect)
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("Start the experiment simulator", 1, (255,255,255))
screen.blit(label, (100, 100))
label2 = myfont.render("Start the quiz", 1, (255,255,255))
screen.blit(label2, (550, 100))
label3 = myfont.render("Quit game", 1, (255,255,255))
screen.blit(label3, (350, 400))
# Use our created rects
pygame.draw.rect(screen, red, simulator_rect)
pygame.draw.rect(screen, red, quiz_rect)
pygame.draw.rect(screen, red, quit_rect)
# Check to see if the user presses the enter key
if pressed[pygame.K_RETURN]:
# Check to see if the selection rect
# collides with any other rect
for rect in option_rects:
# Add rects as needed
if selector_rect.colliderect(rect):
if rect == simulator_rect:
# Do simulations stuff!
print('Simulating!')
elif rect == quiz_rect:
# Do quizzing stuff!
print('Quizzing!')
elif rect == quit_rect:
# Quit!
done = True
pygame.display.flip()
clock.tick(60)
This does add some complication to your program, but at least it's a rock solid method that you can add features too, and that will remain robust.
Answer to my own question, I managed to make my first attempt work by adding brackets around the x and y checks in this section:
and x >= 375 or x <= 405 and y >=425 or y <= 455:
So that it now reads:
and (x >= 375 and x <= 405) and (y >= 425 and y <= 455):
I just create a system for interactable object and it easy to scale.
listBox = [] # this list used to store all object inside
listBox.append(("text", pos, size, bgColor, textColor, InteractAction))
# add dumy object to the list, "text" can be empty if you dont want.
def InteractAction(mousePos): # sample action used to tie to object
print("do somehthing")
def newDrawBox(IableO):
pygame.draw.rect(gameDisplay, IableO[3],(IableO[1][0], IableO[1][1], IableO[2][0], IableO[2][1]))
text = basicfont.render(str(IableO[0]), True,IableO[4], None)
textrect = text.get_rect()
textrect.centerx = IableO[1][0] + IableO[2][0] / 2
textrect.centery = IableO[1][1] + IableO[2][1] / 2
gameDisplay.blit(text, textrect)
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.MOUSEBUTTONDOWN:
Mouse[event.button] = 1
Mouse[0] = (event.pos[0], event.pos[1])
elif event.type == pygame.MOUSEBUTTONUP:
Mouse[event.button] = 0
Mouse[0] = (event.pos[0], event.pos[1])
#-------- check if mouse is click on any object in the list of Interatable object
if Mouse[1] == 1:
for x in listBox:
if x[1][0] < Mouse[0][0] < x[1][0] + x[2][0] and x[1][1] < Mouse[0][1] < x[1][1] + x[2][1]:
x[5](Mouse[0])
#---- draw all object -----
for x in listBox:
newDrawBox(x)

UnboundLocalError: local variable 'event' referenced before assignment [PYGAME]

I am currently trying to create a game for a school assignment setting up timers for some events in one of my levels, but the "UnboundLocalError" keeps appearing and I'm not sure how to fix it. I've read some other posts where you can set the variable as global but I've tried that in a few places and it still gives me the same error. We are using python 3.4.3.
Here is my code:
import pygame
import random
import sys
import time
import os
#Global Colours and Variables
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
DARKGREEN = (0, 155, 0)
DARKGRAY = (40, 40, 40)
BLUE = (23, 176, 199)
WHITE = (255, 255, 255)
WIDTH = 640
HEIGHT = 480
TILE_SIZE = 32
NUM_TILES_WIDTH = WIDTH//TILE_SIZE
NUM_TILES_HEIGHT = HEIGHT//TILE_SIZE
COUNT = 10
COOKIEVENT = pygame.USEREVENT
pygame.time.set_timer(COOKIEVENT, 3000)
REVENT = pygame.USEREVENT + 3
pygame.time.set_timer(REVENT, 5000)
PEVENT = pygame.USEREVENT + 2
pygame.time.set_timer(PEVENT ,5000)
# - level 1 -
MAXHEALTH = 3
SCORE = 0
grave = pygame.sprite.Sprite()
#Global Definitions
candies = pygame.sprite.OrderedUpdates()
def add_candy(candies):
candy = pygame.sprite.Sprite()
candy.image = pygame.image.load('cookie.png')
candy.rect = candy.image.get_rect()
candy.rect.left = random.randint(1, 19)*32
candy.rect.top = random.randint(1, 13)*32
candies.add(candy)
for i in range(10):
add_candy(candies)
# OPENING SCREEN DEFINITIONS
def showStartScreen():
screen.fill((DARKGRAY))
StartFont = pygame.font.SysFont('Browallia New', 20, bold = False, italic = False)
first_image = StartFont.render("Instructions: Eat all the good cookies!", True, (255, 255, 255))
second_image = StartFont.render("Raccoon and purple cookies will kill you!", True, (255, 255, 255))
third_image = StartFont.render("Collect potions to regain HP!", True, (255, 255, 255))
first_rect = first_image.get_rect(centerx=WIDTH/2, centery=100)
second_rect = second_image.get_rect(centerx=WIDTH/2, centery=120)
third_rect = third_image.get_rect(centerx=WIDTH/2, centery=140)
screen.blit(first_image, first_rect)
screen.blit(second_image, second_rect)
screen.blit(third_image, third_rect)
while True:
drawPressKeyMsg()
if checkForKeyPress():
pygame.event.get()
return
pygame.display.update()
def showlevel2StartScreen():
screen.fill((DARKGRAY))
StartFont = pygame.font.SysFont('Browallia New', 20, bold = False, italic = False)
title_image = StartFont.render("Instructions: Eat all the cookies before the timer runs out!", True, (255, 255, 255))
title_rect = title_image.get_rect(centerx=WIDTH/2, centery=100)
screen.blit(title_image, title_rect)
while True:
drawPressKeyMsg()
if checkForKeyPress():
pygame.event.get()
return
pygame.display.update()
def drawPressKeyMsg():
StartFont = pygame.font.SysFont('Browallia New', 20, bold = False, italic = False)
pressKeyScreen = StartFont.render('Press any key to play.', True, WHITE)
pressKeyRect = pressKeyScreen.get_rect(centerx=WIDTH/2, centery=160)
screen.blit(pressKeyScreen, pressKeyRect)
def checkForKeyPress():
if len(pygame.event.get(pygame.QUIT)) > 0:
terminate()
keyUpEvents = pygame.event.get(pygame.KEYUP)
if len(keyUpEvents) == 0:
return None
if keyUpEvents[0] == pygame.K_ESCAPE:
terminate()
return keyUpEvents[0].key
def getRandomLocation():
return {'x': random.randint(0, TILE_SIZE - 1), 'y': random.randint(0, TILE_SIZE - 1)}
def terminate():
pygame.quit()
sys.exit()
# LEVEL 1 DEFINITIONS
pcandies = pygame.sprite.OrderedUpdates()
def add_candie(pcandies):
candy = pygame.sprite.Sprite()
candy.image = pygame.image.load('cookie.png')
candy.rect = candy.image.get_rect()
pcandy = pygame.sprite.Sprite()
pcandy.image = pygame.image.load('pcookie.png')
pcandy.rect = pcandy.image.get_rect()
pcandy.rect.left = random.randint(1, 19)*32
pcandy.rect.top = random.randint(1, 13)*32
candycollides = pygame.sprite.groupcollide(pcandies, candies, False, True)
while len(candycollides) > 0:
pcandies.remove(pcandy)
pcandy.rect.left = random.randint(1, 19)*32
pcandy.rect.top = random.randint(1, 13)*32
pcandies.add(pcandy)
for i in range (5):
add_candie(pcandies)
raccoons = pygame.sprite.GroupSingle()
def add_raccoon(raccoon):
raccoon = pygame.sprite.Sprite()
raccoon.image = pygame.image.load('enemy.gif')
raccoon.rect = raccoon.image.get_rect()
raccoon.rect.left = random.randint(1, 19)*32
raccoon.rect.top = random.randint(1, 13)*32
raccoon.add(raccoons)
potions = pygame.sprite.GroupSingle()
def add_potion(potion):
potion = pygame.sprite.Sprite()
potion.image = pygame.image.load('potion.gif')
potion.rect = potion.image.get_rect()
potion.rect.left = random.randint(1, 20)*32
potion.rect.top = random.randint(1, 13)*32
potion.add(potions)
#Classes
class Wall(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color):
""" Constructor function """
#Call the parent's constructor
super().__init__()
self.image = pygame.screen([width, height])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
self.rect.y = y
self.rect.x = x
class Room():
#Each room has a list of walls, and of enemy sprites.
wall_list = None
candies = None
def __init__(self):
self.wall_list = pygame.sprite.Group()
self.candies = pygame.sprite.Group
class Player(pygame.sprite.Sprite):
# Set speed vector
change_x = 0
change_y = 0
def __init__(self, x, y):
super().__init__()
#Setting up main character + Adding image/properties to hero!
player = pygame.sprite.Sprite()
player.image = pygame.image.load('rabbit.png')
player_group = pygame.sprite.GroupSingle(hero)
player.rect = player.image.get_rect()
player.rect.y = y
player.rect.x = x
def changespeed(self, x, y):
""" Change the speed of the player. Called with a keypress. """
player.change_x += x
player.change_y += y
def move(self, walls):
""" Find a new position for the player """
# Move left/right
player.rect.x += player.change_x
# Did this update cause us to hit a wall?
block_hit_list = pygame.sprite.spritecollide(player, walls, False)
for block in block_hit_list:
# If we are moving right, set our right side to the left side of
# the item we hit
if player.change_x > 0:
player.rect.right = block.rect.left
else:
# Otherwise if we are moving left, do the opposite.
player.rect.left = block.rect.right
# Move up/down
player.rect.y += player.change_y
# Check and see if we hit anything
block_hit_list = pygame.sprite.spritecollide(self, walls, False)
for block in block_hit_list:
# Reset our position based on the top/bottom of the object.
if player.change_y > 0:
player.rect.bottom = block.rect.top
else:
player.rect.top = block.rect.bottom
class levelwalls(Room):
def __init__(self):
Room.__init__(self)
#Make the walls. (x_pos, y_pos, width, height)
# This is a list of walls. Each is in the form [x, y, width, height]
walls = [[0, 0, 20, 250, WHITE],
[0, 350, 20, 250, WHITE],
[780, 0, 20, 250, WHITE],
[780, 350, 20, 250, WHITE],
[20, 0, 760, 20, WHITE],
[20, 580, 760, 20, WHITE],
[390, 50, 20, 500, BLUE]
]
# Loop through the list. Create the wall, add it to the list
for item in walls:
wall = Wall(item[0], item[1], item[2], item[3], item[4])
self.wall_list.add(wall)
def main():
pygame.init()
global FPSCLOCK, screen, my_font, munch_sound, bunny_sound, potion_sound, COOKIEVENT, PEVENT, REVENT
FPSCLOCK = pygame.time.Clock()
munch_sound = pygame.mixer.Sound('crunch.wav')
bunny_sound = pygame.mixer.Sound('sneeze.wav')
screen = pygame.display.set_mode((WIDTH,HEIGHT))
my_font = pygame.font.SysFont('Browallia New', 34, bold = False, italic = False)
pygame.display.set_caption('GRABBIT')
#Sounds
pygame.mixer.music.load('Music2.mp3')
pygame.mixer.music.play(-1,0.0)
potion_sound = pygame.mixer.Sound('Correct.wav')
COOKIEVENT = pygame.USEREVENT
pygame.time.set_timer(COOKIEVENT, 3000)
REVENT = pygame.USEREVENT + 3
pygame.time.set_timer(REVENT, 5000)
PEVENT = pygame.USEREVENT + 2
pygame.time.set_timer(PEVENT ,5000)
showStartScreen()
while True:
level1_init()
showGameOverScreen
def level1_init():
global COOKIEVENT, PEVENT, REVENT
finish = False
win = False
gameOverMode = False
move = True
MAXHEALTH = 3
SCORE = 0
count = 10
COOKIEVENT = pygame.USEREVENT
pygame.time.set_timer(COOKIEVENT, 3000)
REVENT = pygame.USEREVENT + 3
pygame.time.set_timer(REVENT, 5000)
PEVENT = pygame.USEREVENT + 2
pygame.time.set_timer(PEVENT ,5000)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
terminate()
def drawHealthMeter(currentHealth):
for i in range(currentHealth): # draw health bars
pygame.draw.rect(screen, BLUE, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10))
for i in range(MAXHEALTH): # draw the white outlines
pygame.draw.rect(screen, WHITE, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10), 1)
if event.type == COOKIEVENT:
if win == False and gameOverMode == False:
add_candy(candies)
if event.type == PEVENT:
if win == False and gameOverMode == False:
add_potion(potions)
if event.type == REVENT:
if win == False and gameOverMode == False:
add_raccoon(raccoons)
if move == True:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
hero.rect.top -= TILE_SIZE
elif event.key == pygame.K_DOWN:
hero.rect.top += TILE_SIZE
elif event.key == pygame.K_RIGHT:
hero.rect.right += TILE_SIZE
elif event.key == pygame.K_LEFT:
hero.rect.right -= TILE_SIZE
elif event.key == pygame.K_ESCAPE:
terminate()
screen.fill((DARKGRAY))
grass = pygame.image.load('grass.jpg')
for x in range(int(WIDTH/grass.get_width()+3)):
for y in range(int(HEIGHT/grass.get_height()+3)):
screen.blit(grass,(x*100,y*100))
candies.draw(screen)
pcandies.draw(screen)
potions.draw(screen)
hero_group.draw(screen)
raccoons.draw(screen)
playerObj = {'health': MAXHEALTH}
drawHealthMeter(playerObj['health'])
#Collision with Raccoon
instantdeath = pygame.sprite.groupcollide(hero_group, raccoons, False, True)
if len(instantdeath) > 0:
bunny_sound.play()
MAXHEALTH = 0
#Health Potions
morehealth = pygame.sprite.groupcollide(hero_group, potions, False, True)
if len(morehealth) > 0:
potion_sound.play()
MAXHEALTH = MAXHEALTH + 1
#Collision with Bad Cookies
bad = pygame.sprite.groupcollide(hero_group, pcandies, False, True)
if len(bad) > 0:
bunny_sound.play()
MAXHEALTH = MAXHEALTH - 1
if playerObj['health'] == 0:
gameOverMode = True
move = False
grave.image = pygame.image.load('grave.png')
grave.rect = grave.image.get_rect(left = hero.rect.left, top = hero.rect.top)
screen.blit(grave.image, grave.rect)
#Collision with Good Cookies
collides = pygame.sprite.groupcollide(hero_group, candies, False, True)
if len(collides) > 0:
munch_sound.play()
SCORE += 1
if len(candies) == 0:
win = True
scoretext = my_font.render("Score = "+str(SCORE), 1, (255, 255, 255))
screen.blit(scoretext, (520, 5))
#If you collide with Racoon
if gameOverMode == True:
font = pygame.font.SysFont('Browallia New', 36, bold = False, italic = False)
text_image = font.render("You Lose. Game Over!", True, (255, 255, 255))
text_rect = text_image.get_rect(centerx=WIDTH/2, centery=100)
screen.blit(text_image, text_rect)
if win:
move = False
CEVENT = pygame.USEREVENT + 5
pygame.time.set_timer(CEVENT, 1000)
if count > 0:
if event.type == CEVENT:
count -= 1
text_image = my_font.render('You won! Next level will begin in ' + str(count) + ' seconds', True, (255, 255, 255))
text_rect = text_image.get_rect(centerx=WIDTH/2, centery=100)
screen.blit(text_image, text_rect)
score_text_image = my_font.render("You achieved a score of " + str(SCORE), True, (255, 255, 255))
score_text_rect = score_text_image.get_rect(centerx = WIDTH/2, centery = 150)
screen.blit(score_text_image, score_text_rect)
if count == 0:
showlevel2StartScreen()
win = False
level2_init()
pygame.display.update()
main()
pygame.quit()
The error comes up as:
Traceback (most recent call last):
File "F:\Year 10\IST\Programming\Pygame\Final Game\Final Game - Grabbit.py", line 426, in <module>
main()
File "F:\Year 10\IST\Programming\Pygame\Final Game\Final Game - Grabbit.py", line 284, in main
level1_init()
File "F:\Year 10\IST\Programming\Pygame\Final Game\Final Game - Grabbit.py", line 324, in level1_init
if event.type == COOKIEVENT:
UnboundLocalError: local variable 'event' referenced before assignment
Is anyone able to suggest what I could do to fix this? Would also appreciate any tips for improvements in my code. I'm a beginner at python and this is the first project I've undertaken using this coding language. Thank you.
The event variable is not initialized in the line
if event.type == COOKIEVENT:
You may need to indent that part of the code so that it goes inside the loop
for event in pygame.event.get():
....
if event.type == COOKIEVENT:`

Categories

Resources