Throwing barrels at specific intervals (donkey kong pygame) [duplicate] - pygame

This question already has answers here:
Is there a way to have different tick rates for differents parts of my code in pygame?
(1 answer)
Spawning multiple instances of the same object concurrently in python
(1 answer)
Closed 9 months ago.
please excuse the messiness of my code as im still a beginner, but i'm here to ask about a problem im having. I'm trying to create a timer for donkey kong to throw barrels at specific time intervals but im not sure exactly how to work it out. I have the logic figured out for one barrel, but trying to apply my thinking for generating multiple isnt working (it worked when i did it for some simple shapes in a test). If i had to hazard a guess, i assume it might have to do with it trying to index my animation frame on a new barrel, because i dont think i have it set up correctly, but im not sure why my first barrel isnt blitting in the place i have it set. Here's my code for reference:
import pygame
import random
import math
from pygame import *
import pygame.freetype
def resetPosition():
global marioX
marioX = 50
global marioY
marioY = 725
global moveMarioRight
moveMarioRight = False
global moveMarioLeft
moveMarioLeft = False
global marioJump
marioJump = False
global climbPause
climbPause = False
global onLadder
onLadder = False
global isClimbingUp
isClimbingUp = False
global isClimbingDown
isClimbingDown = False
global gravity
gravity = 0
global walkCount
walkCount = 0
global climbCount
climbCount = 0
global barrelRollCount
barrelRollCount = 0
global dkCount
dkCount = 0
global barrelGravity
barrelGravity = 0
global barrelPos
barrelPos = [231, 244]
global barrelMoveRight
barrelMoveRight = True
global barrelMoveLeft
barrelMoveLeft = False
global barrelDescend
barrelDescend = False
global wasMovingLeft
wasMovingLeft = True
global barrelOffLadder
barrelOffLadder = True
global barrelMoveAnimate
barrelMoveAnimate = True
global barrelDescendAnimate
barrelDescendAnimate = False
def main():
""" Set up the game and run the main game loop """
pygame.init() # Prepare the pygame module for use
pygame.freetype.init()
surfaceWidth = 715
surfaceLength = 813# Desired physical surface size, in pixels.
clock = pygame.time.Clock() #Force frame rate to be slower
# Create surface of (width, height), and its window.
mainSurface = pygame.display.set_mode((surfaceWidth, surfaceLength))
font = pygame.freetype.Font("8bitOperatorPlus8-Bold.ttf", 72)
buttonFont = pygame.freetype.Font("8bitOperatorPlus8-Bold.ttf", 48)
programState = 'initialize'
if programState == 'initialize':
platforms = pygame.image.load("level.png")
platformPos = [0, 0]
global marioX
marioX = 50
global marioY
marioY = 725
marioRight = [pygame.image.load("mario-right.png"), pygame.image.load("run-right.png"), pygame.image.load("jump-right.png")]
marioLeft = [pygame.image.load("mario-left.png"), pygame.image.load("run-left.png"), pygame.image.load("jump-left.png")]
marioClimb = [pygame.image.load("marioClimb1.png"), pygame.image.load("marioClimb2.png")]
dkSprite = [pygame.image.load("dkForward.png"), pygame.image.load("dkLeft.png"), pygame.image.load("dkRight.png")]
barrelStack = pygame.image.load("barrel-stack.png")
barrels = [pygame.image.load("barrel1.png"), pygame.image.load("barrel2.png"), pygame.image.load("barrel3.png"), pygame.image.load("barrel4.png"), pygame.image.load("barrel-down.png")]
deadMario = pygame.image.load("dead.png")
deadMario = pygame.transform.scale2x(deadMario)
hammer = pygame.image.load("marioHammer.png")
hammer = pygame.transform.scale2x(hammer)
marioHammer = pygame.image.load("marioHammer1.png")
marioHammer = pygame.transform.scale2x(marioHammer)
#luigiRight = [pygame.image.load("luigi-right.png").convert(), pygame.image.load("luigi-runright.png").convert()]
#luigiRight.set_colorkey((255, 255, 255))
dkPos = [95, 183]
global moveMarioRight
moveMarioRight = False
global moveMarioLeft
moveMarioLeft = False
runRightAnimate = False
runLeftAnimate = False
standingLeft = False
standingRight = True
jumpingLeft = False
jumpingRight = False
global marioJump
marioJump = False
climbAnimate = False
global barrelMoveAnimate
barrelMoveAnimate = True
global barrelDescendAnimate
barrelDescendAnimate = False
global climbPause
climbPause = False
global onLadder
onLadder = False
global isClimbingUp
isClimbingUp = False
global isClimbingDown
isClimbingDown = False
global gravity
gravity = 0
global walkCount
walkCount = 0
global climbCount
climbCount = 0
global barrelRollCount
barrelRollCount = 0
global dkCount
dkCount = 0
groundLevel = 800
barrelGroundLevel = 250
global barrelGravity
barrelGravity = 0
ladderPosList = []
blockerPosList = []
detectorPosList = []
numLadders = 6
numLadderBlockers = 6
numBarrelDetectors = 5
ladderHitboxColour = (100, 100, 100)
ladderBlockerColour = (255, 0, 0)
barrelDetectorColour = (0, 0, 255)
global barrelPos
barrelPos = [231, 244]
global barrelMoveRight
barrelMoveRight = True
global barrelMoveLeft
barrelMoveLeft = False
global barrelDescend
barrelDescend = False
global wasMovingLeft
wasMovingLeft = True
global barrelOffLadder
barrelOffLadder = True
buttonColour = (161, 161, 161)
button2Colour = (161, 161, 161)
barrelCount = 60
hammerPos = [560, 608]
hammerGrabbed = False
barrelPosList = []
barrelCount = 0
futureBarrelCount = 60
for i in range((numLadders)):
ladderPosList.append([577, 676])
ladderPosList.append([122, 582])
ladderPosList.append([354, 466])
ladderPosList.append([116, 383])
ladderPosList.append([565, 282])
ladderPosList.append([403, 197])
for i in range((numLadderBlockers)):
blockerPosList.append([577, 751.5])
blockerPosList.append([122, 654.5])
blockerPosList.append([354, 563.5])
blockerPosList.append([116, 455.5])
blockerPosList.append([565, 359.5])
blockerPosList.append([403, 282.5])
for i in range((numBarrelDetectors)):
detectorPosList.append([577, 676])
detectorPosList.append([122, 577])
detectorPosList.append([354, 466])
detectorPosList.append([116, 383])
detectorPosList.append([565, 282])
programState = 'game'
while True:
mouseX, mouseY = pygame.mouse.get_pos()
print(mouseX, mouseY)
ev = pygame.event.poll() # Look for any event
if ev.type == pygame.QUIT: # Window close button clicked?
break# ... leave game loop
if programState == 'game':
marioHitBox = marioRight[0].get_rect(topleft=(marioX, marioY))
barrelHitBox = barrels[0].get_rect(topleft=(barrelPos[0], barrelPos[1]))
hammerHitBox = hammer.get_rect(topleft=(120, 700))
if ev.type == pygame.KEYDOWN:
if isClimbingUp == False and isClimbingDown == False:
if ev.key == pygame.K_d:
moveMarioRight = True
runRightAnimate = True
standingRight = False
if ev.key == pygame.K_a:
moveMarioLeft = True
runLeftAnimate = True
standingLeft = False
if ev.key == pygame.K_w:
if onLadder == False:
pass
elif onLadder == True:
jumpingLeft = False
jumpingRight = False
isClimbingUp = True
climbAnimate = True
standingRight = False
standingLeft = False
climbPause = False
if ev.key == pygame.K_s:
if onLadder == False:
pass
elif onLadder == True:
jumpingLeft = False
jumpingRight = False
isClimbingDown = True
climbAnimate = True
standingRight = False
standingLeft = False
climbPause = False
elif ev.type == pygame.KEYUP:
if isClimbingUp == False and isClimbingDown == False:
if ev.key == pygame.K_d:
moveMarioRight = False
runRightAnimate = False
standingRight = True
standingLeft = False
if ev.key == pygame.K_a:
moveMarioLeft = False
runLeftAnimate = False
standingLeft = True
standingRight = False
if ev.key == pygame.K_w:
if onLadder == False:
if (not marioJump):
gravity -= 7.5
marioJump = True
if standingLeft or runLeftAnimate == True:
jumpingLeft = True
standingLeft = False
runRightAnimate = False
jumpingRight = False
elif standingRight or runRightAnimate == True:
jumpingRight = True
standingRight = False
jumpingLeft = False
runLeftAnimate = False
if onLadder == True:
isClimbingUp = False
climbAnimate = False
climbPause = True
if ev.key == pygame.K_s:
if onLadder == False:
pass
if onLadder == True:
isClimbingDown = False
climbAnimate = False
climbPause = True
# Update your game objects and data structures here...
if barrelCount >= futureBarrelCount:
barrelPosList.append(barrelPos)
futureBarrelCount = barrelCount + 60
for i in range(len(ladderPosList)):
if marioHitBox.colliderect((ladderPosList[i], (70, 90))):
#A collision happens!
onLadder = True
break
else:
onLadder = False
if onLadder == True:
if isClimbingDown:
for i in range(len(blockerPosList)):
if marioHitBox.colliderect((blockerPosList[i], (70, 22.5))):
#A collision happens!
isClimbingDown = False
break
else:
isClimbingDown = True
for i in range(len(detectorPosList)):
if barrelHitBox.colliderect((detectorPosList[i], (70, 22.5))):
barrelOffLadder = False
if barrelMoveRight == True:
wasMovingLeft = False
barrelMoveRight = False
barrelDescendAnimate = True
barrelDescend = True
elif barrelMoveLeft == True:
wasMovingLeft = True
barrelMoveLeft = False
barrelDescendAnimate = True
barrelDescend = True
for i in range(len(blockerPosList)):
if barrelHitBox.colliderect((blockerPosList[i], (70, 22.5))):
barrelOffLadder = True
barrelDescend = False
barrelDescendAnimate = False
barrelMoveAnimate = True
break
if marioHitBox.colliderect(barrelHitBox):
programState = 'game over'
if marioHitBox.colliderect(hammerHitBox):
hammerGrabbed = True
if onLadder == False:
marioY += gravity
detectionCoord = [int(marioX), int(marioY)+34]
colorBelow = mainSurface.get_at(detectionCoord)
if colorBelow == (255, 6, 65, 255):
groundLevel = detectionCoord[1]-1
else:
groundLevel = surfaceLength
if ((marioY + 34) > groundLevel):
marioY = groundLevel - 34
gravity = 0
marioJump = False
else:
gravity += 0.5
barrelPos[1] += barrelGravity
barrelDetectionCoord = [int(barrelPos[0]), int(barrelPos[1])+23]
barrelColorBelow = mainSurface.get_at(barrelDetectionCoord)
if barrelColorBelow == (255, 6, 65, 255):
barrelGroundLevel = barrelDetectionCoord[1]-1
else:
barrelGroundLevel = surfaceLength
if ((barrelPos[1] + 23) > barrelGroundLevel):
barrelPos[1] = barrelGroundLevel - 23
barrelGravity = 0
else:
barrelGravity += 0.5
if walkCount >= 2:
walkCount = 0
if climbCount >= 2:
climbCount = 0
if barrelRollCount >= 4:
barrelRollCount = 0
if moveMarioRight:
marioX += 3 #update the x
if moveMarioLeft:
marioX -= 3 #update the x
if isClimbingUp:
marioY -= 2
if isClimbingDown:
marioY += 2
if barrelOffLadder and wasMovingLeft == True:
barrelMoveRight = True
barrelMoveLeft = False
if barrelMoveRight:
barrelPos[0] += 5
elif barrelOffLadder and wasMovingLeft == False:
barrelMoveRight = False
barrelMoveLeft = True
if barrelMoveLeft:
barrelPos[0] -= 5
if barrelDescend:
barrelPos[1] += 4
if marioX <= 0:
marioX = 0
elif marioX >= 671:
marioX = 671
# We draw everything from scratch on each frame.
# So first fill everything with the background color
mainSurface.fill((8, 8, 8))
for i in range(len(ladderPosList)):
pygame.draw.rect(mainSurface, ladderHitboxColour, (ladderPosList[i], (70, 90)))
for i in range(len(blockerPosList)):
pygame.draw.rect(mainSurface, ladderBlockerColour, (blockerPosList[i], (70, 22.5)))
for i in range(len(detectorPosList)):
pygame.draw.rect(mainSurface, barrelDetectorColour, (detectorPosList[i], (70, 22.5)))
mainSurface.blit(platforms, platformPos)
mainSurface.blit(barrelStack, (36, 196))
if hammerGrabbed == False:
mainSurface.blit(hammer, (120, 700))
dkCount += 1
if dkCount < 30:
mainSurface.blit(dkSprite[0], dkPos)
elif dkCount >= 30 and dkCount < 60:
mainSurface.blit(dkSprite[1], dkPos)
elif dkCount >= 60 and dkCount < 90:
mainSurface.blit(dkSprite[2], dkPos)
elif dkCount == 90:
dkCount = 0
else:
mainSurface.blit(dkSprite[0], dkPos)
for i in range(len(barrelPosList)):
if barrelMoveAnimate:
mainSurface.blit(barrels[barrelRollCount], barrelPosList[i])
barrelRollCount += 1
if barrelDescendAnimate:
mainSurface.blit(barrels[4], barrelPosList[i])
#mainSurface.blit(marioHammer, (60, 700))
pygame.draw.rect(mainSurface, (6,6,6), (0, 0, surfaceWidth, 70))
pygame.draw.line(mainSurface, (255, 6, 65), (0, 769), (364, 769), 10)
pygame.draw.line(mainSurface, (255, 6, 65), (364, 769), (698, 747),10)
pygame.draw.line(mainSurface, (255, 6, 65), (32, 649), (650, 685), 10)
pygame.draw.line(mainSurface, (255, 6, 65), (79, 587), (697, 551), 10)
pygame.draw.line(mainSurface, (255, 6, 65), (32, 453), (649, 489), 10)
pygame.draw.line(mainSurface, (255, 6, 65), (79, 391), (697, 356), 10)
pygame.draw.line(mainSurface, (255, 6, 65), (461, 283), (650, 292), 10)
pygame.draw.line(mainSurface, (255, 6, 65), (32, 279), (460, 279), 10)
#mainSurface.blit(luigi, (100, 100))
if marioJump == True:
runRightAnimate = False
runLeftAnimate = False
if runRightAnimate:
mainSurface.blit(marioRight[walkCount], (marioX, marioY))
walkCount += 1
elif runLeftAnimate:
mainSurface.blit(marioLeft[walkCount], (marioX, marioY))
walkCount += 1
elif standingRight:
mainSurface.blit(marioRight[0], (marioX, marioY))
elif standingLeft:
mainSurface.blit(marioLeft[0], (marioX, marioY))
elif jumpingLeft:
mainSurface.blit(marioLeft[2], (marioX, marioY))
if marioJump == False:
standingLeft = True
elif jumpingRight:
mainSurface.blit(marioRight[2], (marioX, marioY))
if marioJump == False:
standingRight = True
elif climbAnimate:
mainSurface.blit(marioClimb[climbCount], (marioX, marioY))
climbCount += 1
elif climbPause:
mainSurface.blit(marioClimb[1], (marioX, marioY))
if programState == 'game over':
if mouseX >= 265 and mouseX <= 465 and mouseY >= 460 and mouseY <= 540:
buttonColour = (84, 84, 84)
if ev.type == pygame.MOUSEBUTTONUP:
resetPosition()
programState = "game"
else:
buttonColour = (161, 161, 161)
if mouseX >= 265 and mouseX <= 465 and mouseY >= 590 and mouseY <= 670:
button2Colour = (84, 84, 84)
if ev.type == pygame.MOUSEBUTTONUP:
pass
else:
button2Colour = (161, 161, 161)
mainSurface.fill((8,8,8))
font.render_to(mainSurface, (135, 190), "GAME OVER!", (88, 245, 242))
pygame.draw.rect(mainSurface, buttonColour, [265, 460, 200, 80])
pygame.draw.rect(mainSurface, button2Colour, [265, 590, 200, 80])
buttonFont.render_to(mainSurface, (300, 480), "PLAY", (8, 8, 8))
buttonFont.render_to(mainSurface, (300, 610), "MENU", (8, 8, 8))
mainSurface.blit(pygame.transform.rotate(deadMario, 90), (330, 300))
# Now the surface is ready, tell pygame to display it!
barrelCount += 1
pygame.display.flip()
clock.tick(30) #Force frame rate to be slower
pygame.quit() # Once we leave the loop, close the window.
main()

Related

screen.blit() function executing even after pygame.quit() is used

I am making a basic pong game in pygame with a separate menu screen. I have figured out all the gameplay (physics of ball,score system etc.).However, when i quit the game no matter from the menu screen or from the main game loop, i get this error:pygame.error: display Surface quit. I have seen all the posts about this error on stackoverflow, as well as other websites. I understand that the error is occuring because even after the pygame.quit() function, the next screen.blit(player1,(player1x,player1y)) is being executed. Following is the my code :
import pygame
import random
pygame.init()
#screen
screenw = 1000
screenh = 600
screen = pygame.display.set_mode((screenw, screenh))
bg = pygame.image.load("bg.jpg")
dp = pygame.image.load("ping-pong.png")
pygame.display.set_caption("PONG")
pygame.display.set_icon(dp)
def main():
# score
font = pygame.font.Font('font.otf', 24)
winfont = pygame.font.Font('font.otf', 50)
score_value_p1 = 0
scorexp1 = 10
scoreyp1 = 0
score_value_p2 = 0
scorexp2 = screenw - 145
scoreyp2 = 0
#toss
toss = random.choice([-1,1])
#players
def initial_bars():
global player1,player1x,player1y,player1_change,player2,player2x,player2y,player2_change
player1 = pygame.image.load("danda.png")
player1 = pygame.transform.scale(player1,(25,128))
player1x = 10
player1y = 232
player1_change = 0
player2 = pygame.image.load("danda.png")
player2 = pygame.transform.scale(player1,(25,128))
player2x = 965
player2y = 232
player2_change = 0
#ball
def initial_ball():
global ball,ballx,bally,ballx_change,bally_change
ball = pygame.image.load("ball.png")
ballx = 484
bally = 284
ballx_change = 0.4*toss
bally_change = 0.0
initial_bars()
initial_ball()
global player1,player1x,player1y,player1_change,player2,player2x,player2y,player2_change,ball,ballx,bally,ballx_change,bally_change,running
#functions
def player1bar():
screen.blit(player1,(player1x,player1y))
def player2bar():
screen.blit(player2,(player2x,player2y))
def balll():
screen.blit(ball,(ballx,bally))
def show_score():
scorep1 = font.render("Score : " + str(score_value_p1), True, (255, 50, 50))
screen.blit(scorep1, (scorexp1 , scoreyp1))
scorep2 = font.render("Score : " + str(score_value_p2), True, (255, 50, 50))
screen.blit(scorep2, (scorexp2 , scoreyp2))
#game window
running = True
while running:
screen.fill((0, 0, 0))
pygame.draw.line(screen,(255,255,30),(499,0),(499,600), 10)
pygame.draw.circle(screen,(255,255,30),(500,300), 40, 10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
# player1 movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s :
player1_change = 0.6
if event.key == pygame.K_w:
player1_change = -0.6
if event.type == pygame.KEYUP:
if event.key == pygame.K_s or event.key == pygame.K_w:
player1_change = 0
# player2 movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN :
player2_change = 0.6
if event.key == pygame.K_UP:
player2_change = -0.6
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
player2_change = 0
player1y += player1_change
player2y += player2_change
# player1 boundary
if player1y <= 0:
player1y = 0
elif player1y >= 472:
player1y = 472
# player2 boundary
if player2y <= 0:
player2y = 0
elif player2y >= 472:
player2y = 472
#ball move
ballx += ballx_change
bally += bally_change
toss = random.choice([-1,1])
if ballx < 35 and ballx > 30 and (player1y == bally or (player1y < bally and player1y > bally - 128) or (player1y > bally and player1y < bally + 32)):
ballx_change *= -1
if ballx_change < 1:
ballx_change += 0.05
bally_change = ballx_change*toss
if ballx > 933 and ballx < 938 and (player2y == bally or (player2y < bally and player2y > bally - 128) or (player2y > bally and player2y < bally + 32)):
ballx_change *= -1
if ballx_change > -1:
ballx_change -= 0.05
bally_change = ballx_change*toss
# ball boundary
if bally < 0 or bally > screenh - 32:
bally_change *= -1
#score
if ballx > screenw:
score_value_p1 += 1
if ballx < -32:
score_value_p2 += 1
#respawn
if ballx > screenw or ballx < -32:
initial_ball()
initial_bars()
player1bar()
player2bar()
balll()
show_score()
#winner
if score_value_p1 == 5:
winner = winfont.render("The Winner is Player 1", True, (50, 255, 50))
winner_rect = winner.get_rect(center=(screenw/2, screenh/2))
pygame.draw.rect(screen, (0,0,0), pygame.Rect(winner_rect))
screen.blit(winner, winner_rect)
if score_value_p2 == 5:
winner = winfont.render("The Winner is Player 2", True, (50, 255, 50))
winner_rect = winner.get_rect(center=(screenw/2, screenh/2))
pygame.draw.rect(screen, (0,0,0), pygame.Rect(winner_rect))
screen.blit(winner, winner_rect)
pygame.display.update()
if score_value_p1 == 5 or score_value_p2 == 5:
pygame.time.delay(2000)
menu_screen()
if ballx == 484 and bally == 284:
pygame.time.delay(1250)
ballx_change = 0.4*toss
def menu_screen():
menufont = pygame.font.Font('font.otf', 50)
tipfont = pygame.font.Font('font.otf', 30)
running = True
while running:
screen.blit(bg,(0,0))
title = menufont.render("Multiplayer Pong", True, (255, 255, 20))
screen.blit(title, (220,70))
tip = tipfont.render("Click Anywhere to Play", True, (50, 255, 50))
screen.blit(tip, (275,500))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
running = False
pygame.display.update()
main()
menu_screen()
I have tried methods like adding break,pygame.quit(),declaring running as a global variable. However, i have not been able to get rid of this problem. Can anyone please try o provide a solution for this problem. Following is the complete error i recieved :
Traceback (most recent call last):
File "c:\Users\jaism\OneDrive\Desktop\Codes\Minor Project CSE\main.py", line 208, in <module>
menu_screen()
File "c:\Users\jaism\OneDrive\Desktop\Codes\Minor Project CSE\main.py", line 206, in menu_screen
main()
File "c:\Users\jaism\OneDrive\Desktop\Codes\Minor Project CSE\main.py", line 158, in main
player1bar()
File "c:\Users\jaism\OneDrive\Desktop\Codes\Minor Project CSE\main.py", line 63, in player1bar
screen.blit(player1,(player1x,player1y))
pygame.error: display Surface quit
pygame.quit() uninitialize all pygame modules that have previously been initialized. So you can't call any pygame API function after pygame.quite(). pygame.quite() must be the very last pygame function called after the application loop:
def main():
# [...]
running = True
while running:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# pygame.quit() <-- DELETE
# [...]
def menu_screen():
# [...]
run_main = True
running = True
while running:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
run_main = False
# pygame.quit() <-- DELETE
# [...]
if run_main:
main()
menu_screen()
pygame.quit() # <-- INSERT

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

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.

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 create multiple enemies but keep getting same error code

Blockquote I just started coding in this coronatime and I am running into a problem.
The error code is
enemy_icon = [i]
NameError: name 'i' is not defined
And i'm not sure why. I having been looking online but couldn't find any answers.
Hopefully this has given enough resources to be a good enough question.
import pygame
import random
import math
pygame.init()
# game over logo
game_over = pygame.image.load("game-over.png")
# create screen
screen = pygame.display.set_mode((1000, 600))
background = pygame.image.load("8717.jpg")
# Title + Logo
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("chicken.png")
pygame.display.set_icon(icon)
# Player icon
player_icon = pygame.image.load("spaceship.png")
playerX = 400
playerY = 500
player_changeX = 0
player_changeY = 0
# multiple enemy players
enemy_icon = [i]
enemyX = [i]
enemyY = [i]
enemy_changeX = [i]
enemy_changeY = [i]
num_of_enemies = 2
for i in range(num_of_enemies):
enemy_icon.append(pygame.image.load("space-invaders.png"))
enemyX.append(random.randint(0, 936))
enemyY.append(random.randint(-100, -50))
enemy_changeX.append(random.randint(-2, 2))
enemy_changeY.append(random.randint(1, 2))
# bullet #ready you can't see bullet. fire you can
bullet = pygame.image.load("bullet.png")
bulletX = 0
bulletY = 0
bulletY_change = 2
bulletX_change = 0
bullet_state = "ready"
# score
score = 0
def player(x, y):
screen.blit(player_icon, (x, y))
def enemy(x, y, i):
screen.blit(enemy_icon[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bullet, (x + 16, y + 10))
def has_collided(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 collided(enemyX, enemyY, playerX, playerY):
distance2 = math.sqrt((math.pow(enemyX - playerX, 2)) + (math.pow(enemyY - playerY, 2)))
if distance2 < 27:
return True
else:
return False
# game loop
running = True
while running:
# background round colour RGB
screen.fill((0, 0, 0))
# background image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If key pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_changeX = -5
if event.key == pygame.K_RIGHT:
player_changeX = 5
if event.key == pygame.K_UP:
player_changeY = -5
if event.key == pygame.K_DOWN:
player_changeY = 5
# bullet shot
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bulletX = playerX
bulletY = playerY
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_changeX = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player_changeY = 0
# If player reaches boarder
if playerX >= 936:
playerX = 20
if playerX <= 0:
playerX = 936
if playerY <= 0:
playerY = 0
if playerY >= 550:
playerY = 550
# enemy control
for i in range(num_of_enemies):
if enemyX[i] >= 936:
enemyX[i] = 20
if enemyX[i] <= 0:
enemyX[i] = 936
if enemyY[i] <= 0:
enemyY[i] = 0
if enemyY[i] >= 550:
enemyY[i] = random.randint(-100, -50)
# collision bullet and enemy
collision = has_collided(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = playerY
bulletX = playerX
bullet_state = "ready"
score += 1
print(score)
enemyX[i] = random.randint(0, 936)
enemyY[i] = random.randint(-100, -50)
enemy_changeX[i] = random.randint(-2, 2)
enemy_changeY[i] = random.randint(1, 2)
collision2 = collided(enemyX[i], enemyY[i], playerX, playerY)
if collision2:
screen.blit(game_over, (400, 100))
score = 0
playerY = 400
playerX = 500
enemy(enemyX[i], enemyY[i], i)
# bullet movement
if bullet_state == "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
if bulletY <= 0:
bullet_state = "ready"
# collision enemy and player
# Player coordinates
playerX += player_changeX
playerY += player_changeY
# enemy change in coordinates
enemyX += enemy_changeX
enemyY += enemy_changeY
# bullet change in y
bulletY -= bulletY_change
# Results
player(playerX, playerY)
pygame.display.update()
The error seems pretty clear. You have this line in you code:
# multiple enemy players
enemy_icon = [i]
This line says that you are trying to create a variable enemy_icon and initialize it to a list with one element in it. That element is the variable i which has not been previously defined. I suspect that the i is a typo and that you are really trying to initialize with an empty list, in which case just remove the i like this:
# multiple enemy players
enemy_icon = []
The same is true for the 4 variables right after that.

PyGame surface locked during blit [duplicate]

I am trying to draw text to a screen in a space above a bunch of rects that are all in the 2d array square. When i try and draw text to the screen it says that "Surfaces must not be locked during blit."
I have tried unlocking, it makes no difference.
import sys, time, random, pygame
from pygame import *
from time import time,sleep
pygame.init()
global isDragging, inDrag, rightDrag, lastDrag, inDragRight, mouseX,mouseY, borderHeight
isDragging = False
isAuto = False
inDrag= False
inDragRight = False
isFilling = False
done = False
lastDrag = None
rightDrag = None
tickTime = 300
font = pygame.font.SysFont(None, 12,False,False)
dragDelay = 2
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
PINK = ( 255, 150, 200)
BLUE = ( 0, 0, 255)
RED = GREEN
width, height, margin = 100, 100, 1
noWidth, noHeight = 6,6
speed = [2, 2]
borderHeight = 50
size = (width*noWidth,height*noHeight + borderHeight)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("PieStone")
clock = pygame.time.Clock()
pixArray = pygame.PixelArray(screen)
font = pygame.font.SysFont("monospace", 15)
word = font.render("test", 1, (0, 0, 0))
class Null:
pass
square = [[Null() for i in range(noHeight)]for i in range(noWidth)]
for d1 in range(noWidth):
for d2 in range(noHeight):
square[d1][d2].man = False
square[d1][d2].visits = 0
square[d1][d2].colour = BLACK
square[d1][d2].margin = 1
a = 1
i = 1
def text(word,size,pos1,pos2,pos3):
word = font.render(str(word),size,(pos1,pos2,pos3))
return word
def colide(obj,mouseX,mouseY):
if obj.collidepoint(mouseX,mouseY) == 1:
return True
else:
return False
def click(mouseX,mouseY):
#rint("left")
global inDrag,lastDrag
for d1 in range(noWidth):
for d2 in range(noHeight):
if colide(square[d1][d2].rect,mouseX,mouseY):
square[d1][d2].man = True
#print("square",d1,d2,"has been clicked")
try:
if square[d1][d2] != lastDrag:
inDrag = True
lastDrag = square[d1][d2]
else:
inDrag = False
except UnboundLocalError:
print("error")
lastDrag = square[d1][d2]
#print(inDrag)
if square[d1][d2].margin == 0 and inDrag:
square[d1][d2].margin = 1
square[d1][d2].visits = square[d1][d2].visits + 1
elif square[d1][d2].margin == 1 and inDrag:
square[d1][d2].margin = 0
square[d1][d2].visits = square[d1][d2].visits + 1
break
'''if square[d1][d2].visits >= 5 and square[d1][d2].colour == BLACK:
square[d1][d2].visits = 0
square[d1][d2].colour = RED
elif square[d1][d2].visits >= 5 and square[d1][d2].colour == RED:
square[d1][d2].visits = 0
square[d1][d2].colour = BLACK'''
def rightClick(mouseX,mouseY):
#print("right")
global inDragRight, lastRight
for d1 in range(noWidth):
for d2 in range(noHeight):
if colide(square[d1][d2].rect,mouseX,mouseY):
square[d1][d2].man = True
#print("colide")
try:
if square[d1][d2] != lastRight:
inDragRight = True
lastRight = square[d1][d2]
else:
inDragRight = False
except:
print("error")
lastRight = square[d1][d2]
#print(inDragRight)
if square[d1][d2].colour == RED and inDragRight:
square[d1][d2].colour = BLACK
#print("black")
elif square[d1][d2].colour == BLACK and inDragRight:
square[d1][d2].colour = RED
#print("red")
break
while not done:
screen.blit(word, (0, 0))
(mouseX,mouseY) = pygame.mouse.get_pos()
#print(str(mouseX)+",",mouseY)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.MOUSEBUTTONDOWN:
#print(mouseX,mouseY)
if pygame.mouse.get_pressed()[0] == 1:
isDragging = True
if pygame.mouse.get_pressed()[2] == 1:
isFilling = True
elif pygame.mouse.get_pressed()[1] == 1:
isAuto = True
#print(pygame.mouse.get_pressed())
elif event.type == pygame.MOUSEBUTTONUP:
#print("up")
isDragging = False
isFilling = False
lastDrag = None
lastRight = False
if pygame.mouse.get_pressed()[0] == 1:
isDragging = True
if pygame.mouse.get_pressed()[2] == 1:
isFilling = True
if isAuto:
rnd1 = random.randint(0,1)
if rnd1 == 1:
isDragging = True
isFilling = False
else:
isDragging = False
isFilling = True
(mouseX,mouseY) = (random.randint(0,width*noWidth),random.randint(0,height*noHeight)+borderHeight)
#print(mouseX,mouseY)
if isDragging:
click(mouseX,mouseY)
if isFilling:
rightClick(mouseX,mouseY)
screen.fill(WHITE)
# --- Game logic should go here
i = 0
for d1 in range(noWidth):
if noHeight % 2 == 0:
'''if i == 0:
i = 1
else:
i = 0'''
for d2 in range(noHeight):
#if i % a == 0:
try:
if i == 0:
pass
elif i == 1:
pass
except AttributeError:
print("AttributeError")
square[d1][d2].margin = random.randint(0,1)
#print(square[d1][d2].visits)
square[d1][d2].rect = pygame.draw.rect(screen, square[d1][d2].colour, [(d1*width), ((d2*height)+borderHeight),width,(height)],square[d1][d2].margin)
#print("d1*width:",d1*width,"d2*height:",d2*height,"d1*width+width:",d1*width+width,"d2*height+height:",d2*height+height)
pygame.display.flip()
clock.tick(tickTime)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
You're using a PixelArray:
pixArray = pygame.PixelArray(screen)
But using a PixelArray locks your Surface, as stated in the documentation:
During its lifetime, the PixelArray locks the surface, thus you explicitly have to delete it once its not used anymore and the surface should perform operations in the same scope.
Just remove the line, since you're not using it anyway.