Related
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
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()
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 have made a game where you have to dodge objects. You can also pause the game by pressing p. Once you pause the game you get an option if you want to continue or quit. For me, the quit button is working but the continue button isn't. Where it says define unpause() is where the code starts for the pause button.
import time
import random
pygame.init()
display_width = 800
display_height = 600
red = (200,0,0)
orange = (255, 165, 0)
yellow = (255, 242, 0)
green = (0,200,0)
blue = (0,0,255)
indigo = (75, 0, 130)
violet = (238, 130, 238)
black = (0,0,0)
white = (255,255,255)
bright_red = (255,0,0)
bright_green = (0,255,0)
car_width = 86
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Racing Game")
clock = pygame.time.Clock()
carImg = pygame.image.load("download.png")
carImg = pygame.transform.scale(carImg,(100,160))
pause = False
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render ("Dodged: "+str(count), True, black)
gameDisplay.blit(text,(0,0))
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def car(x,y):
gameDisplay.blit(carImg, (x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font("freesansbold.ttf",100)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
game_loop()
time.sleep(2000)
def crash():
message_display ("YOU CRASHED")
def button(msg,x,y,w,h,ic,ac,action = None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(click)
if x + w > mouse [0] > x and y + h > mouse [1] > y:
pygame.draw.rect(gameDisplay, ac, (x,y,w,h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ic, (x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def quitgame():
pygame.quit()
quit
def unpause():
global pause
pause = False
def paused():
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font("freesansbold.ttf",100)
TextSurf, TextRect = text_objects("PAUSED", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button ("Continue!",150,450,100,50,green,bright_green,unpause)
button ("Quit!",550,450,100,50,red,bright_red,"quit")
pygame.display.update()
clock.tick(15)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font("freesansbold.ttf",100)
TextSurf, TextRect = text_objects("Racing Game", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button ("GO!",150,450,100,50,green,bright_green,"play")
button ("QUIT!",550,450,100,50,red,bright_red,"quit")
pygame.display.update()
clock.tick(15)
def game_loop():
global pause
x = (display_width * 0.45)
y = (display_height * 0.72)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
thingCount = 1
dodged = 0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.key == pygame.K_p:
pause = True
paused()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
car (x,y)
things_dodged(dodged)
if x > display_width - car_width or x < -10:
crash()
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0,display_width)
dodged += 1
thing_speed += 1
#thing_width += (dodged * 0.5)
if y < thing_starty + thing_height:
if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width:
crash()
pygame.display.update()
clock.tick(100)
game_intro()
game_loop()
pygame.quit()
quit()
Please try to help. I am saying Thank You in advance for all your guy's help.
You have typo in while paused: in def paused()- it has to be while pause:
def paused():
while pause: # <- pause instead of paused
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()