How to fix Process finished with exit code -805306369 (0xCFFFFFFF) - pygame

I've been getting a weird bug were my game crashes randomly with exit code -805306369 (0xCFFFFFFF) in PyCharm
and I think the error is somewhere in my while loop but idk where
While loop:
while True:
clock.tick(FPS)
# Start screen
if Starting_screen is True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
screen.fill((101, 67, 33))
screen.blit(Start_game_box, Start_game_box_rect)
screen.blit(Play_game_text, Play_game_text_rect)
screen.blit(Game_name_text, Game_name_text_rect)
screen.blit(Pepsi_credits_text, Pepsi_credits_text_rect)
screen.blit(Brew_credits_text, Brew_credits_text_rect)
screen.blit(Q_credits_text, Q_credits_text_rect)
screen.blit(mouse, mouse_rect)
mouse_pos = pygame.mouse.get_pos()
if pygame.MOUSEMOTION:
mx, my = mouse_pos
mouse_rect.x = mx
mouse_rect.y = my
mouse_pressed = pygame.mouse.get_pressed()
if (mouse_pressed[0]) and mouse_rect.colliderect(Start_game_box_rect):
Main_tycoon_screen = True
Play_game_text_rect.x = 9999
Game_name_text_rect.x = 9999
Start_game_box_rect.x = 9999
print(Main_tycoon_screen)
Starting_screen = False
print(Starting_screen)
pygame.display.update()
if Main_tycoon_screen is True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.fill((101, 67, 33))
screen.blit(dropper1, (100, 400))
screen.blit(conveyor1, (100, 450))
screen.blit(dropper1_block, dropperblock1_rect)
screen.blit(sell_block1, sell_block1_rect)
screen.blit(Buy_block1, Buy_block1_rect)
screen.blit(Buy1_cost_text, Buy1_cost_text_rect)
# functions
spawn_dropper2()
spawn_dropper3()
spawn_dropper4()
spawn_dropper5()
spawn_dropper6()
spawn_dropper7()
spawn_dropper8()
spawn_dropper9()
spawn_dropper10()
spawn_dropper11()
spawn_dropper_rainbow()
spawn_conveyor2()
setting_stuff()
dropperblock1_rect.x += 2
mouse_pos = pygame.mouse.get_pos()
if pygame.MOUSEMOTION:
mx, my = mouse_pos
mouse_rect.x = mx
mouse_rect.y = my
screen.blit(mouse, mouse_rect)
# sell block collisions
if dropperblock12_rect.colliderect(sell_block1_rect):
monet += 500
dropperblock12_rect.x = 70
print(monet)
if dropperblock11_rect.colliderect(sell_block1_rect):
monet += 100
dropperblock11_rect.x = 560
print(monet)
if dropperblock10_rect.colliderect(sell_block1_rect):
monet += 70
dropperblock10_rect.x = 460
print(monet)
if dropperblock9_rect.colliderect(sell_block1_rect):
monet += 50
dropperblock9_rect.x = 360
print(monet)
if dropperblock8_rect.colliderect(sell_block1_rect):
monet += 30
dropperblock8_rect.x = 260
print(monet)
if dropperblock7_rect.colliderect(sell_block1_rect):
monet += 20
dropperblock7_rect.x = 160
print(monet)
if dropperblock6_rect.colliderect(sell_block1_rect):
monet += 15
dropperblock6_rect.x = 600
print(monet)
if dropperblock5_rect.colliderect(sell_block1_rect):
monet += 15
dropperblock5_rect.x = 500
print(monet)
if dropperblock4_rect.colliderect(sell_block1_rect):
monet += 10
dropperblock4_rect.x = 400
print(monet)
if dropperblock3_rect.colliderect(sell_block1_rect):
monet += 8
dropperblock3_rect.x = 300
print(monet)
if dropperblock2_rect.colliderect(sell_block1_rect):
monet += 6
dropperblock2_rect.x = 200
print(monet)
if dropperblock1_rect.colliderect(sell_block1_rect):
monet += 5
dropperblock1_rect.x = 100
print(monet)
# Buy block collisions
mouse_pressed = pygame.mouse.get_pressed()
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block1_rect) and monet >= 10:
monet -= 10
Buy_block1_rect.x = 999
Buy_block1_rect.y = 999
Spawn_dropper2 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block2_rect) and monet >= 30:
monet -= 30
Buy_block2_rect.x = 999
Buy_block2_rect.y = 999
Buy2_cost_text_rect.x = 999
Spawn_dropper3 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block3_rect) and monet >= 100:
monet -= 100
Buy_block3_rect.x = 999
Buy_block3_rect.y = 999
Buy3_cost_text_rect.x = 999
Spawn_dropper4 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block4_rect) and monet >= 200:
monet -= 200
Buy_block4_rect.x = 999
Buy_block4_rect.y = 999
Buy4_cost_text_rect.x = 999
Spawn_dropper5 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block5_rect) and monet >= 500:
monet -= 500
Buy_block5_rect.x = 999
Buy_block5_rect.y = 999
Buy5_cost_text_rect.x = 999
Spawn_dropper6 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block6_rect) and monet >= 1000:
monet -= 1000
Buy_block6_rect.x = 999
Buy_block6_rect.y = 999
Buy6_cost_text_rect.x = 999
Spawn_dropper7 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block7_rect) and monet >= 1500:
monet -= 1500
Buy_block7_rect.x = 999
Buy_block7_rect.y = 999
Buy7_cost_text_rect.x = 999
Spawn_dropper8 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block8_rect) and monet >= 2000:
monet -= 2000
Buy_block8_rect.x = 999
Buy_block8_rect.y = 999
Buy8_cost_text_rect.x = 999
Spawn_dropper9 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block9_rect) and monet >= 3000:
monet -= 3000
Buy_block9_rect.x = 999
Buy_block9_rect.y = 999
Buy9_cost_text_rect.x = 999
Spawn_dropper10 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block10_rect) and monet >= 4000:
monet -= 4000
Buy_block10_rect.x = 999
Buy_block10_rect.y = 999
Buy10_cost_text_rect.x = 999
Spawn_dropper11 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_block11_rect) and monet >= 5000:
monet -= 5000
Buy_block11_rect.x = 999
Buy_block11_rect.y = 999
Buy11_cost_text_rect.x = 999
Spawn_dropper12 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
if (mouse_pressed[0]) and mouse_rect.colliderect(Buy_conveyor2_block_rect) and monet >= 10000:
monet -= 10000
Buy_conveyor2_block_rect.x = 999
Buy_conveyor2_text_rect.x = 999
Spawn_conveyor2 = True
print(monet)
pygame.mixer.Sound.play(Buying_dropper_sound)
draw_monet_counter(f"monet: {monet}", "white", 60, 600, 50)
pygame.display.update()
and here are the funcitons
Spawn_conveyor2 = False
Spawn_dropper2 = False
Spawn_dropper3 = False
Spawn_dropper4 = False
Spawn_dropper5 = False
Spawn_dropper6 = False
Spawn_dropper7 = False
Spawn_dropper8 = False
Spawn_dropper9 = False
Spawn_dropper10 = False
Spawn_dropper11 = False
Spawn_dropper12 = False
Spawn_pho_dropper1 = False
def spawn_conveyor2():
if Spawn_conveyor2 is True:
screen.blit(conveyor2, (100, 200))
Buy_conveyor2_block_rect.x = 999
Buy_conveyor2_text_rect.x = 9999
Buy_pho1_rect.x = 110
screen.blit(Buy_pho1, Buy_pho1_rect)
def spawn_dropper2():
if Spawn_dropper2 is True:
Buy_block1_rect.x = 2400
screen.blit(Buy2_cost_text, Buy2_cost_text_rect)
screen.blit(dropper2, (200, 390))
screen.blit(dropper2_block, dropperblock2_rect)
Buy_block2_rect.x = 300
screen.blit(Buy_block2, Buy_block2_rect)
dropperblock2_rect.x += 2
Buy1_cost_text_rect.x = 999
def spawn_dropper3():
if Spawn_dropper3 is True:
screen.blit(dropper3, (300, 390))
screen.blit(dropper3_block, dropperblock3_rect)
dropperblock3_rect.x += 2
Buy_block3_rect.x = 400
screen.blit(Buy_block3, Buy_block3_rect)
screen.blit(Buy3_cost_text, Buy3_cost_text_rect)
def spawn_dropper4():
if Spawn_dropper4 is True:
screen.blit(dropper4, (400, 390))
screen.blit(dropper4_block, dropperblock4_rect)
dropperblock4_rect.x += 2
Buy_block4_rect.x = 500
screen.blit(Buy_block4, Buy_block4_rect)
screen.blit(Buy4_cost_text, Buy4_cost_text_rect)
def spawn_dropper5():
if Spawn_dropper5 is True:
screen.blit(dropper5, (500, 390))
screen.blit(dropper5_block, dropperblock5_rect)
dropperblock5_rect.x += 2
Buy_block5_rect.x = 600
screen.blit(Buy_block5, Buy_block5_rect)
screen.blit(Buy5_cost_text, Buy5_cost_text_rect)
def spawn_dropper6():
if Spawn_dropper6 is True:
screen.blit(dropper6, (600, 390))
screen.blit(dropper6_block, dropperblock6_rect)
dropperblock6_rect.x += 1
Buy_block6_rect.x = 160
screen.blit(Buy_block6, Buy_block6_rect)
screen.blit(Buy6_cost_text, Buy6_cost_text_rect)
def spawn_dropper7():
if Spawn_dropper7 is True:
screen.blit(dropper7, (160, 500))
screen.blit(dropper7_block, dropperblock7_rect)
dropperblock7_rect.x += 2
Buy_block7_rect.x = 260
screen.blit(Buy_block7, Buy_block7_rect)
screen.blit(Buy7_cost_text, Buy7_cost_text_rect)
def spawn_dropper8():
if Spawn_dropper8 is True:
screen.blit(dropper8, (260, 500))
screen.blit(dropper8_block, dropperblock8_rect)
dropperblock8_rect.x += 2
Buy_block8_rect.x = 360
screen.blit(Buy_block8, Buy_block8_rect)
screen.blit(Buy8_cost_text, Buy8_cost_text_rect)
screen.blit(Buy_conveyor2_text, Buy_conveyor2_text_rect)
screen.blit(Buy_conveyor2_block, Buy_conveyor2_block_rect)
def spawn_dropper9():
if Spawn_dropper9 is True:
screen.blit(dropper9, (360, 500))
screen.blit(dropper9_block, dropperblock9_rect)
dropperblock9_rect.x += 2
Buy_block9_rect.x = 460
screen.blit(Buy_block9, Buy_block9_rect)
screen.blit(Buy9_cost_text, Buy9_cost_text_rect)
def spawn_dropper10():
if Spawn_dropper10 is True:
screen.blit(dropper10, (460, 500))
screen.blit(dropper10_block, dropperblock10_rect)
dropperblock10_rect.x += 2
Buy_block10_rect.x = 560
screen.blit(Buy_block10, Buy_block10_rect)
screen.blit(Buy10_cost_text, Buy10_cost_text_rect)
def spawn_dropper11():
if Spawn_dropper11 is True:
screen.blit(dropper11, (560, 500))
screen.blit(dropper11_block, dropperblock11_rect)
dropperblock11_rect.x += 2
Buy_block11_rect.x = 40
screen.blit(Buy_block11, Buy_block11_rect)
screen.blit(Buy11_cost_text, Buy11_cost_text_rect)
def spawn_dropper_rainbow():
if Spawn_dropper12 is True:
screen.blit(dropper12, (40, 450))
screen.blit(Rainbow_block_red, (15, 450))
screen.blit(Rainbow_block_blue, (35, 450))
screen.blit(Rainbow_block_yellow, (50, 450))
screen.blit(Rainbow_block_purple, (65, 450))
screen.blit(Rainbow_block_green, (80, 450))
screen.blit(dropper12_block, dropperblock12_rect)
dropperblock12_rect.x += 2
Starting_screen = True
Main_tycoon_screen = False
Setting_On = False
Setting_Off = True
Music = True
def setting_stuff():
global Setting_On, Setting_Off, Music, Tycoon_music1, Starting_screen_music, mouse_pressed
screen.blit(Setting_button, Setting_button_rect)
screen.blit(setting_button_icon, setting_button_icon_rect)
mouse_pressed = pygame.mouse.get_pressed()
if (mouse_pressed[0]) and mouse_rect.colliderect(Setting_button_rect):
Setting_Off = False
Setting_On = True
if Setting_On is True:
Setting_Background_rect.x = 200
exit_setting_button_rect.x = 470
screen.blit(Setting_Background, Setting_Background_rect)
screen.blit(exit_setting_button, exit_setting_button_rect)
setting_button_icon_rect.x = 999
Setting_button_rect.x = 999
pause_music_block_rect.x = 250
pause_music_text_rect.x = 260
screen.blit(pause_music_block, pause_music_block_rect)
screen.blit(pause_music_text, pause_music_text_rect)
unpause_music_block_rect.x = 250
unpause_music_text_rect.x = 260
screen.blit(unpause_music_block, unpause_music_block_rect)
screen.blit(unpause_music_text, unpause_music_text_rect)
if (mouse_pressed[0]) and mouse_rect.colliderect(exit_setting_button_rect):
Setting_On = False
Setting_Off = True
if (mouse_pressed[0]) and mouse_rect.colliderect(pause_music_block_rect):
Music = False
if (mouse_pressed[0]) and mouse_rect.colliderect(unpause_music_block_rect):
Music = True
if Music is False:
pygame.mixer.music.pause()
if Music is True:
pygame.mixer.music.unpause()
if Setting_Off is True:
pause_music_block_rect. x = 999
pause_music_text_rect.x = 999
unpause_music_block_rect.x = 999
unpause_music_text_rect.x = 999
Setting_Background_rect.x = 999
exit_setting_button_rect.x = 999
setting_button_icon_rect.x = 50
Setting_button_rect.x = 50
the error happens when i hit a button in the game sometimes it happens and sometimes not and i dont know how to fix it

It's likely that somehow both your variables Starting_screen and Main_tycoon_screen are becoming False. With both of these false, you are no longer handling the window event queue. The operating system notices your application is no longer processing events (i.e. "Not Responding"), and takes the action of terminating it. This results in the 0xCFFFFFFF code.
I suggest you modify your program to process the window events in a single place, and always process the event queue.
START_SCREEN = 1
GAME_SCREEN = 2
current_screen = START_SCREEN
while True:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
mouse_pos = pygame.mouse.get_pos()
mouse_pressed = pygame.mouse.get_pressed()
clock.tick(FPS)
if ( current_screen == START_SCREEN ):
pass
# TODO paint start screen
# TODO handle start screen events
elif ( current_screen == GAME_SCREEN ):
pass
# TODO paint game screen
# TODO handle game screen events
This framework allows you to switch between the "state" of the application by setting the current_screen variable. But the key point is that is always handling the event queue, no matter what the current_screen.

Related

Pygame not recognizing my mouse when I click down on an in-game item [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How can I add an image or icon to a button rectangle in Pygame?
(1 answer)
Closed 2 years ago.
I have a problem in my code that I want one of your guys to answer.
This is my code:
import pygame
import time
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((1280,720))
pygame.display.set_caption('Title Screen')
titleim = pygame.image.load(r'C:\Users\kp876\Desktop\Temorairy\Kill, Buy, Repeat title screen.png')
menuim = pygame.image.load(r'C:\Users\kp876\Desktop\Menu Screen.png')
playim = pygame.image.load(r'C:\Users\kp876\Desktop\play button.png')
stickmanim = pygame.image.load('stickmanfightpose.png')
shopim = pygame.image.load('shop.png')
rplayim = pygame.transform.scale(playim,(640,360))
rshopim = pygame.transform.scale(shopim,(35,30))
popSound = pygame.mixer.Sound('Pop sound effect.wav')
menumusic = pygame.mixer.music.load('awesomeness.mp3')
screen.blit(titleim,(0,0))
pygame.display.update()
running = True
running_title = True
mouse = False
coins = 10
def redrawTitle():
screen.fill((0,0,0))
screen.blit(titleim,(0,0))
def fade(w,h):
val1 = 1
fade = pygame.Surface((w,h))
fade.fill((0,0,0))
for alpha in range(0, 300, 5):
fade.set_alpha(alpha)
redrawTitle()
screen.blit(fade,(0,0))
pygame.display.update()
def mainmenuText():
font = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 100)
text = font.render('Press Play',True,(210,200,200))
playRect = pygame.Rect((555,480),(150,120))
pygame.draw.rect(screen, (0,0,0), playRect)
screen.blit(menuim,(0,0))
screen.blit(text,(380,340))
screen.blit(rplayim,(310,360))
pygame.display.update()
def shop():
pistol = False
rifle = False
machinegun = False
white = (255,255,255)
screen.fill(white)
global coins
shopfont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 60)
shoptxt = shopfont.render('Shop', True,(0,0,0))
coinstxt = shopfont.render('Coins:' + str(coins) + '!',True,(0,0,0))
namefont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 35)
pistoltxt = namefont.render('Pistol', True, (0,0,0))
rifletxt = namefont.render('Rifle', True, (0,0,0))
machineguntxt = namefont.render('Machine Gun', True, (0,0,0))
mainshopR = pygame.Rect((0,0),(1280,720))
pistolR = pygame.Rect((50,150),(200,200))
rifleR = pygame.Rect((450,150),(200,200))
machinegunR = pygame.Rect((850,150),(200,200))
pygame.draw.rect(screen, white, mainshopR)
pygame.draw.rect(screen, (128,128,128),pistolR)
pygame.draw.rect(screen, (128,128,128),rifleR)
pygame.draw.rect(screen, (128,128,128),machinegunR)
screen.blit(shoptxt,(500,30))
screen.blit(pistoltxt,(100,220))
screen.blit(rifletxt,(500,220))
screen.blit(machineguntxt,(850,220))
screen.blit(coinstxt,(50,30))
pygame.display.update()
if pistol:
pygame.draw.rect(screen, (0,128,0),pistolR)
if rifle:
pygame.draw.rect(screen, (0,128,0),rifleR)
if machinegun:
pygame.draw.rect(screen, (0,128,0),machinegunR)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
spot1 = pygame.mouse.get_pos()
if spot1[0] > 50 and spot1[0] < 250 and spot1[1] > 150 and spot1[1] < 350:
if not pistol:
if coins >= 3:
pistolR = pygame.Rect((50,150),(200,200))
pygame.event.get()
pistol = True
coins = coins - 3
screen.blit(coinstxt,(50,30))
pygame.draw.rect(screen, (0,128,0),pistolR)
pygame.display.update()
pygame.event.get()
if spot1[0] > 450 and spot1[0] < 650 and spot1[1] > 150 and spot1[1] < 350:
if not rifle:
if coins >= 10:
pygame.event.get()
rifle = True
coins = coins - 10
print(coins)
screen.blit(coinstxt,(50,30))
pygame.draw.rect(screen, (0,128,0),rifleR)
pygame.display.update()
pygame.event.get()
if spot1[0] > 850 and spot1[0] < 1050 and spot1[1] > 150 and spot1[1] < 350:
if not machinegun:
if coins >= 30:
pygame.event.get()
machinegun = True
coins = coins - 30
print(coins)
screen.blit(coinstxt,(50,30))
pygame.draw.rect(screen, (0,128,0),machinegunR)
pygame.display.update()
pygame.event.get()
mouse1 = False
val1 = 0
nop = True
music = True
pygame.mixer.music.play(-1)
while running_title:
pygame.event.get()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running_title = False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse1 = True
if mouse1 and val1 == 1:
spot = pygame.mouse.get_pos()
if spot[0] < 705 and spot[0] > 555 and spot[1] < 600 and spot[1] > 480:
pygame.event.get()
White = (255,250,250)
screen.fill(White)
pygame.display.update()
pygame.mixer.music.stop()
popSound.play()
screen.blit(stickmanim,(0,0))
pygame.display.update()
running_title = False
if val1 == 0:
time.sleep(3)
fade(1280,720)
pygame.display.update()
mouse = True
if mouse and nop:
screen.blit(menuim,(0,0))
time.sleep(1)
mainmenuText()
val1 = 1
nop = False
go = True
while running:
if go:
fightR = pygame.Rect((550,300),(100,60))
fightborderR = pygame.Rect((540,294),(120,72))
fightfont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 25)
fightext = fightfont.render('FIGHT!',True,(0,0,0))
shopR = pygame.Rect((100,20),(130,50))
shopborderR = pygame.Rect((90,15),(150,60))
coinsfont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 50)
shoptext = fightfont.render('Shop',True,(0,0,0))
pygame.draw.rect(screen,(0,0,0),fightborderR)
pygame.draw.rect(screen,(128,128,128),fightR)
pygame.draw.rect(screen,(0,0,0),shopborderR)
pygame.draw.rect(screen,(128,128,128),shopR)
screen.blit(fightext,(555,303))
screen.blit(rshopim,(110,30))
screen.blit(shoptext,(150,28))
pygame.display.update()
go = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running_title = False
if event.type == pygame.MOUSEBUTTONDOWN:
spot = pygame.mouse.get_pos()
if spot[0] < 660 and spot[0] > 540 and spot[1] < 366 and spot[1] > 294:
yo = 'yo'
if spot[0] < 240 and spot[0] > 90 and spot[1] > 15 and spot[1] < 85:
shop()
in shop() I want it to recognize when someone clicks an item(pistol,rifle,etc) but whenever i click it nothing happens.
Hopefully this is enough details for you guys to fix my problem.
Thanks!
ps. This code is not finished. So if you are wondering why there is some weird stuff in the code, most likely it's for later on in the project.
I am struggling to understand the logic behind your code, but the problem is caused because you are calling pygame.event.get() multiple times. Its everywhere. Sometimes you are calling it and not even storing it which again is probably not what you want. In your main loop, call it once and store it.
while running:
events = pygame.event.get()
for event in events:
#do stuff with it
Then to get access to events in shop, take events as argument def shop(events) and use this events variable instead of pygame.event.get().
Then in the main loop, when you call shop, pass events as argument.
if spot[0] < 240 and spot[0] > 90 and spot[1] > 15 and spot[1] < 85:
shop(events)
You are also calling pygame.display.update() multiple times, which might cause flickering problems.

Problem creating new enemies when player levels up

i'm working on a simple clone of Space Invaders for an University project. The idea is that when the players levels up, the amount of enemies increase, but when i try to do it, the enemies creates infinitly while the stablished condition is true. I can't dettect the problem, so if one of you can help me, i'll apreciate it.
import random
import csv
import operator
import pygame
import time
from pygame import mixer
# Intialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('background.png')
# Sound
mixer.music.load("background.wav")
mixer.music.play(-1)
#Reloj
clock = pygame.time.Clock()
# Caption and Icon
pygame.display.set_caption("Space Invader")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Score
score_value = 0
level_value = 1
level_up_value = ""
font = pygame.font.Font('freesansbold.ttf', 20)
game_over = False
high_scores = []
names = []
with open('high_scores.csv') as csvfile:
reader = csv.reader(csvfile)
sortedlist = sorted(reader, key=operator.itemgetter(1), reverse=True)
for i in sortedlist:
names.append(i[0])
high_scores.append(i[1])
scoreX = 10
scoreY = 10
level_textX = 10
level_textY = 80
levelX = 10
levelY = 40
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
menu_font = pygame.font.Font('freesansbold.ttf', 48)
scores_font = pygame.font.Font('freesansbold.ttf', 45)
#Número de vidas
num_vidas = 3
font = pygame.font.Font('freesansbold.ttf', 32)
vidasX = 650
vidasY = 10
# Player
playerImg = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemyImg = []
bichoImg = []
meteoroImg = []
enemyX = []
enemyY = []
enemyY_change = []
bichoX = []
bichoY = []
bichoY_change = []
meteoroX = []
meteoroY = []
meteoroY_change = []
num_of_enemies_10 = 5
num_of_enemies_20 = 4
num_of_enemies_30 = 3
for i in range(num_of_enemies_10):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyY_change.append(0.5)
for i in range(num_of_enemies_20):
bichoImg.append(pygame.image.load('bicho.png'))
bichoX.append(random.randint(0, 736))
bichoY.append(random.randint(10, 120))
bichoY_change.append(0.5)
for i in range(num_of_enemies_30):
meteoroImg.append(pygame.image.load('meteoro.png'))
meteoroX.append(random.randint(0, 736))
meteoroY.append(random.randint(0, 150))
meteoroY_change.append(0.5)
# Bullet
# Ready - You can't see the bullet on the screen
# Fire - The bullet is currently moving
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (255, 255, 255))
screen.blit(score, (x, y))
def show_level(x, y):
level = font.render("Level: " + str(level_value), True, (255, 255, 255))
screen.blit(level, (x, y))
def level_up_text(x, y):
level_text = font.render(level_up_value, True, (255, 255, 0))
screen.blit(level_text, (level_textX, level_textY))
def show_vidas(x, y):
vidas = font.render("Vidas : " + str(num_vidas), True, (255, 255, 255))
screen.blit(vidas, (x, y))
def game_over_text():
over_text = over_font.render("GAME OVER", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y, i):
screen.blit(enemyImg[i], (x, y))
def bicho(x, y, i):
screen.blit(bichoImg[i], (x, y))
def meteoro(x, y, i):
screen.blit(meteoroImg[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 16, y + 10))
#Colisiones para cada tipo de enemigo
def isCollision1(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
def isCollision2(bichoX, bichoY, bulletX, bulletY):
distance = math.sqrt(math.pow(bichoX - bulletX, 2) + (math.pow(bichoY - bulletY, 2)))
if distance < 27:
return True
else:
return False
def isCollision3(meteoroX, meteoroY, bulletX, bulletY):
distance = math.sqrt(math.pow(meteoroX - bulletX, 2) + (math.pow(meteoroY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# Pause Loop
def show_pause():
paused = True
while paused:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
pause_title = menu_font.render("PAUSED", True, (255, 255, 0))
pauseRect = pause_title.get_rect()
pauseRect.centerx = screen.get_rect().centerx
pauseRect.centery = screen.get_rect().centery - 50
screen.blit(pause_title, pauseRect)
high_title = menu_font.render("HIGH SCORES", True, (255, 255, 255))
highRect = high_title.get_rect()
highRect.centerx = screen.get_rect().centerx
highRect.centery = screen.get_rect().centery + 50
screen.blit(high_title, highRect)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
paused = False
break
if event.type == pygame.MOUSEBUTTONDOWN:
mpos = pygame.mouse.get_pos()
if highRect.collidepoint(mpos):
show_high_scores_menu()
break
pygame.display.update()
# High Scores Loop
def show_high_scores_menu():
high_scores_menu = True
global high_scores, names
high_scores.clear()
names.clear()
with open('high_scores.csv') as csvfile:
reader = csv.reader(csvfile)
sortedlist = sorted(reader, key=operator.itemgetter(1), reverse=True)
for i in sortedlist:
names.append(i[0])
high_scores.append(i[1])
while high_scores_menu:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
high_title = menu_font.render("HIGH SCORES", True, (255, 255, 0))
highRect = high_title.get_rect()
highRect.centerx = screen.get_rect().centerx
highRect.centery = 100
screen.blit(high_title, highRect)
score1 = scores_font.render(names[0] + " : " + str(high_scores[0]), True, (255, 255, 255))
score1Rect = score1.get_rect()
score1Rect.centerx = screen.get_rect().centerx
score1Rect.centery = 250
screen.blit(score1, score1Rect)
score2 = scores_font.render(names[1] + " : " + str(high_scores[1]), True, (255, 255, 255))
score2Rect = score1.get_rect()
score2Rect.centerx = screen.get_rect().centerx
score2Rect.centery = 300
screen.blit(score2, score2Rect)
score3 = scores_font.render(names[2] + " : " + str(high_scores[2]), True, (255, 255, 255))
score3Rect = score3.get_rect()
score3Rect.centerx = screen.get_rect().centerx
score3Rect.centery = 350
screen.blit(score3, score3Rect)
score4 = scores_font.render(names[3] + " : " + str(high_scores[3]), True, (255, 255, 255))
score4Rect = score4.get_rect()
score4Rect.centerx = screen.get_rect().centerx
score4Rect.centery = 400
screen.blit(score4, score4Rect)
score5 = scores_font.render(names[4] + " : " + str(high_scores[4]), True, (255, 255, 255))
score5Rect = score1.get_rect()
score5Rect.centerx = screen.get_rect().centerx
score5Rect.centery = 450
screen.blit(score5, score5Rect)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
high_scores_menu = False
show_pause()
break
pygame.display.update()
def save_high_scores():
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
name = ""
while len(name) < 3:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.unicode.isalpha():
name += event.unicode
elif event.key == pygame.K_BACKSPACE:
name = name[:-1]
name = name.upper()
screen.fill((0, 0, 0))
screen.blit(background, (0, 0))
high_title = menu_font.render("High Score!", True, (255, 255, 0))
highRect = high_title.get_rect()
highRect.centerx = screen.get_rect().centerx
highRect.centery = 100
screen.blit(high_title, highRect)
inpt = font.render("Enter a 3-letter name", True, (255, 255, 255))
inptRect = inpt.get_rect()
inptRect.centerx = screen.get_rect().centerx
inptRect.centery = 200
screen.blit(inpt, inptRect)
namedisplay = menu_font.render(name, True, (255, 255, 255))
namedisplayRect = namedisplay.get_rect()
namedisplayRect.center = screen.get_rect().center
screen.blit(namedisplay, namedisplayRect)
pygame.display.update()
#replace lowest
lowest = high_scores[0]
lowest_index = 0
for i in range(len(high_scores)):
if high_scores[i] <= lowest:
lowest = high_scores[i]
lowest_index = i
high_scores[lowest_index] = score_value
names[lowest_index] = name
with open('high_scores.csv', 'w',newline='') as csvfile:
writer = csv.writer(csvfile)
for i in range(len(names)):
writer.writerow([str(names[i]), str(high_scores[i])])
show_high_scores_menu()
BLACK = (0, 0, 0)
#Agregar imágenes para explosión
explosión_anim = []
for i in range(9):
file = "Explosión/Explosión 0{}.png".format(i)
img = pygame.image.load(file).convert()
img.set_colorkey(BLACK)
img_scale = pygame.transform.scale(img, (70, 70))
explosión_anim.append (img_scale)
def explosión1():
image = explosión_anim[0]
center = image.get_rect()
frame = 0
last_update = pygame.time.get_ticks()
frame_rate = 50 #Velocidad de la explosión
screen.blit(image, (enemyX[i], enemyY[i]))
now = pygame.time.get_ticks()
if now - last_update > frame_rate:
last_update = now
frame += 1
if frame == len(explosión_anim):
kill()
else:
center = rect.center
image = explosión_anim[frame]
rect = image.get_rect()
rect.center = center
def explosión2():
image = explosión_anim[0]
center = image.get_rect()
frame = 0
last_update = pygame.time.get_ticks()
frame_rate = 50 #Velocidad de la explosión
screen.blit(image, (bichoX[i], bichoY[i]))
now = pygame.time.get_ticks()
if now - last_update > frame_rate:
last_update = now
frame += 1
if frame == len(explosión_anim):
kill()
else:
center = rect.center
image = explosión_anim[frame]
rect = image.get_rect()
rect.center = center
def explosión3():
image = explosión_anim[0]
center = image.get_rect()
frame = 0
last_update = pygame.time.get_ticks()
frame_rate = 50 #Velocidad de la explosión
screen.blit(image, (meteoroX[i], meteoroY[i]))
now = pygame.time.get_ticks()
if now - last_update > frame_rate:
last_update = now
frame += 1
if frame == len(explosión_anim):
kill()
else:
center = rect.center
image = explosión_anim[frame]
rect = image.get_rect()
rect.center = center
# Game Loop
en_partida = True
while en_partida:
clock.tick(60)
en_final = False
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
# if player levels up
if score_value < 40:
level_value = 1
elif score_value <= 80:
level_value = 2
elif score_value <= 120:
level_value = 3
elif score_value <= 160:
level_value = 4
if (score_value >= 40 and score_value <= 42):
level_up_value = "LEVEL UP!"
elif (score_value >= 80 and score_value <= 82):
level_up_value = "LEVEL UP!"
elif (score_value >= 120 and score_value <= 122):
level_up_value = "LEVEL UP!"
else:
level_up_value = ""
for event in pygame.event.get():
if event.type == pygame.QUIT:
en_partida = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bulletSound = mixer.Sound("laser.wav")
bulletSound.play()
# Get the current x cordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# 5 = 5 + -0.1 -> 5 = 5 - 0.1
# 5 = 5 + 0.1
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy Movement
for i in range(num_of_enemies_10):
# Game Over
enemyY[i] += enemyY_change[i]
if enemyY[i] > 440:
for j in range(num_of_enemies_10):
enemyY[j] = 2000
game_over_text()
break
for i in range(num_of_enemies_20):
# Game Over
bichoY[i] += bichoY_change[i]
if bichoY[i] > 440:
for j in range(num_of_enemies_20):
bichoY[j] = 2000
game_over_text()
break
for i in range(num_of_enemies_30):
# Game Over
meteoroY[i] += meteoroY_change[i]
if meteoroY[i] > 440:
for j in range(num_of_enemies_30):
meteoroY[j] = 2000
game_over_text()
break
# Collision
collision1 = isCollision1(enemyX[i], enemyY[i], bulletX, bulletY)
collision2 = isCollision2(bichoX[i], bichoY[i], bulletX, bulletY)
collision3 = isCollision3(meteoroX[i], meteoroY[i], bulletX, bulletY)
enemy(enemyX[i], enemyY[i], i)
bicho(bichoX[i], bichoY[i], i)
meteoro(meteoroX[i], meteoroY[i], i)
if collision1:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
explosión1()
bulletY = 480
bullet_state = "ready"
score_value += 10
num_of_enemies_10 -= 1
if collision2:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
explosión2()
bulletY = 480
bullet_state = "ready"
score_value += 20
num_of_enemies_20 -= 1
if collision3:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
explosión3()
bulletY = 480
bullet_state = "ready"
score_value += 30
num_of_enemies_30 -= 1
#Aumento de enemigos por nivel
enemy_created = False
flag = False
if(level_value == 2 and flag == True):
flag = True
enemyX[i] = random.randint(0,736)
enemyY[i] = random.randint(50,150)
enemy(enemyX[i], enemyY[i], i)
enemy_created = True
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state == "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
show_score(scoreX, scoreY)
show_level(levelX, levelY)
level_up_text(levelX + 100, levelY)
show_vidas(vidasX, vidasY)
pygame.display.update()
pygame.quit()
Set the flag before the game loop:
# Game Loop
flag = True # set flag here
en_partida = True
while en_partida:
clock.tick(60)
....................
#Aumento de enemigos por nivel
enemy_created = False
if(level_value == 2 and flag == True): # check flag
flag = False # reset flag
enemyX[i] = random.randint(0,736)
enemyY[i] = random.randint(50,150)
enemy(enemyX[i], enemyY[i], i)
enemy_created = True

I want to add a bomb into my flappy bird game, but it won't detect the collision. here is the code

I want to add a bomb into my flappy bird game, but it won't detect the collision.
I cannot get the bird to be detected if it made contact with the bomb
The bomb shows up, but I can't make it detect the collision with the bird, here is the code I have so far.Also,i did not class a new object for the bomb, I put it in with the pipes.
I think there is a problem with the colliderect
If you need the images please tell me.
Can someone help me?
I would be really grateful.
Thanks in advance.
import pygame
from pygame.locals import * # noqa
import sys
import random
class FlappyBird:
def __init__(self):
self.screen = pygame.display.set_mode((400, 708))
self.bird = pygame.Rect(65, 50, 50, 50)
self.background = pygame.image.load("background.png")
self.birdSprites = [pygame.image.load("1.png"),
pygame.image.load("2.png"),
pygame.image.load("dead.png")]
self.wallUp = pygame.image.load("bottom.png")
self.wallDown = pygame.image.load("top.png")
self.bomb = pygame.image.load("bomb.png")
self.bombx = 600
self.gap = 130
self.wallx = 400
self.birdY = 350
self.jump = 0
self.jumpSpeed = 10
self.gravity = 5
self.dead = False
self.sprite = 0
self.counter = 0
self.offset = random.randint(-110, 110)
def updateWalls(self):
self.wallx -= 2
if self.wallx < -80:
self.wallx = 400
self.counter += 1
self.offset = random.randint(-110, 110)
self.bombx -= 2
if self.bombx < -80:
self.bombx = 600
self.counter += 1
self.offset = random.randint(-110, 110)
def birdUpdate(self):
if self.jump:
self.jumpSpeed -= 1
self.birdY -= self.jumpSpeed
self.jump -= 1
else:
self.birdY += self.gravity
self.gravity += 0.2
self.bird[1] = self.birdY
upRect = pygame.Rect(self.wallx,
360 + self.gap - self.offset + 10,
self.wallUp.get_width() - 10,
self.wallUp.get_height())
downRect = pygame.Rect(self.wallx,
0 - self.gap - self.offset - 10,
self.wallDown.get_width() - 10,
self.wallDown.get_height())
bombRect = pygame.Rect(self.bombx,
0 - self.gap - self.offset - 10,
self.bomb.get_width() - 10,
self.bomb.get_height()
)
if upRect.colliderect(self.bird):
self.dead = True
if downRect.colliderect(self.bird):
self.dead = True
if bombRect.colliderect(self.bird):
self.bomb = pygame.image.load("bombexplode")
self.dead = True
if not 0 < self.bird[1] < 720:
self.bird[1] = 50
self.birdY = 50
self.dead = False
self.counter = 0
self.wallx = 400
self.offset = random.randint(-110, 110)
self.gravity = 5
def run(self):
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.SysFont("Arial", 50)
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not self.dead:
self.jump = 17
self.gravity = 5
self.jumpSpeed = 10
self.screen.fill((255, 255, 255))
self.screen.blit(self.background, (0, 0))
self.screen.blit(self.wallUp,
(self.wallx, 360 + self.gap - self.offset))
self.screen.blit(self.wallDown,
(self.wallx, 0 - self.gap - self.offset))
self.screen.blit(self.bomb,
(self.bombx, 0 - self.gap - self.offset))
self.screen.blit(font.render(str(self.counter),
-1,
(255, 255, 255)),
(200, 50))
if self.dead:
self.sprite = 2
elif self.jump:
self.sprite = 1
self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))
if not self.dead:
self.sprite = 0
self.updateWalls()
self.birdUpdate()
pygame.display.update()
if __name__ == "__main__":
FlappyBird().run()
I don't know much about using sprites, but if you can get the position and size of each object, you can give them rectangular hitboxes and check if their corners are inside each other:
Another way is to use circular hitboxes if those fit better. For these, find the distace between the centers and check if it is smaller than their radius' combined.
Edit :
You can use
self.bird = pygame.Rect(65, 50, 50, 50)
# creating bomb hitbox
self.rect_bomb = pygame.Rect(100, 100, 200, 200)
if self.bird.colliderect(self.rect_bomb):
# end up your code

Enemy Sprite is hit and disappears but is not fixed later if it was hit on the sides

I have a code solved for this issue Image does not remain on screen after executing for loop in pygame. So I decided to put some platforms as a result of what I learned from pygame. I also decided to make the cowboy move to the right and left and go down to the bottom of the screen.
But when a collision occurs on the right or left side of the cowboy as shown in the Diagram, the class PlayerShip is not executed as expected in the main loop through the def draw_reaction () function because I do not see the image of the cowboy represented by player_sprite fixed in position (60, 48). It only works correctly if the cowboy is hit from below.
Assets
missile.png
cowboy.png
police.png
Diagram:
|missile| <--<-- (is touched its right side by the missile)|cowboy| <--<-- direction
^
|
^
|
(fire missile direction vertical)
^
|
d
i
r
e
c
t
i
o
n
My MWE coding:
import pygame
import random
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
GRAY = (128,128,128)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class PlayerShip( pygame.sprite.Sprite ):
def __init__(self):
super().__init__()
self.image = pygame.image.load( "cowboy.png" )
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.topleft = ( 60, 48 )
player_sprite = PlayerShip()
class Platform(pygame.sprite.Sprite):
def __init__(self, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(GREEN)
self.rect = self.image.get_rect()
class MovingPlatform(Platform):
change_x = 0
change_y = 0
boundary_top = 0
boundary_bottom = 0
boundary_left = 0
boundary_right = 0
player = None
level = None
def update(self):
self.rect.x += self.change_x
hit = pygame.sprite.collide_rect(self, self.player)
if hit:
if self.change_x < 0:
self.player.rect.right = self.rect.left
else:
self.player.rect.left = self.rect.right
self.rect.y += self.change_y
hit = pygame.sprite.collide_rect(self, self.player)
if hit:
if self.change_y < 0:
self.player.rect.bottom = self.rect.top
else:
self.player.rect.top = self.rect.bottom
if self.rect.bottom > self.boundary_bottom or self.rect.top < self.boundary_top:
self.change_y *= -1
cur_pos = self.rect.x - self.level.world_shift
if cur_pos < self.boundary_left or cur_pos > self.boundary_right:
self.change_x *= -1
class Level(object):
def __init__(self, player):
self.platform_list = pygame.sprite.Group()
self.enemy_list = pygame.sprite.Group()
self.player = player
self.background = None
self.world_shift = 0
self.level_limit = -1000
def update(self):
self.platform_list.update()
self.enemy_list.update()
def draw(self, screen):
screen.fill(GRAY)
self.platform_list.draw(screen)
self.enemy_list.draw(screen)
def shift_world(self, shift_x):
self.world_shift += shift_x
for platform in self.platform_list:
platform.rect.x += shift_x
for enemy in self.enemy_list:
enemy.rect.x += shift_x
class Room(object):
wall_list = None
enemy_sprites = None
def __init__(self):
self.wall_list = pygame.sprite.Group()
self.enemy_sprites = pygame.sprite.Group()
class Level_01(Level):
def __init__(self, player):
Level.__init__(self, player)
self.level_limit = -1500
level = [[210, 70, 500, 500],
[210, 70, 800, 400],
[210, 70, 1000, 500],
[210, 70, 1120, 280],
[210, 70, -120, 500],
]
for platform in level:
block = Platform(platform[0], platform[1])
block.rect.x = platform[2]
block.rect.y = platform[3]
block.player = self.player
self.platform_list.add(block)
block = MovingPlatform(70, 40)
block.rect.x = 1350
block.rect.y = 280
block.boundary_left = 1350
block.boundary_right = 1600
block.change_x = 10
block.player = self.player
block.level = self
self.platform_list.add(block)
class Level_02(Level):
def __init__(self, player):
Level.__init__(self, player)
self.level_limit = -1000
level = [[210, 70, 500, 550],
[210, 70, 800, 400],
[210, 70, 1000, 500],
[210, 70, 1120, 280],
]
for platform in level:
block = Platform(platform[0], platform[1])
block.rect.x = platform[2]
block.rect.y = platform[3]
block.player = self.player
self.platform_list.add(block)
block = MovingPlatform(70, 70)
block.rect.x = 1500
block.rect.y = 300
block.boundary_top = 100
block.boundary_bottom = 550
block.change_y = -1
block.player = self.player
block.level = self
self.platform_list.add(block)
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
width = 40
height = 60
self.image = pygame.image.load("police.png").convert()
self.rect = self.image.get_rect()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.change_x = 0
self.change_y = 0
self.level = None
def update(self):
self.calc_grav()
self.rect.x += self.change_x
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
if self.change_x > 0:
self.rect.right = block.rect.left
elif self.change_x < 0:
self.rect.left = block.rect.right
self.change_y += 0
self.rect.y += self.change_y
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
if self.change_y > 0:
self.rect.bottom = block.rect.top
elif self.change_y < 0:
self.rect.top = block.rect.bottom
self.change_y = 0
if isinstance(block, MovingPlatform):
self.rect.x += block.change_x
def calc_grav(self):
if self.change_y == 0:
self.change_y = 1
else:
self.change_y += .35
if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
self.change_y = 0
self.rect.y = SCREEN_HEIGHT - self.rect.height
def jump(self):
self.rect.y += 2
platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
self.rect.y -= 2
if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
self.change_y = -10
def go_left(self):
self.change_x = -6
def go_right(self):
self.change_x = 6
def stop(self):
self.change_x = 0
class Cowboy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("cowboy.png").convert()
self.rect = self.image.get_rect()
self.image.set_colorkey(BLACK)
class Missile(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("missile.png").convert()
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
def update(self):
self.rect.y += -3
def main():
pygame.init()
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
block_list = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
pygame.display.set_caption("Platformer with moving platforms")
apple = pygame.image.load("missile.png").convert()
block = Cowboy()
player_image = pygame.image.load("cowboy.png").convert()
player = Player()
level_list = []
level_list.append(Level_01(player))
level_list.append(Level_02(player))
current_level_no = 0
current_level = level_list[current_level_no]
block_list.add(block)
all_sprites_list.add(block)
all_sprites_list.add(player)
active_sprite_list = pygame.sprite.Group()
player.level = current_level
player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)
done = False
clock = pygame.time.Clock()
x_speed = 0
y_speed = 0
rect_x = 50
rect_y = 50
rect_change_x = 1
rect_change_y = 90
x = rect_x
y = rect_y
player.rect.y = rect_x
player.rect.y = 480
score = 0
size = (1366, 768)
screen = pygame.display.set_mode(size, pygame.RESIZABLE)
while not done:
x += x_speed
y += y_speed
rect_x += rect_change_x
if rect_x > 280:
rect_change_x *= -1
rect_x += rect_change_x
rect_y += rect_change_y
if rect_x < 0:
rect_change_x *= -1
rect_x += rect_change_x
rect_y += rect_change_y
block.rect.x = rect_x
block.rect.y = rect_y
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
bullet = Missile()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()
for bullet in bullet_list:
block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
for block in block_hit_list:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
score += 1
print(score)
screen.blit(player_image, [60, 48])
if bullet.rect.y < -10:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
def draw_reaction():
for bullet in bullet_list:
block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
for block in block_hit_list:
all_sprites_list.add( player_sprite )
break
all_sprites_list.update()
active_sprite_list.update()
current_level.update()
if player.rect.right >= 1500:
diff = player.rect.right - 500
player.rect.right = 500
current_level.shift_world(-diff)
if player.rect.left <= 120:
diff = 120 - player.rect.left
player.rect.left = 120
current_level.shift_world(diff)
current_position = player.rect.x + current_level.world_shift
if current_position < current_level.level_limit:
if current_level_no < len(level_list)-1:
player.rect.x = 120
current_level_no += 1
current_level = level_list[current_level_no]
player.level = current_level
else:
done = True
current_level.draw(screen)
active_sprite_list.draw(screen)
x += x_speed
y += y_speed
all_sprites_list.draw(screen)
draw_reaction()
clock.tick(60)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
UPDATE EDIT: If current_level.draw(screen) is not used in the main loop then the code works as expected. But I still don't know what causes it.
I simply added all_sprites_list.add (player_sprite) to the for block in block_hit_list:. In my view this would be necessary to track self.image.get_rect (). Then:
Before:
for bullet in bullet_list:
block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
for block in block_hit_list:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
score += 1
print(score)
screen.blit(player_image, [60, 48])
if bullet.rect.y < -10:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
Later:
for bullet in bullet_list:
block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
for block in block_hit_list:
all_sprites_list.add(player_sprite)
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
score += 1
print(score)
screen.blit(player_image, [60, 48])
if bullet.rect.y < -10:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
But I would like someone to explain to me how it really happened behind the code by making more experienced references to the documentation or the style of the code itself. Thankful if anyone can make that explanation.

Pygame Snake food generator

I'm currently in the process of creating a Snake game and I want to create a food generator that generates an apple every 10 seconds based on my in-game timer. The timer counts down from 60 to 0(when the game ends) and I want an new apple to generate every 10 seconds, keeping the old one even if it hasn't been eaten. I don't know how to approach this and could use some help. Here is my full program.
Edit: this is a beginner Computer Science school project so the more basic the better.
import random
import pygame
pygame.init()
#---------------------------------------#
#
# window properties #
width = 640 #
height = 480
game_window=pygame.display.set_mode((width,height))
black = ( 0, 0, 0) #
#---------------------------------------#
# snake's properties
outline=0
body_size = 9
head_size = 10
apple_size = 8
speed_x = 8
speed_y = 8
dir_x = 0
dir_y = -speed_y
segx = [int(width/2.)]*3
segy = [height, height + speed_y, height + 2*speed_y]
segments = len(segx)
apple_counter = 0
grid_step = 8
regular_font = pygame.font.SysFont("Andina",18)
blue = [11, 90, 220]
clock = pygame.time.Clock()
time = 60
fps = 25
time = time + 1.0/fps
text = regular_font.render("Time from start: "+str(int(time)), 1, blue)
text2 = regular_font.render("Score: "+str(int(apple_counter)), 1, blue)
apple_x = random.randrange(0, 640, grid_step)
apple_y = random.randrange(0, 480, grid_step)
apple_colour = (255,0,0)
def redraw_game_window():
game_window.fill(black)
for i in range(segments):
segment_colour = (random.randint(1,50),random.randint(100,150),random.randint(1,50))
head_colour = (random.randint(180,220),random.randint(180,220),random.randint(1,15))
apple_colour = (255,0,0)
pygame.draw.circle(game_window, segment_colour, (segx[i], segy[i]), body_size, outline)
pygame.draw.circle(game_window, head_colour, (segx[0], segy[0]), head_size, outline)
game_window.blit(text, (530, 20))
game_window.blit(text2, (30, 20))
pygame.draw.circle(game_window, apple_colour, (apple_x, apple_y), apple_size, outline)
pygame.display.update()
exit_flag = False
print "Use the arrows and the space bar."
print "Hit ESC to end the program."
########################################################## TIMER/CONTROLS
while exit_flag == False:
redraw_game_window()
clock.tick(fps)
time = time - 1.00/fps
text = regular_font.render("Time: "+str(int(time)), 1, blue)
text2 = regular_font.render("Score: "+str(int(apple_counter)), 1, blue)
if time < 0.1:
print "Game Over"
exit_flag = True
pygame.event.get()
keys = pygame.key.get_pressed()
if time ==
if keys[pygame.K_ESCAPE]:
exit_flag = True
if keys[pygame.K_LEFT] and dir_x != speed_x:
dir_x = -speed_x
dir_y = 0
if keys[pygame.K_RIGHT] and dir_x != -speed_x:
dir_x = speed_x
dir_y = 0
if keys[pygame.K_UP] and dir_y != speed_x:
dir_x = 0
dir_y = -speed_y
if keys[pygame.K_DOWN] and dir_y != -speed_x:
dir_x = 0
dir_y = speed_y
############################################################ SNAKE MOVEMENT
for i in range(segments-1,0,-1):
segx[i]=segx[i-1]
segy[i]=segy[i-1]
segx[0] = segx[0] + dir_x
segy[0] = segy[0] + dir_y
############################################################ COLLISION
for i in range(segments-1, 3, -1):
if segments > 3:
if segx[0] == segx[i] and segy[0] == segy[i]:
print "You have collided into yourself, Game Over."
exit_flag = True
############################################################# BORDERS
if segx[0] > 640 or segx[0] < 0:
print "Game Over, you left the borders."
break
if segy[0] > 480 or segy[0] < 0:
print "Game Over, you left the borders."
break
############################################################# APPLE DETECT
for i in range (0 , 13):
if segx[0] == apple_x + i and segy[0] == apple_y + i:
segments = segments + 1
segx.append(segx[-1])
segy.append(segy[-1])
apple_counter = apple_counter + 1
if segx[0] == apple_x - i and segy[0] == apple_y - i:
segments = segments + 1
segx.append(segx[-1])
segy.append(segy[-1])
apple_counter = apple_counter + 1
#############################################################
pygame.quit()
You either
A) use pygame.time.set_timer to call a function every 10 seconds to spawn food, and every 60 seconds to end the round.
or
B) compare get_ticks()
def new_round():
last_apple = pygame.time.get_ticks() + 10*1000
while true:
now = pygame.time.get_ticks()
if now - last_apple >= 1000:
spawn_apple()
last_apple = now
if now - round_start >= 60*1000:
round_end()