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:`
Related
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()
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
# [...]
I want to know how to Display a "You Win" and a picture at the end of the game when my player reaches 2000 score in the game. I also want to randomly display a hint when the player collides with the class Reseta. Below is my current code. Please be patient with me. Thank you!
import pygame
import os
import random
pygame.init()
pygame.display.set_caption("Chimera")
SCREEN_HEIGHT = 576
SCREEN_WIDTH = 936
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
RUNNING = [pygame.transform.scale(pygame.image.load("images/Main1_side_right.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_1.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_2.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_3.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_4.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_5.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_6.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Main1_side_right_7.png"), (64,64))]
JUMPING = pygame.transform.scale(pygame.image.load("images/Main1_jump_right.png"), (64,64))
DUCKING = [pygame.transform.scale(pygame.image.load("images/slide3.png"), (64, 64)),
pygame.transform.scale(pygame.image.load("images/slide3.png"), (64,64))]
TREE = [pygame.transform.scale(pygame.image.load("images/Tree_1.png"), (64,140)),
pygame.transform.scale(pygame.image.load("images/Tree_1.png"), (64,140)),
pygame.transform.scale(pygame.image.load("images/Tree_2.png"), (64,140))]
BOX = [pygame.transform.scale(pygame.image.load("images/box1.png"), (110,90)),
pygame.transform.scale(pygame.image.load("images/box2.png"), (110,90)),
pygame.transform.scale(pygame.image.load("images/box3.png"), (110,90))]
SHADOW = [pygame.transform.scale(pygame.image.load("images/Enemy_1.png"), (64,64)),
pygame.transform.scale(pygame.image.load("images/Enemy_2.png"), (64,64)),]
PORTAL = [pygame.transform.scale(pygame.image.load("images/portal_real.png"), (64,128)),
pygame.transform.scale(pygame.image.load("images/portal_real.png"), (64,128)),
pygame.transform.scale(pygame.image.load("images/portal_real.png"), (64,128))]
RESETA = [pygame.transform.scale(pygame.image.load("images/reseta_real.png"), (45,120)),
pygame.transform.scale(pygame.image.load("images/reseta_real.png"), (45,120)),
pygame.transform.scale(pygame.image.load("images/reseta_real.png"), (45,120))]
DRUG = [pygame.transform.scale(pygame.image.load("images/Drug.png"), (45,90)),
pygame.transform.scale(pygame.image.load("images/Drug.png"), (45,90)),
pygame.transform.scale(pygame.image.load("images/Drug.png"), (45,90))]
STANDING = pygame.transform.scale(pygame.image.load("images/Main1_front.png"), (64,64))
BG = pygame.image.load(os.path.join("images", "Background_2.jpg"))
class Boy:
X_POS = 80
Y_POS = 390
Y_POS_DUCK = 430
JUMP_VEL = 8.5
def __init__(self):
self.duck_img = DUCKING
self.run_img = RUNNING
self.jump_img = JUMPING
self.boy_duck = False
self.boy_run = True
self.boy_jump = False
self.step_index = 0
self.jump_vel = self.JUMP_VEL
self.image = self.run_img[0]
self.boy_rect = self.image.get_rect()
self.boy_rect.x = self.X_POS
self.boy_rect.y = self.Y_POS
def update(self, userInput):
if self.boy_duck:
self.duck()
if self.boy_run:
self.run()
if self.boy_jump:
self.jump()
if self.step_index >= 10:
self.step_index = 0
if userInput[pygame.K_UP] and not self.boy_jump:
self.boy_duck = False
self.boy_run = False
self.boy_jump = True
elif userInput[pygame.K_DOWN] and not self.boy_jump:
self.boy_duck = True
self.boy_run = False
self.boy_jump = False
elif not (self.boy_jump or userInput[pygame.K_DOWN]):
self.boy_duck = False
self.boy_run = True
self.boy_jump = False
def duck(self):
self.image = self.duck_img[self.step_index // 5]
self.boy_rect = self.image.get_rect()
self.boy_rect.x = self.X_POS
self.boy_rect.y = self.Y_POS_DUCK
self.step_index += 1
def run(self):
self.image = self.run_img[self.step_index // 5]
self.boy_rect = self.image.get_rect()
self.boy_rect.x = self.X_POS
self.boy_rect.y = self.Y_POS
self.step_index += 1
def jump(self):
self.image = self.jump_img
if self.boy_jump:
self.boy_rect.y -= self.jump_vel * 4
self.jump_vel -= 0.8
if self.jump_vel < - self.JUMP_VEL:
self.boy_jump = False
self.jump_vel = self.JUMP_VEL
def draw(self, SCREEN):
SCREEN.blit(self.image, (self.boy_rect.x, self.boy_rect.y))
class Obstacle:
def __init__(self, image, type):
self.image = image
self.type = type
self.rect = self.image[self.type].get_rect()
self.rect.x = SCREEN_WIDTH
def update(self):
self.rect.x -= game_speed
if self.rect.x < -self.rect.width:
obstacles.pop()
def draw(self, SCREEN):
SCREEN.blit(self.image[self.type], self.rect)
class Box(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 380
class Tree(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 325
class Shadow(Obstacle):
def __init__(self, image):
self.type = 0
super().__init__(image, self.type)
self.rect.y = 390
self.index = 0
def draw(self, SCREEN):
if self.index >= 9:
self.index = 0
SCREEN.blit(self.image[self.index//5], self.rect)
self.index += 1
class Drug(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 325
class Portal(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 300
class Reseta(Obstacle):
def __init__(self, image):
self.type = random.randint(0, 2)
super().__init__(image, self.type)
self.rect.y = 350
def main():
global game_speed, x_pos_bg, y_pos_bg, points, obstacles
run = True
clock = pygame.time.Clock()
player = Boy()
# cloud = Cloud()
game_speed = 10
x_pos_bg = 0
y_pos_bg = 0
points = 0
font = pygame.font.Font('freesansbold.ttf', 20)
obstacles = []
death_count = 0
def score():
global points, game_speed
points += 1
if points % 500 == 0:
game_speed += 1
text = font.render("Points: " + str(points), True, (0, 0, 0))
textRect = text.get_rect()
textRect.center = (850, 30)
SCREEN.blit(text, textRect)
def background():
global x_pos_bg, y_pos_bg
image_width = BG.get_width()
SCREEN.blit(BG, (x_pos_bg, y_pos_bg))
SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))
if x_pos_bg <= -image_width:
SCREEN.blit(BG, (image_width + x_pos_bg, y_pos_bg))
x_pos_bg = 0
x_pos_bg -= game_speed
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
SCREEN.fill((255, 255, 255))
userInput = pygame.key.get_pressed()
background()
player.draw(SCREEN)
player.update(userInput)
if len(obstacles) == 0:
if random.randint(0, 2) == 0:
obstacles.append(Box(BOX))
elif random.randint(0, 2) == 1:
obstacles.append(Tree(TREE))
elif random.randint(0, 2) == 2:
obstacles.append(Shadow(SHADOW))
elif random.randint(0, 2) == 0:
obstacles.append(Portal(PORTAL))
elif random.randint(0, 2) == 0:
obstacles.append(Reseta(RESETA))
elif random.randint(0, 2) == 0:
obstacles.append(Drug(DRUG))
for obstacle in obstacles:
obstacle.draw(SCREEN)
obstacle.update()
if player.boy_rect.colliderect(obstacle.rect):
pygame.time.delay(2000)
death_count += 1
menu(death_count)
score()
clock.tick(30)
pygame.display.update()
def menu(death_count):
global points
run = True
while run:
# SCREEN.fill((255, 255, 255))
SCREEN.blit(BG, (0,0))
font = pygame.font.Font('freesansbold.ttf', 30)
if death_count == 0:
text = font.render("Press any Key to Start", True, (250, 245, 225))
save = font.render("Score 1000 to save the Girl", True, (250, 245, 225))
saveRect = save.get_rect()
saveRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50)
SCREEN.blit(save, saveRect)
elif death_count > 0:
text = font.render("Press any Key to Restart", True, (250, 245, 225))
score = font.render("Your Score: " + str(points), True, (250, 245, 225))
scoreRect = score.get_rect()
scoreRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50)
SCREEN.blit(score, scoreRect)
textRect = text.get_rect()
textRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
SCREEN.blit(text, textRect)
SCREEN.blit(STANDING, (SCREEN_WIDTH // 2 - 20, SCREEN_HEIGHT // 2 - 140))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.KEYDOWN:
main()
menu(death_count=0)
below is the file for the folder of images used in my game.
https://drive.google.com/file/d/1t_kDNw3G1Q6X4KKZ9IfsCmYKpEecz9Ci/view?usp=sharing
There is a very simple way that you can have a "You Win" show up in your game when the score reaches 200. You would need a variable for the score that increases every time something happens. First, you would have to load an image for the "You Win" by doing pygame.image.load(file name.png) then you would have to assign variables for the x-axis and y-axis of the image (I used You_WinX and You_WinY for the example) then you can simply do this:
if score == 2000:
You_WinX = (location on x-axis)
You_WinY = (location in y-axis)
What this would do is when the score reaches the value of 2000, the image of "You Win" will appear where you want it to be on the screen (x,y)
I created a little exemple for you. The only thing you have to remember is the purpose of the method main_loop() contained in my class Game (comments will help you to understand it). Just remember that you add several while loops that depends on a variable you will change in order to change state of the game. Each loop print out different things according to what is its goal.
For the point to reach, just create an invisible rect and check if your player rect collide with the invisible one. If it does, switch your variables in order to get into another loop that will print out something else than your game (in this case you could print out "You won".
For the score, you could add score every time the player does something and check every frame if the score exceed the score you have set to win. In this case, just switch variables in order to change state of the game.
import pygame
# creating screen
screen = pygame.display.set_mode((1000, 500))
class Player(pygame.sprite.Sprite):
"""Defining a little class just to show the player on the screen"""
def __init__(self):
# initialize super class (pygame.sprite.Sprite)
super().__init__()
# defining rect of the player
self.rect = pygame.Rect((100, 100), (100, 100))
self.color = (255, 0, 0)
def move_right(self):
self.rect.x += 20
def show_player(self):
pygame.draw.rect(screen, self.color, self.rect)
class Game:
"""Defining the game class that contains the main loop and main variables"""
def __init__(self):
# defining variables for game loops
self.running = True
self.end_menu = False
self.game = True
# initialising player class
self.pl = Player()
# creating an invisible rect that the player has to reach
self.reach_point = pygame.Rect((500, 100), (100, 100))
def main_loop(self):
"""The goal here is to create several loops. One will be for the main game loop that will contains
the two other loops (as many as you want), when an event you chose will happens, the variable that makes
the loop run will turn on false and the variable that makes the loop of the other stage you want to reach
will turn on true. So you will constantly run a loop because your main loop will end up only if you quit the
game."""
while self.running:
while self.game:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.game = False
if event.type == pygame.KEYDOWN:
# defining just a key for the example
if event.key == pygame.K_d:
self.pl.move_right()
# detecting if the player reach the invisible rect
if self.pl.rect.colliderect(self.reach_point):
self.game = False
self.end_menu = True
# fill the screen in white
screen.fill((255, 255, 255))
# shows the player
self.pl.show_player()
# update the screen
pygame.display.flip()
while self.end_menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.end_menu = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
self.game = True
self.end_menu = False
# fills the screen in order to see the different states of the game
screen.fill((255, 255, 0))
# update the screen
pygame.display.flip()
# initializing the class game
game = Game()
pygame.init()
# calling function `main_loop()` contained in the class Game (initialised as game)
game.main_loop()
pygame.quit()
I made code for the snake game, but now, I am trying to edit that code to have the snake move without having to use the keys. I have tried editing my move function and changing event.type and pygame.keydown, but the snake isn't moving without the keys. When I try to alter the code so the snake moves automatically at a certain point on the grid, the snake automatically dies right after it gets to the coordinate.
import random
import pygame
import tkinter as tk
from tkinter import messagebox
import sys
import time
pygame.display.set_caption('SNAKE GAME BOT!')
class cube(object):
rows = 20
w = 800
def __init__(self, start, dirnx=1, dirny=0, color=(30,144,255)):
self.pos = start
self.dirnx = 1
self.dirny = 0
self.color = color
def move(self, dirnx, dirny):
self.dirnx = dirnx
self.dirny = dirny
self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)
def draw(self, surface, eyes=False):
dis = self.w // self.rows
i = self.pos[0]
j = self.pos[1]
pygame.draw.rect(surface, self.color, (i * dis + 1, j * dis + 1, dis - 2, dis - 2))
if eyes:
centre = dis // 2
radius = 3
circleMiddle = (i * dis + centre - radius, j * dis + 8)
circleMiddle2 = (i * dis + dis - radius * 2, j * dis + 8)
pygame.draw.circle(surface, (0,128,0), circleMiddle, radius)
pygame.draw.circle(surface, (0,128,0), circleMiddle2, radius)
class snake(object):
body = []
turns = {}
def __init__(self, color, pos):
self.color = color
self.head = cube(pos)
self.body.append(self.head)
self.dirnx = 0
self.dirny = 1
self.direction = direction
def move(self):
for i, c in enumerate(self.body):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and self.direction != "right":
self.direction = 'left'
self.dirnx = -1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and self.direction != "left":
self.direction = 'right'
self.dirnx = 1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif (event.key == pygame.K_UP or event.key == pygame.K_w) and self.direction != "down":
self.direction = 'up'
self.dirnx = 0
self.dirny = -1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and self.direction != "up":
self.direction = 'down'
self.dirnx = 0
self.dirny = 1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
p = c.pos[:]
if p in self.turns:
turn = self.turns[p]
c.move(turn[0], turn[1])
if i == len(self.body) - 1:
self.turns.pop(p)
else:
reset = (0, 10)
if c.dirnx == -1 and c.pos[0] <= 0:
show_score(0, red, 'times', 75, len(s.body))
time.sleep(1)
s.reset(reset)
elif c.dirnx == 1 and c.pos[0] >= c.rows - 1:
show_score(0, red, 'times', 75, len(s.body))
time.sleep(1)
s.reset(reset)
elif c.dirny == 1 and c.pos[1] >= c.rows - 1:
show_score(0, red, 'times', 75, len(s.body))
time.sleep(1)
s.reset(reset)
elif c.dirny == -1 and c.pos[1] <= 0:
show_score(0, red, 'times', 75, len(s.body))
time.sleep(1)
s.reset(reset)
else:
c.move(c.dirnx, c.dirny)
def reset(self, pos):
self.head = cube(pos)
self.body = []
self.body.append(self.head)
self.turns = {}
self.dirnx = 0
self.dirny = 1
def addCube(self):
tail = self.body[-1]
dx, dy = tail.dirnx, tail.dirny
if dx == 1 and dy == 0:
self.body.append(cube((tail.pos[0] - 1, tail.pos[1])))
elif dx == -1 and dy == 0:
self.body.append(cube((tail.pos[0] + 1, tail.pos[1])))
elif dx == 0 and dy == 1:
self.body.append(cube((tail.pos[0], tail.pos[1] - 1)))
elif dx == 0 and dy == -1:
self.body.append(cube((tail.pos[0], tail.pos[1] + 1)))
self.body[-1].dirnx = dx
self.body[-1].dirny = dy
def draw(self, surface):
for i, c in enumerate(self.body):
if i == 0:
c.draw(surface, True)
else:
c.draw(surface)
def drawGrid(w, rows, surface):
sizeBtwn = w // rows
x = 0
y = 0
for l in range(rows):
x = x + sizeBtwn
y = y + sizeBtwn
pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, w))
pygame.draw.line(surface, (255, 255, 255), (0, y), (w, y))
def redrawWindow(surface):
global rows, width, s, snack
surface.fill((154,205,50))
s.draw(surface)
snack.draw(surface)
drawGrid(width, rows, surface)
pygame.display.update()
def randomSnack(rows, item):
positions = item.body
while True:
x = random.randrange(rows)
y = random.randrange(rows)
if len(list(filter(lambda z: z.pos == (x, y), positions))) > 0:
continue
else:
break
return (x, y)
def message_box(subject, content):
root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
messagebox.showinfo(subject, content)
try:
root.destroy()
except:
pass
def show_score(choice, color, font, size, score):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('BOTS SCORE : ' + str(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (60, 60)
else:
score_rect.midtop = (400, 400)
win.blit(score_surface, score_rect)
pygame.display.flip()
def main():
global width, rows, s, snack, win, direction, red
direction = 'right'
width = 800
rows = 20
red = pygame.Color(255, 0, 0)
check_errors = pygame.init()
if check_errors[1] > 0:
print(f'[!] Had {check_errors[1]} errors when initializing game, exiting...')
sys.exit(-1)
else:
print('[+] Game successfully initialized')
win = pygame.display.set_mode((width, width))
s = snake((30,144,255), (0, 10))
snack = cube(randomSnack(rows, s), color=(255, 0, 0))
flag = True
clock = pygame.time.Clock()
while flag:
pygame.time.delay(1)
clock.tick(10)
s.move()
if s.body[0].pos == snack.pos:
s.addCube()
snack = cube(randomSnack(rows, s), color=(255, 0, 0))
for x in range(len(s.body)):
if s.body[x].pos in list(map(lambda z: z.pos, s.body[x + 1:])):
show_score(0, red, 'times', 80, len(s.body))
print('BOTS SCORE: ', len(s.body))
time.sleep(1)
s.reset((0, 10))
break
redrawWindow(win)
main()
Please Help!
import pygame
import random
import os
from Snake import Snake
from Food import Food
from Block import Block
from World import worlds
from tkinter import *
import tkinter.simpledialog
head_path = os.path.join('Assets','Images','head.png')
index3_path = os.path.join('Assets','Images','index3.jpg')
python_path = os.path.join( 'Assets','Images','python.jpg')
point_path = os.path.join('Assets','Sounds','Point.wav')
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()
pygame.init()
#intiating sounds
intro_sound = pygame.mixer.Sound(os.path.join('Assets','Sounds','intro.wav'))
game_sound = pygame.mixer.Sound(os.path.join('Assets','Sounds','gamesound.wav'))
pause_sound = pygame.mixer.Sound(os.path.join('Assets','Sounds','pausesound.wav'))
endgame_sound = pygame.mixer.Sound(os.path.join('Assets','Sounds','endsound.wav'))
#the volume are set such that sounds are pleasant
intro_sound.set_volume(0.1)
game_sound.set_volume(0.6)
pause_sound.set_volume(0.1)
endgame_sound.set_volume(0.12)
width, height = 1000, 600
game_display = pygame.display.set_mode((width, height))
game_display.fill((170,150,255))
blist=[]
pygame.display.set_caption('SNAKES')
img = pygame.image.load(head_path)
pygame.display.set_icon(img)
dirn = "right"
clock = pygame.time.Clock()
font = pygame.font.SysFont("comicsansms", 35)
FPS = 25
def total(score, i):
""" function for total score """
return score + i * 10
# for highscore
highscorefile = open('highscore.txt', 'rt')
highscore = highscorefile.readline()
try:
highscore = int(highscore)
except ValueError:
highscore = 0
namehighscore = highscorefile.readline()
highscorefile.close()
def pause(scorestr):
#stop in game music and play pause music
game_sound.stop()
pause_sound.play(-1)
paused = True
while paused:
showButton()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
keyp = action()
if event.type == pygame.KEYDOWN or keyp != None:
try:
if keyp == 'c' or event.key == pygame.K_c:
paused = False
except:
pass
try:
if keyp == 'q' or event.key == pygame.K_q:
print('quit')
pygame.quit()
quit()
except:
pass
message("Paused", (0, 0, 0))
message("C to continue, Q to Quit", (200, 0, 0), 40)
# display score on pause
message(scorestr, (255, 0, 0), 80)
pygame.display.update()
clock.tick(5)
#stop pause music and play in game music if game continues
if paused == False:
pause_sound.stop()
game_sound.play(-1)
def button(msg,x,y,w,h):
mouse = pygame.mouse.get_pos()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(game_display, (0,0,250),(x,y,w,h))
else:
pygame.draw.rect(game_display, (0,0,100),(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
text= smallText.render(msg, True, (0,200,0))
t=text.get_rect()
t.center = ( (x+(w/2)), (y+(h/2)) )
game_display.blit(text, t)
def intro():
#play intro music infinite loop
intro_sound.play(-1)
i=True
while i:
for event in pygame.event.get():
keyp=action()
if event.type==pygame.QUIT:
pygame.quit()
quit()
if keyp!=None or event.type==pygame.KEYDOWN :
try:
if keyp=='c' or event.key==pygame.K_c :
i=False
except:
continue
showButton()
image = pygame.image.load(index3_path)
game_display.blit(image,(0,0))
message(" Welcome to Snakes!!",(200,0,0),-59)
message("Press C to continue",(100,0,100),260)
pygame.display.update()
clock.tick(15)
def showButton():
global blist
pygame.draw.rect(game_display, (170, 150, 255), (800, 0, 200, 600))
button("Continue", 800, 200, 130, 30)
blist.append((800, 200, 130, 30,'c'))
button("Exit", 935, 200, 65, 30)
blist.append((935, 200, 65, 30,'q'))
button("Up", 870, 235, 50, 30)
blist.append((870, 235, 50, 30,'up'))
button("Down", 865, 305, 60, 30)
blist.append((865, 305, 60, 30,'dn'))
button("Right", 895, 270, 60, 30)
blist.append((895, 270, 60, 30,'rt'))
button("Left", 830, 270, 60, 30)
blist.append((830, 270, 60, 30,'lt'))
button("Pause",830,340,125,30)
blist.append((830,340,125,30,'p'))
button("Shift", 830, 375, 125, 30)
blist.append((830, 375, 125, 30,'st'))
pygame.draw.line(game_display,(0,200,100),(800,0),(800,600),5)
def action():
global blist
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
for tup in blist:
if tup[0] + tup[2] > mouse[0] > tup[0] and tup[1] + tup[3] > mouse[1] > tup[1]:
if click[0] == 1:
return tup[4]
return None
def message(m, color, dispy=0):
text = font.render(m, True, color)
t = text.get_rect()
t.center = (400), (300) + dispy
game_display.blit(text, t)
def food_collides_block(food_rect, blocks):
""" Returns True if any of the blocks collide with the food """
for block in blocks:
if food_rect.colliderect(block.get_rect()):
return True
return False
def get_blocks(food_rect, n):
""" Generates `n` blocks at random x, y """
blocks = list()
for i in range(n):
block_x = round(random.randrange(0, (width)) / 10.0) * 10
block_y = round(random.randrange(0, height) / 10.0) * 10
block_width, block_height = 10, 10
block = Block(block_x, block_y, block_width, block_height)
# if the block collides with food, generate at other x, y.
if food_rect.colliderect(block.get_rect()):
i -= 1
continue
blocks.append(block)
return blocks
def gameLoop():
global dirn, k, highscore, namehighscore
pyExit = False
pyOver = False
#stop intro music and play in game music infinite loop
intro_sound.stop()
game_sound.play(-1)
score = 0
world_num = 0
scorestr = "Score:0"
# Initialize the game
snake = Snake(200, 200, img)
food = Food(int(width / 2), int(height / 2))
blocks = worlds(width - 200, height, world_num)
# Keeps track of the direction of the snake.
dx, dy = 0, 0
lossreason = ''
while not pyExit:
if pyOver == True:
#play end music
endgame_sound.play(-1)
while pyOver:
image = pygame.image.load(python_path)
game_display.blit(image, (0, 0))
message("Game Over! Press C to play Again, Q to Quit",
(255, 0, 0), -20)
message(lossreason, (255, 0, 0), 30)
# display score on game over
message("Your" + scorestr, (255, 0, 0), 80)
if totalscore > highscore:
# message("Highscore!!!",(255,0,0),120)
# write new highscore
highscorefile = open('highscore.txt', 'wt')
highscorefile.write(str(totalscore) + "\n")
# name window
def namewrite():
highscorefile.write(v.get())
scorewindow.destroy()
scorewindow = Tk()
scorewindow.geometry('300x100')
frame = Frame(scorewindow, width=100, height=100)
frame.pack()
scorewindow.title("congratulations")
Label(frame, text='you\'ve made highscore!!!!').pack(side='top')
v = StringVar()
v.set("type your name")
textbox = Entry(frame, textvariable=v)
textbox.pack(side='top')
okbutton = Button(frame, text="ok", fg="black",
bg="white", command=namewrite)
okbutton.pack(side='bottom')
scorewindow.mainloop()
highscorefile.close()
# incase user wants to countinue after creating highscore
# to read his new score
highscorefile = open('highscore.txt', 'rt')
highscore = highscorefile.readline()
highscore = int(highscore)
namehighscore = highscorefile.readline()
highscorefile.close()
else:
message("Highscore by " + namehighscore +
":" + str(highscore), (255, 0, 0), 120)
pygame.display.update()
for event in pygame.event.get():
keyp = action()
if keyp != None or event.type == pygame.KEYDOWN:
try:
if keyp == 'q' or event.key == pygame.K_q:
pyExit = True
pyOver = False
except:
blank = [] # bypass the exception
try:
if keyp == 'c' or event.key == pygame.K_c:
#stop endgame music
endgame_sound.stop()
gameLoop()
except:
blank = [] # bypass the exception
""" Events """
#the conditions are modified to work with the buttons
for event in pygame.event.get():
keyp = action()
# blank is not used anywhere
# it is just used to jump the exception
if event.type == pygame.QUIT:
pyExit = True
if event.type == pygame.KEYDOWN or keyp != None:
try:
if keyp == 'lt' or event.key == pygame.K_LEFT and dirn != "right":
dirn = "left"
dx = -1
dy = 0
except:
blank = []
try:
if keyp == 'rt' or event.key == pygame.K_RIGHT and dirn != "left":
dirn = "right"
dx = 1
dy = 0
except:
blank = []
try:
if keyp == 'up' or event.key == pygame.K_UP and dirn != "down":
dirn = "up"
dy = -1
dx = 0
except:
blank = []
try:
if keyp == 'dn' or event.key == pygame.K_DOWN and dirn != "up":
dirn = "down"
dy = 1
dx = 0
except:
blank = []
try:
if keyp == 'p' or event.key == pygame.K_p:
pause(scorestr)
except:
blank = []
try:
if keyp == 'q' or event.key == pygame.K_q:
pygame.quit()
quit(0)
except:
blank = []
# level changer value
if score > 10:
score = 0
world_num += 1
blocks = worlds(width - 200, height, world_num)
food.x, food.y = int(width / 2), int(height / 2)
# Engage boost of pressing shift
keyp=action()
keyPresses = pygame.key.get_pressed()
boost_speed = keyPresses[pygame.K_LSHIFT] or keyPresses[pygame.K_RSHIFT] or keyp=='st'
# if boost_speed is true it will move 2 blocks in one gameloop
# else it will just move one block
iterations = [1]
if boost_speed == 1:
iterations.append(2)
for i in iterations:
""" Update snake """
snake.move(dx, dy, 10)
snake.check_boundary(width, height)
snake_rect = snake.get_rect()
food_rect = food.get_rect()
""" Snake-Snake collision """
if snake.ate_itself():
#stop game sound
game_sound.stop()
pyOver = True
lossreason = 'Oooops You Hit YOURSELF'
""" Snake-Block collision """
for block in blocks:
block_rect = block.get_rect()
if block_rect.colliderect(snake_rect):
#stop game sound
game_sound.stop()
pyOver = True
lossreason = 'Ooops You Hit a BLOCKER'
""" Snake-Food collision """
# if snake collides with food, increase its length.
if food_rect.colliderect(snake_rect):
score += 1
snake.increment_length()
sound = pygame.mixer.Sound(point_path)
sound.set_volume(0.3)
sound.play()
# generate food at random x, y.
food.generate_food(width, height)
# try generating the food at a position where blocks are not present.
while food_collides_block(food.get_rect(), blocks):
food.generate_food(width - food.size, height - food.size)
""" Draw """
game_display.fill((255, 255, 255))
showButton()
# draw the food and snake.
snake.draw(game_display, dirn, (0, 155, 0))
food.draw(game_display, (0, 255, 0))
# draw the blocks.
for block in blocks:
block.draw(game_display, (255, 0, 0))
# count and display score on screen
totalscore = total(score, world_num)
scorestr = 'Score: ' + str(totalscore)
font = pygame.font.SysFont(None, 30)
text = font.render(scorestr, True, (0, 0, 255))
game_display.blit(text, (0, 0, 20, 20))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
intro()
gameLoop()
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")