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
Related
This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How can I add an image or icon to a button rectangle in Pygame?
(1 answer)
Closed 2 years ago.
I have a problem in my code that I want one of your guys to answer.
This is my code:
import pygame
import time
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((1280,720))
pygame.display.set_caption('Title Screen')
titleim = pygame.image.load(r'C:\Users\kp876\Desktop\Temorairy\Kill, Buy, Repeat title screen.png')
menuim = pygame.image.load(r'C:\Users\kp876\Desktop\Menu Screen.png')
playim = pygame.image.load(r'C:\Users\kp876\Desktop\play button.png')
stickmanim = pygame.image.load('stickmanfightpose.png')
shopim = pygame.image.load('shop.png')
rplayim = pygame.transform.scale(playim,(640,360))
rshopim = pygame.transform.scale(shopim,(35,30))
popSound = pygame.mixer.Sound('Pop sound effect.wav')
menumusic = pygame.mixer.music.load('awesomeness.mp3')
screen.blit(titleim,(0,0))
pygame.display.update()
running = True
running_title = True
mouse = False
coins = 10
def redrawTitle():
screen.fill((0,0,0))
screen.blit(titleim,(0,0))
def fade(w,h):
val1 = 1
fade = pygame.Surface((w,h))
fade.fill((0,0,0))
for alpha in range(0, 300, 5):
fade.set_alpha(alpha)
redrawTitle()
screen.blit(fade,(0,0))
pygame.display.update()
def mainmenuText():
font = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 100)
text = font.render('Press Play',True,(210,200,200))
playRect = pygame.Rect((555,480),(150,120))
pygame.draw.rect(screen, (0,0,0), playRect)
screen.blit(menuim,(0,0))
screen.blit(text,(380,340))
screen.blit(rplayim,(310,360))
pygame.display.update()
def shop():
pistol = False
rifle = False
machinegun = False
white = (255,255,255)
screen.fill(white)
global coins
shopfont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 60)
shoptxt = shopfont.render('Shop', True,(0,0,0))
coinstxt = shopfont.render('Coins:' + str(coins) + '!',True,(0,0,0))
namefont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 35)
pistoltxt = namefont.render('Pistol', True, (0,0,0))
rifletxt = namefont.render('Rifle', True, (0,0,0))
machineguntxt = namefont.render('Machine Gun', True, (0,0,0))
mainshopR = pygame.Rect((0,0),(1280,720))
pistolR = pygame.Rect((50,150),(200,200))
rifleR = pygame.Rect((450,150),(200,200))
machinegunR = pygame.Rect((850,150),(200,200))
pygame.draw.rect(screen, white, mainshopR)
pygame.draw.rect(screen, (128,128,128),pistolR)
pygame.draw.rect(screen, (128,128,128),rifleR)
pygame.draw.rect(screen, (128,128,128),machinegunR)
screen.blit(shoptxt,(500,30))
screen.blit(pistoltxt,(100,220))
screen.blit(rifletxt,(500,220))
screen.blit(machineguntxt,(850,220))
screen.blit(coinstxt,(50,30))
pygame.display.update()
if pistol:
pygame.draw.rect(screen, (0,128,0),pistolR)
if rifle:
pygame.draw.rect(screen, (0,128,0),rifleR)
if machinegun:
pygame.draw.rect(screen, (0,128,0),machinegunR)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
spot1 = pygame.mouse.get_pos()
if spot1[0] > 50 and spot1[0] < 250 and spot1[1] > 150 and spot1[1] < 350:
if not pistol:
if coins >= 3:
pistolR = pygame.Rect((50,150),(200,200))
pygame.event.get()
pistol = True
coins = coins - 3
screen.blit(coinstxt,(50,30))
pygame.draw.rect(screen, (0,128,0),pistolR)
pygame.display.update()
pygame.event.get()
if spot1[0] > 450 and spot1[0] < 650 and spot1[1] > 150 and spot1[1] < 350:
if not rifle:
if coins >= 10:
pygame.event.get()
rifle = True
coins = coins - 10
print(coins)
screen.blit(coinstxt,(50,30))
pygame.draw.rect(screen, (0,128,0),rifleR)
pygame.display.update()
pygame.event.get()
if spot1[0] > 850 and spot1[0] < 1050 and spot1[1] > 150 and spot1[1] < 350:
if not machinegun:
if coins >= 30:
pygame.event.get()
machinegun = True
coins = coins - 30
print(coins)
screen.blit(coinstxt,(50,30))
pygame.draw.rect(screen, (0,128,0),machinegunR)
pygame.display.update()
pygame.event.get()
mouse1 = False
val1 = 0
nop = True
music = True
pygame.mixer.music.play(-1)
while running_title:
pygame.event.get()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running_title = False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse1 = True
if mouse1 and val1 == 1:
spot = pygame.mouse.get_pos()
if spot[0] < 705 and spot[0] > 555 and spot[1] < 600 and spot[1] > 480:
pygame.event.get()
White = (255,250,250)
screen.fill(White)
pygame.display.update()
pygame.mixer.music.stop()
popSound.play()
screen.blit(stickmanim,(0,0))
pygame.display.update()
running_title = False
if val1 == 0:
time.sleep(3)
fade(1280,720)
pygame.display.update()
mouse = True
if mouse and nop:
screen.blit(menuim,(0,0))
time.sleep(1)
mainmenuText()
val1 = 1
nop = False
go = True
while running:
if go:
fightR = pygame.Rect((550,300),(100,60))
fightborderR = pygame.Rect((540,294),(120,72))
fightfont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 25)
fightext = fightfont.render('FIGHT!',True,(0,0,0))
shopR = pygame.Rect((100,20),(130,50))
shopborderR = pygame.Rect((90,15),(150,60))
coinsfont = pygame.font.Font("C:\Windows\Fonts\Arial.ttf", 50)
shoptext = fightfont.render('Shop',True,(0,0,0))
pygame.draw.rect(screen,(0,0,0),fightborderR)
pygame.draw.rect(screen,(128,128,128),fightR)
pygame.draw.rect(screen,(0,0,0),shopborderR)
pygame.draw.rect(screen,(128,128,128),shopR)
screen.blit(fightext,(555,303))
screen.blit(rshopim,(110,30))
screen.blit(shoptext,(150,28))
pygame.display.update()
go = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running_title = False
if event.type == pygame.MOUSEBUTTONDOWN:
spot = pygame.mouse.get_pos()
if spot[0] < 660 and spot[0] > 540 and spot[1] < 366 and spot[1] > 294:
yo = 'yo'
if spot[0] < 240 and spot[0] > 90 and spot[1] > 15 and spot[1] < 85:
shop()
in shop() I want it to recognize when someone clicks an item(pistol,rifle,etc) but whenever i click it nothing happens.
Hopefully this is enough details for you guys to fix my problem.
Thanks!
ps. This code is not finished. So if you are wondering why there is some weird stuff in the code, most likely it's for later on in the project.
I am struggling to understand the logic behind your code, but the problem is caused because you are calling pygame.event.get() multiple times. Its everywhere. Sometimes you are calling it and not even storing it which again is probably not what you want. In your main loop, call it once and store it.
while running:
events = pygame.event.get()
for event in events:
#do stuff with it
Then to get access to events in shop, take events as argument def shop(events) and use this events variable instead of pygame.event.get().
Then in the main loop, when you call shop, pass events as argument.
if spot[0] < 240 and spot[0] > 90 and spot[1] > 15 and spot[1] < 85:
shop(events)
You are also calling pygame.display.update() multiple times, which might cause flickering problems.
They pygame game i made has run into an error i cannot figure out how to fix. I am new to pygame. I am using pycharm and python version 3.
The error is stopping me from doing anything and it won't even let me run it
Here is the error
TypeError: pow expected 2 arguments, got 1
Here is the code:
import math
import random
import pygame
pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((800, 600))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480
playerX_change = 0
def player(x, y):
# Blit means Draw
screen.blit(playerimg, (x, y))
def enemy(x, y):
# Blit means Draw
screen.blit(enemyimg, (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletimg, (x + 16, y + 10))
def isCollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + math.pow(math.pow(enemyY - bulletY,2)))
if distance < 27:
return True
else:
return False
background = pygame.image.load('247.jpg')
enemyimg = pygame.image.load('space-invaders.png')
enemyX = random.randint(0, 800)
enemyY = random.randint(50, 150)
enemyX_change = 4
enemyY_change = 40
bulletimg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 450
bulletX_change = 480
bulletY_change = 10
bullet_state = "ready"
score = 0
# Game loop (Put most of code for game in this loop)
while running:
screen.fill((255, 0, 0))
# BAckground
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether is 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":
bulletX = playerX
fire_bullet(playerX, bulletY)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# RGB (screen.fill) = red green blue
# 5 = 5 + - 0.1 -> 5 = 5 - 0.1
# making so nothing can go out of bounds
enemyX += enemyX_change
if enemyX <= 0:
enemyX_change = 4
enemyY += enemyY_change
elif enemyX >= 736:
enemyX_change = -4
enemyY += enemyY_change
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Bullet movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state == "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
# Collison
collision = isCollision(enemyX,enemyY,bulletX,bulletY)
if collision:
bulletY = 480
bullet_state = "ready"
score +=1
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
I believe you are trying to do this:
c = sqrt(pow(a,2) + pow(b,2))
But your code has one pow() too many. Happens to me too, when I make I make game sounds in my head, while coding (pew pew pew)
Try to remove one pow()
from
math.pow(math.pow(enemyY - bulletY,2))
to
math.pow(enemyY - bulletY,2)
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.
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
In my program I have a square that jumps over cars. But the player can just hold down space and never touch the ground. This means this can't. I am wondering how o make it force the cube to go back down to the ground after a set time.
Here is my code:
import pygame
import time
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Traffic Jumper')
orange = (255, 100, 0)
black = (0,0,0)
grey = (128,128,128)
yellow = (255,255,0)
green = (0,128,0)
red=(255,0,0)
blue = (64,224,208)
brown = (139,69,19)
magenta = (255,0,255)
olive = (128,128,0)
clock = pygame.time.Clock()
def options():
op = True
while op:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.QUIT()
screen.fill(magenta)
largeText = pygame.font.Font('freesansbold.ttf',115)
Textsurf, TextRect = text_objects("Get Hit Bro!", largeText)
TextRect.center = ((400),(300))
screen.blit(Textsurf, TextRect)
smallText = pygame.font.Font('freesansbold.ttf',30)
Textsurf, TextRect1 = text_objects("Press Y to restart and N to\ leave", smallText)
TextRect1.center = (400,(400))
screen.blit(Textsurf, TextRect1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_y:
game_loop()
elif event.key == pygame.K_n:
pygame.quit()
def pause():
paused = True
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
paused=False
pygame.QUIT()
quit()
screen.fill(olive)
largeText = pygame.font.Font('freesansbold.ttf',115)
Textsurf, TextRect = text_objects("Paused", largeText)
TextRect.center = ((400),(300))
screen.blit(Textsurf, TextRect)
smallText = pygame.font.Font('freesansbold.ttf',30)
Textsurf, TextRect1 = text_objects("Press r To Resume", smallText)
TextRect1.center = (400,(400))
screen.blit(Textsurf, TextRect1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
paused = False
def text_objects(text, font):
textsurface = font.render(text,True,red)
return textsurface, textsurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
Textsurf, TextRect = text_objects(text, largeText)
TextRect.center = ((400),(300))
screen.blit(Textsurf, TextRect)
pygame.display.update()
time.sleep(2)
#game_loop()
def game_loop():
paused = False
score = 0
x = 20
y = 520
carx = 1000
cary = 490
carspeed = 7
done = False
while not done:
screen.fill((255, 255, 255))
sky=pygame.draw.rect(screen,blue,pygame.Rect(0,0,800,400))
grass=pygame.draw.rect(screen,green,pygame.Rect(0,400,800,100))
floor1=pygame.draw.rect(screen,black,pygame.Rect(0,500,800,10))
floor2=pygame.draw.rect(screen,black,pygame.Rect(0,590,800,10))
road=pygame.draw.rect(screen,grey,pygame.Rect(0,510,800,80))
paint1=pygame.draw.rect(screen,yellow,pygame.Rect(10,540,100,\ 20))
paint2=pygame.draw.rect(screen,yellow,pygame.Rect(200,540,100,\ 20))
paint3=pygame.draw.rect(screen,yellow,pygame.Rect(400,540,100,\ 20))
paint4=pygame.draw.rect(screen,yellow,pygame.Rect(600,540,100,\ 20))
paint5=pygame.draw.rect(screen,yellow,pygame.Rect(780,540,100,\ 20))
player=pygame.draw.rect(screen, orange, pygame.Rect(x, y, 60,\ 60))
car=pygame.draw.rect(screen,black,pygame.Rect(carx,cary,80,\ 95))
if x > 800 - 60:
x -= 3
elif x < 0:
x += 3
for event in pygame.event.get():
if event.type == pygame.QUIT:
#done = True
quit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
y -= 200
if event.type == pygame.KEYUP and event.key == pygame.K_SPACE:
y += 200
if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
pause()
pressed = pygame.key.get_pressed()
#if pressed[pygame.K_UP]: y -= 3
#if pressed[pygame.K_DOWN]: y += 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
carx -= carspeed
if carx < -100:
score += 1
carspeed += 0.2
carx = 1000
if x > carx - 55 and x < carx + 55 and y > cary:
#message_display('Get Hit Bro!')
options()
font = pygame.font.SysFont(None,25)
text = font.render("Dodged: " + str(score) ,True,black)
screen.blit(text,(0,0))
pygame.display.flip()
clock.tick(60)
game_loop()
Add these variables to game_loop:
hasJumped = False
jumpCooldown = 0.0
In your loop, in the 'while not done' add
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
if hasJumped == False:
y -= 200
hasJumped = True
if hasJumped == True:
jumpCooldown += clock.get_time()
if jumpCooldown > [Jump Cooldown Limit]: # Set this number to the amount of time the car can jump at once. You'll have to experiment.
hasJumped = False
jumpCooldown = 0.0
PS : I don't understand why you use pygame.KEYDOWN/KEYUP to detect one set of keys and pygame.key.get_pressed() for another set. It seems messy
You could have a counter that was set each time the player presses space. This counter could count down each iteration, and when it reaches zero, the y position would be set back:
delta_y = 0
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
counter = 10
if event.type == pygame.KEYUP and event.key == pygame.K_SPACE:
counter = 0
if counter > 0:
delta_y = 200
counter -= 1
else:
delta_y = 0
You have to set counter = 0 outside the while loop. I've added a delta_y to the vertical position, because this is a little more cleaner way to do it. You have to update this line to:
player=pygame.draw.rect(screen, orange, pygame.Rect(x, y + delta_y, 60, 60))
The counter counts down from 10 - you'll just have to experiment with that.