My game has been created but I would really like to add a second level to it how could I go about and creating another level for my racing game? I have created the first level to it but I would want to add another level as soon as my car reaches the end of the of the finish line. How can I do that? Thank you in advance!
import pygame, random
from time import sleep
pygame.init()
# music/sounds
CarSound = pygame.mixer.Sound("image/CAR+Peels+Out.wav")
CarSound_two = pygame.mixer.Sound("image/racing01.wav")
CarSound_three = pygame.mixer.Sound("image/RACECAR.wav")
CarSound_four = pygame.mixer.Sound("image/formula+1.wav")
Crowds = pygame.mixer.Sound("image/cheer_8k.wav")
Crowds_two = pygame.mixer.Sound("image/applause7.wav")
Crowds_three = pygame.mixer.Sound("image/crowdapplause1.wav")
final_tone = pygame.mixer.Sound("image/Victory.wav")
music = pygame.mixer.music.load("image/Led Zeppelin - Rock And Roll (Alternate Mix) (Official Music Video).mp3")
pygame.mixer.music.play(-1)
bg = pygame.image.load('image/Crowds.png')
main_img = pygame.image.load("image/img4.png")
main_img2 = pygame.image.load("image/img5.png")
side_img = pygame.image.load("image/bull2.png")
side_img2 = pygame.image.load("image/fox.png")
pauseimg = pygame.image.load("image/pause2.png")
clock = pygame.time.Clock()
pause = False
# Setting up our colors that we are going to use
GREEN = (20, 255, 140)
GREY = (210, 210, 210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACKWHITE = (96, 96, 96)
BLACK = (105, 105, 105)
RGREEN = (0, 66, 37)
LIGHT_RED = (200, 0, 0)
BRIGHT_GREEN = (0, 255, 0)
DARK_BLUE = (0, 0, 139)
BLUE = (0, 0, 255)
NAVY = (0, 0 , 128)
DARK_OLIVE_GREEN = (85, 107, 47)
YELLOW_AND_GREEN = (154, 205, 50)
SCREENWIDTH = 400
SCREENHEIGHT = 500
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
Icon = pygame.image.load("image/redca_iconr.png")
pygame.display.set_icon((Icon))
# This will be a list that will contain all the sprites we intend to use in our game.
# all_sprites_list = pygame.sprite.Group()
# player
playerIMG = pygame.image.load("image/red_racecar.png")
playerX = 280
playerY = 450
playerCar_position = 0
# player2
playerIMG_two = pygame.image.load("image/greencar.png")
playerX_two = 150
playerY_two = 450
playerCar_position_two = 0
# player3
playerIMG_three = pygame.image.load("image/Orangecar.png")
playerX_three = 60
playerY_three = 450
playerCar_position_three = 0
# player4
playerIMG_four = pygame.image.load("image/yellowcar2.png")
playerX_four = 210
playerY_four = 450
playerCar_position_four = 0
# Putting cars to the screen
def player(x, y):
screen.blit(playerIMG, (x, y))
def player_two(x, y):
screen.blit(playerIMG_two, (x, y))
def player_three(x, y):
screen.blit(playerIMG_three, (x, y))
def player_four(x, y):
screen.blit(playerIMG_four, (x, y))
finish_text = ""
font2 = pygame.font.SysFont("Papyrus", 65)
players_finished = []
next_level = 0
placings = ["1st", "2nd", "3rd", "4th"]
smallfont = pygame.font.SysFont("Papyrus", 15)
normalfont = pygame.font.SysFont("arial", 25)
differntfont = pygame.font.SysFont("futura", 25)
def level(next_level):
level = normalfont.render("Level: "+ str(next_level), True, BLACK)
screen.blit(level, [250, 10])
def score(score):
text = smallfont.render("Race cars passing: " + str(score), True, RGREEN)
screen.blit(text, [145, 490])
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def message_display(text):
largText = pygame.font.Font("Mulish-Regular.ttf", 15)
TextSurf, TextRect = text_objects(text, largText)
TextRect.center = ((SCREENWIDTH / 1), (SCREENHEIGHT / 1))
screen.blit(TextSurf, TextRect)
text_two = normalfont.render("Start new game?", 5, (0, 66, 37))
time_to_blit = None
pygame.display.flip()
def button(msg, x, y, w, h, iC, aC, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen, iC, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "Play":
game_loop()
if action == "unpause":
unpause()
elif action == "Quit":
pygame.quit()
quit()
else:
pygame.draw.rect(screen, aC, (x, y, w, h))
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects(msg, newtext)
textReact.center = ((x + (100 / 2))), (y + (h / 2))
screen.blit(textSurf, textReact)
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects("QUIT!", newtext)
textReact.center = ((260 + (100 / 2))), (40 + (50 / 2))
screen.blit(textSurf, textReact)
def unpause():
global pause
pause = False
def paused():
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects("paused", newtext)
textReact.center = ((100 + (100 / 2))), (100 + (100 / 2))
screen.blit(textSurf, textReact)
screen.fill(WHITE)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(pauseimg, (0, 1))
button(" Continue!?", 40, 40, 125, 50, DARK_BLUE, BLUE, "unpause")
button("QUIT!", 260, 40, 100, 50, LIGHT_RED, 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()
screen.fill(BLACK)
text = normalfont.render("Super Racer!", 8, (0, 66, 37))
new_text = normalfont.render("By Rafa94", 8, (0, 66, 37))
screen.blit(text, (35 - (text.get_width() / 5), 5))
screen.blit(new_text, (300 - (text.get_width() / 5), 5))
screen.blit(main_img, (5,340))
screen.blit(main_img2, (85, 115))
screen.blit(side_img, (330, 455))
screen.blit(side_img2, (5, 445))
button("GO!", 60, 40, 100, 50, DARK_BLUE, BLUE, "Play")
button("QUIT!", 260, 40, 100, 50, LIGHT_RED, RED, "Quit")
pygame.display.update()
clock.tick(15)
# Main game loop
def game_loop():
global pause
global playerCar_position, playerCar_position_two, playerCar_position_three, playerCar_position_four
global playerY, playerY_two, playerY_three, playerY_four, playerX, playerX_two, playerX_three, playerX_four
finish_line_rect = pygame.Rect(50, 70, 235, 32)
finish_text = ""
players_finished = 0
next_level = 0
time_to_blit = 0
run = True
while run:
# Drawing on Screen
screen.fill(BLACK)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
# Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 20)
text = font.render("Finish line!", 2, (150, 50, 25))
screen.blit(text, (185 - (text.get_width() / 2), 45))
screen.blit(bg, (-236, -34))
screen.blit(bg, (-236, -5))
screen.blit(bg, (-235, 140))
screen.blit(bg, (-235, 240))
screen.blit(bg, (-235, 340))
screen.blit(bg, (340, -60))
screen.blit(bg, (340, -60))
screen.blit(bg, (335, 5))
screen.blit(bg, (335, 130))
screen.blit(bg, (335, 230))
screen.blit(bg, (335, 330))
screen.blit(bg, (333, 330))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
CarSound.play()
playerCar_position = -0.5
if keys[pygame.K_q]:
playerCar_position = 0.5
if keys[pygame.K_2]:
CarSound_two.play()
playerCar_position_two = -0.5
if keys[pygame.K_w]:
playerCar_position_two = 0.5
if keys[pygame.K_3]:
CarSound_three.play()
playerCar_position_three = -0.5
if keys[pygame.K_e]:
playerCar_position_three = 0.5
if keys[pygame.K_4]:
CarSound_four.play()
playerCar_position_four = -0.5
if keys[pygame.K_r]:
playerCar_position_four = 0.5
if keys[pygame.K_SPACE]:
pause = True
paused()
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
finish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
Crowds.play()
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
Crowds_three.play()
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
Crowds_two.play()
if (players_finished and finish_text):
#print("ft:", finish_text)
font = pygame.font.SysFont("Impact", 17)
textrect = font.render(finish_text, False, (0, 66, 37))
#print('x', (SCREENWIDTH - text.get_width()) / 2)
screen.blit(textrect, (65 - (text.get_width() / 5), -2))
#screen.blit(textrect, ((SCREENWIDTH - textrect.get_width()) // 2, -5))
if (finish_line_rect.collidepoint and players_finished):
#pygame.mixer.final_tone.play(-1)
final_tone.play()
pygame.mixer.music.play(0)
if (finish_text):
font = pygame.font.SysFont("Impact", 20)
text = font.render('Game Over!!!', 5, (0, 66, 37))
screen.blit(text, (250 - (text.get_width() / 5), -2))
if players_finished == 4:
time_to_blit = pygame.time.get_ticks() + 5000
if time_to_blit:
screen.blit(text_two, (100, 345))
#final_tone.play()
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = 0
if players_finished == 4:
next_level = 1
score(players_finished)
level(next_level)
pygame.display.update()
clock.tick(60)
game_intro()
pygame.quit()
Make everything you currently have for the level 1 specifically (track, soundtrack, etc) as a class of Level1. And create similar for Level2. Then in your game loop initialize level (for now it can be a global variable to look from, but it is suggested to have a Game object that has attributes like this encapsulated inside it) as Level1 while starting a new game. And when player is finished with level1 (handle the check inside Level1 class that way you can have different parameters of finishing on different levels), change the level to Level2.
What different things you need to keep in mind? Render your level based on currently selected level. Look into this answer for some more insight.
Related
import pygame
import random
import time
pygame.init()
backX = 1000
backY = 600
screen = pygame.display.set_mode((backX, backY))
score = 0
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
timespent = 0
pygame.display.set_caption('Monkey Simulator') # game name
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)
textsurface = myfont.render('Score: ' + str(score), False, (255, 255, 255))
pygame.mixer.init()
# music
sound = pygame.mixer.Sound('background1.mp3')
collection = pygame.mixer.Sound('collection.mp3')
gameover1 = pygame.mixer.Sound('gameover.mp3')
sound.play(-1)
# score indicator
text = myfont.render('Score: ' + str(score), True, white, blue)
textRect = text.get_rect() # getting the rectangle for the text object
textRect.center = (400 // 2, 400 // 2)
pre_background = pygame.image.load('background.jpeg')
background = pygame.transform.scale(pre_background, (backX, backY))
clock = pygame.time.Clock()
FPS = 60
vel = 6.5
BLACK = (0, 0, 0)
monkeyimg = pygame.image.load('monkey.png')
playerX = 410
playerY = 435
bananavelocity = 4
monkey = pygame.transform.scale(monkeyimg, (100, 120))
prebanana = pygame.image.load('banana.png')
bananaXList = []
def change():
if score>=5:
monkey = pygame.transform.scale(pre_shark, (100, 100))
banana = pygame.transform.scale(pre_meat, (50, 50))
background = pygame.transform.scale(underwater, (backX, backY))
for i in range(50):
value = random.randint(10, 980)
bananaXList.append(value)
valuenumber = random.randint(1, 30)
bananaX = bananaXList[valuenumber - 1]
bananaY = 0
banana = pygame.transform.scale(prebanana, (50, 50))
underwater = pygame.image.load('underwater.jpg')
pre_shark = pygame.image.load('shark.png')
pre_meat = pygame.image.load('meat.png')
banana_rect = banana.get_rect(topleft=(bananaX, bananaY))
monkey_rect = monkey.get_rect(topleft=(playerX, playerY))
run = True
black = (0, 0, 0)
# start screen
screen.blit(background, (0, 0))
myfont = pygame.font.SysFont("Britannic Bold", 50)
end_it = False
while not end_it:
myfont1 = pygame.font.SysFont("Britannic Bold", 35)
nlabel = myfont.render("Monkey Simulator", 1, (255, 255, 255))
info = myfont1.render("Use your right and left arrow keys to move the character.", 1, (255, 255, 255))
info2 = myfont1.render("Try to catch as many bananas as you can while the game speeds up!", 1, (255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
end_it = True
screen.blit(nlabel, (400, 150))
screen.blit(info, (100, 300))
screen.blit(info2, (100, 350))
pygame.display.flip()
while run:
clock.tick(FPS)
screen.fill(BLACK)
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
# banana animation
bananaY = bananaY + bananavelocity
timespent = int(pygame.time.get_ticks() / 1000)
bananavelocity = 4 + (timespent * 0.055)
vel = 6.5 + (timespent * 0.07)
# end game sequence
change()
if bananaY > 510:
bananaX = -50
bananaY = -50
banana
velocity = 0
gameover = pygame.image.load("gameover.jpg")
background = pygame.transform.scale(gameover, (backX, backY))
pygame.mixer.Sound.stop(sound)
gameover1.play()
# collecting coins sequence
if banana_rect.colliderect(monkey_rect):
collection.play()
valuenumber = random.randint(1, 30)
bananaX = bananaXList[valuenumber - 1]
bananaY = -25
score += 1
# moving character
if keys[pygame.K_LEFT] and playerX > 0:
playerX = playerX - vel
if keys[pygame.K_RIGHT] and playerX < 930:
playerX = playerX + vel
# adding the sprites to the screen
screen.blit(monkey, (playerX, playerY))
screen.blit(banana, (bananaX, bananaY))
banana_rect = banana.get_rect(topleft=(bananaX, bananaY))
monkey_rect = monkey.get_rect(topleft=(playerX, playerY))
pygame.draw.rect(screen, (150, 75, 0), pygame.Rect(0, 534, 1000, 20))
screen.blit(textsurface, (30, 0))
textsurface = myfont.render('Score: ' + str(score), False, (255, 255, 255))
pygame.display.update()
Right now I'm making a collection game. I want to use a function for replacing all the images once you hit a certain score. It doesn't work, though, no matter how high of a score you get. I don't understand the issue because I tested both the function and the if statement by putting print statements.
You have to use the global statement when you want to change a variable in the global namespace within a function:
def change():
global monkey, banana, background
if score>=5:
monkey = pygame.transform.scale(pre_shark, (100, 100))
banana = pygame.transform.scale(pre_meat, (50, 50))
background = pygame.transform.scale(underwater, (backX, backY))
If you don't use the global statement, the values are assigned to local variables in the scope of the function.
Another option is to return the new values from the function:
def change():
if score>=5:
return (
pygame.transform.scale(pre_shark, (100, 100)),
pygame.transform.scale(pre_meat, (50, 50)),
pygame.transform.scale(underwater, (backX, backY)) )
return monkey, banana, background
while True:
# [...]
monkey, banana, background = change()
So my pause display keeps returning after I click on the button which continues everything.
This is included in the code:
"def paused():
global pause
clock = pygame.time.Clock()"
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.fill(0)
screen.blit(intropic, (0, 0))
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
# print(mouse)
if 270 + 120 > mouse[0] > 270 and 590 + 50 > mouse[1] > 590:
pygame.draw.rect(screen, (0, 0, 0), (268, 588, 124, 54))
pygame.draw.rect(screen, (0, 255, 0), (270, 590, 120, 50))
if click[0] == 1:
pause = False
else:
pygame.draw.rect(screen, (0, 0, 0), (268, 588, 124, 54))
pygame.draw.rect(screen, (100, 255, 100), (270, 590, 120, 50))
if 770 + 150 > mouse[0] > 770 and 590 + 50 > mouse[1] > 590:
pygame.draw.rect(screen, (0, 0, 0), (768, 588, 154, 54))
pygame.draw.rect(screen, (255, 0, 0), (770, 590, 150, 50))
if click[0] == 1:
pygame.quit()
exit()
else:
pygame.draw.rect(screen, (0, 0, 0), (768, 588, 154, 54))
pygame.draw.rect(screen, (255, 100, 100), (770, 590, 150, 50))
healthfont = pygame.font.Font(None, 40)
start = healthfont.render("Weiter", True, (0, 0, 0))
textRect1 = start.get_rect()
textRect1.topright = [370, 603]
screen.blit(start, textRect1)
healthfont = pygame.font.Font(None, 40)
end = healthfont.render("Beenden", True, (0, 0, 0))
textRect1 = end.get_rect()
textRect1.topright = [900, 603]
screen.blit(end, textRect1)
pausefont = pygame.font.Font(None, 80)
pausetxt = pausefont.render("Pause", True, (0, 0, 0))
textRect1 = pausetxt.get_rect()
textRect1.center = [800, 300]
screen.blit(pausetxt, textRect1)
pygame.display.flip()
This is the code if you press P:
if keys[4]:
pause = True
paused()
There is also a global pause = False
any help is much appreciated
Being paused or not paused, it's just a boolean. Your program must decide what that means.
Perhaps it means that the screen is not updated, and perhaps input-handling is different.
Below is a re-working of your code where if the paused flag global_paused ever gets set, the screen stops painting everything except a "*** PAUSED ***" banner.
Note the use of pyagme.Rect to store rectangles, constants for colours, an simpler testing of collisions. Fonts only need to be loaded once, so these have been moved outside the main loop.
global_paused = False
BLACK = (0, 0, 0)
RED = (0, 255, 0)
GREENISH = (100, 255, 100)
area1 = pygame.Rect( 268, 588, 124, 54 )
area2 = pygame.Rect( 270, 590, 120, 50 )
area3 = pygame.Rect(768, 588, 154, 54)
area4 = pygame.Rect(770, 590, 150, 50)
healthfont = pygame.font.Font(None, 40)
start = healthfont.render("Weiter", True, BLACK )
textRect1 = start.get_rect()
textRect1.topright = [370, 603]
healthfont = pygame.font.Font(None, 40)
end = healthfont.render("Beenden", True, BLACK )
textRect1 = end.get_rect()
textRect1.topright = [900, 603]
pausefont = pygame.font.Font(None, 80)
pausetxt = pausefont.render("Pause", True, BLACK )
textRect1 = pausetxt.get_rect()
textRect1.center = [800, 300]
pause_mode = pausefont.render( "*** PAUSED ***", True, RED, BLACK )
clock = pygame.time.Clock()
exiting = False
while not exiting:
mouse_click = None
mouse_pos = pygame.mouse.get_pos()
# Handle Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif ( event.type == pygame.MOUSEBUTTONUP ):
mouse_click = pygame.mouse.get_pressed()
if ( area1.collidepoint( event.pos ) ):
global_paused = not global_paused
elif ( area3.collidepoint( event.pos ) ):
exiting = True
elif ( event.type == pygame.KEYUP ):
if ( event.key == pygame.K_p ):
global_paused = not global_paused
# draw the screen
screen.fill( BLACK )
if ( not global_paused ):
screen.blit(intropic, (0, 0))
pygame.draw.rect(screen, BLACK, area1 )
if ( area1.collidepoint( mouse_pos ) ):
pygame.draw.rect(screen, RED, area2 )
else:
pygame.draw.rect(screen, GREENISH, area2 )
pygame.draw.rect(screen, BLACK, area3 )
pygame.draw.rect(screen, RED, area4 )
else:
pygame.draw.rect(screen, GREENISH, area4 )
screen.blit(start, textRect1)
screen.blit(end, textRect1)
screen.blit(pausetxt, textRect1)
else:
# everything is paused
screen.blit( pause_mode, ( 0, 0 ) )
pygame.display.flip()
clock.tick( 60 )
pygame.quit()
I am making a game, and when I want to go through the loop normally, it doesn't work.
it goes through the loop, but for some reason, it backtracks, rather than starting over. When I add a continue statement, the button just disappears.
Why isn't the continue statement working properly?
Here is my code:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
bro = True
x = 100
y = 100
#button1 = pygame.draw.rect(screen, (0, 0, 255), (200, 200, 30, 30))
#if check <= pos - (w/2) and check >=
pygame.display.set_caption("Auto Maze!")
donk = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
try:
assert button1.collidepoint(mouse)
except AssertionError:
pass
except NameError:
pass
else:
donk = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
screen.fill((0, 0, 0))
"""try:
assert player.colliderect(wall1)
except AssertionError:
pass
except NameError:
pass
else:
death_screen = pygame.display.set_mode((400, 300))
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (200, 200, 30, 30))
if donk:
break"""
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
if player.colliderect(wall1):
death_screen = pygame.display.set_mode((400, 300))
myfont = pygame.font.SysFont("Comic Sans MS", 10)
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if donk:
screen = pygame.display.set_mode((400, 300))
clock.tick(60)
pygame.display.flip()
quit()
Add a gameover to your application:
gameover = False:
Do different things in the application loop, dependent on the state of gameover:
while not done:
# [...]
if not gameover:
# draw game scene
# [...]
else:
# draw gamover scene (button)
# [...]
Set the gameover state if the player collides:
gameover = player.colliderect(wall1)
Reset the position of the player if the continue button is pressed:
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
See the example:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Auto Maze!")
pygame.font.init()
myfont = pygame.font.SysFont("Comic Sans MS", 10)
x, y = 100, 100
gameover = False
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
screen.fill((0, 0, 0))
if not gameover:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
gameover = player.colliderect(wall1)
else:
button1 = pygame.draw.rect(screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
pygame.display.flip()
clock.tick(60)
quit()
This does the same as your code, but just cleaned up. Hopefully it solves your problem
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
mouse = None
click = False
state = "main"
myfont = pygame.font.SysFont("Comic Sans MS", 10)
player = pygame.Rect(100,100,60,60)
wall1 = pygame.Rect(300, 0, 100, 300)
button1 = pygame.Rect(175, 100, 60, 30)
pygame.display.set_caption("Auto Maze!")
while not done:
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
click = True
screen.fill((0, 0, 0))
if state == "main":
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
player.y -= 5
elif pressed[pygame.K_s]:
player.y += 5
elif pressed[pygame.K_a]:
player.x -= 5
elif pressed[pygame.K_d]:
player.x += 5
#draw player and wall
pygame.draw.rect(screen, (0, 255, 0), player)
pygame.draw.rect(screen, (255, 0, 0), wall1)
if player.colliderect(wall1):
state = "death"
else:
pygame.draw.rect(screen, (0, 0, 255), button1)
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if click:
if button1.collidepoint(mouse):
state = "main"
player.x = 100
player.y = 100
clock.tick(60)
pygame.display.flip()
quit()
I am a python beginner. I want to recreate chrome dino game. the random rectangle won't stop and the loop runs forever...please help me to stop the loop and make rectangles move.
Code:
import pygame
import random
pygame.init()
win = pygame.display.set_mode((500, 500))
#red rectangle(dino)
x = 20
y = 400
width = 30
height = 42
gravity = 5
vel = 18
black = (0, 0, 0)
#ground
start_pos = [0, 470]
end_pos = [500, 470]
#cactus
x1 = 20
y1 = 30
white = (2, 200, 200)
run = True
clock = pygame.time.Clock()
while run:
clock.tick(30)
pygame.time.delay(10)
win.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#random rectangle generation
for i in range(1):
width2 = random.randint(25, 25)
height2 = random.randint(60, 60)
top = random.randint(412, 412)
left = random.randint(300, 800)
rect = pygame.draw.rect(win, white, (left, top, width2,height2))
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
y = y - vel
else:
y = min(428, y + gravity)
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.draw.line(win, white, start_pos, end_pos, 2)
pygame.display.update()
pygame.display.flip()
pygame.quit()
pygame.draw.rect() des not "generate" a rectangle, it draws a rectangle on a surface.
pygame.Rect is a rectangle object. Create an instance of pygame.Rect before the main application loop:
obstracle = pygame.Rect(500, random.randint(0, 412), 25, 60)
Change the position of the rectangle:
obstracle.x -= 3
if obstracle.right <= 0:
obstracle.y = random.randint(0, 412)
And draw the rectangle to the window surface:
pygame.draw.rect(win, white, obstracle)
Example:
import pygame
import random
pygame.init()
win = pygame.display.set_mode((500, 500))
start_pos = [0, 470]
end_pos = [500, 470]
gravity = 5
vel = 18
black = (0, 0, 0)
white = (2, 200, 200)
hit = 0
dino = pygame.Rect(20, 400, 30, 40)
obstracles = []
number = 5
for i in range(number):
ox = 500 + i * 500 // number
oy = random.randint(0, 412)
obstracles.append(pygame.Rect(ox, oy, 25, 60))
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
dino.y -= vel
else:
dino.y = min(428, dino.y + gravity)
for obstracle in obstracles:
obstracle.x -= 3
if obstracle.right <= 0:
obstracle.x = 500
obstracle.y = random.randint(0, 412)
if dino.colliderect(obstracle):
hit += 1
win.fill(black)
color = (min(hit, 255), max(255-hit, 0), 0)
pygame.draw.rect(win, color, dino)
for obstracle in obstracles:
pygame.draw.rect(win, white, obstracle)
pygame.draw.line(win, white, start_pos, end_pos, 2)
pygame.display.update()
pygame.quit()
Just out of curiosity, why does a game lag when I load an image as well as display pygame shapes for example rectangles, circles and ellipses. I have this code where you shoot the ghosts that fall down (I'm still working on the shooting part). I made the cannon out of pygame shapes. But when I run it the images of the ghosts are prefect but the images of the cannons lag and disappears and reappear and so on. Is there any way to stop this lag or disappear and reappear thing? I'm running python 2.6 with windows vista.
import pygame, sys, random, math
from pygame.locals import *
WINDOWHEIGHT = 600
WINDOWWIDTH = 600
FPS = 30
BACKGROUNDCOLOR = (255, 255, 255)
TEXTCOLOR = (0, 0, 0)
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
BROWN = (139, 69, 19)
DARKGRAY = (128, 128, 128)
BGCOLOR = WHITE
GHOSTSPEED = 10
GHOSTSIZE = 20
ADDNEWGHOSTRATE = 8
def keyToPlayAgain():
while True:
for event in event.type.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
return
def getAngle(x1, y1, x2, y2):
# Return value is 0 for right, 90 for up, 180 for left, and 270 for down (and all values between 0 and 360)
rise = y1 - y2
run = x1 - x2
angle = math.atan2(run, rise) # get the angle in radians
angle = angle * (180 / math.pi) # convert to degrees
angle = (angle + 90) % 360 # adjust for a right-facing sprite
return angle
def Text(text, font, surface, x, y):
textobj = font.render(text, 2, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
pygame.init()
mainClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWHEIGHT, WINDOWWIDTH))
pygame.display.set_icon(pygame.image.load('s.icon'))
pygame.display.set_caption('Ghost Invasion Pacfighters')
pygame.mouse.set_visible(False)
font = pygame.font.SysFont(None, 48)
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
ghostImage = pygame.image.load('ghosts.png')
dotImage = pygame.image.load('dot.png')
dotRect = dotImage.get_rect()
creditsPage = pygame.image.load('credits.png')
titlePage = pygame.image.load('title.png')
pygame.time.wait(10000)
DISPLAYSURF.blit(creditsPage, (0, 0))
pygame.time.wait(10000)
DISPLAYSURF.blit(titlePage, (0, 0))
pygame.display.update()
cannonSurf = pygame.Surface((100, 100))
cannonSurf.fill(BGCOLOR)
pygame.draw.circle(cannonSurf, DARKGRAY, (20, 50), 20)
pygame.draw.circle(cannonSurf, DARKGRAY, (80, 50), 20)
pygame.draw.rect(cannonSurf, DARKGRAY, (20, 30, 60, 40))
pygame.draw.circle(cannonSurf, BLACK, (80, 50), 15)
pygame.draw.circle(cannonSurf, BLACK, (80, 50), 20, 1)
pygame.draw.circle(cannonSurf, BROWN, (30, 70), 20)
pygame.draw.circle(cannonSurf, BLACK, (30, 70), 20, 1)
health = 100
score = 0
topScore = 0
while True:
ghosts = []
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
ghostAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_x:
bombs()
elif event.type == ESCAPE:
pygame.quit()
sys.exit()
mousex, mousey = pygame.mouse.get_pos()
for cannonx, cannony in ((100, 500), (500, 500)):
degrees = getAngle(cannonx, cannony, mousex, mousey)
rotatedSurf = pygame.transform.rotate(cannonSurf, degrees)
rotatedRect = rotatedSurf.get_rect()
rotatedRect.center = (cannonx, cannony)
DISPLAYSURF.blit(rotatedSurf, rotatedRect)
pygame.draw.line(DISPLAYSURF, BLACK, (mousex - 10, mousey), (mousex + 10, mousey))
pygame.draw.line(DISPLAYSURF, BLACK, (mousex, mousey - 10), (mousex, mousey + 10))
pygame.draw.rect(DISPLAYSURF, BLACK, (0, 0, WINDOWWIDTH, WINDOWHEIGHT), 1)
pygame.display.update()
if not reverseCheat and not slowCheat:
ghostAddCounter += 1
if ghostAddCounter == ADDNEWGHOSTRATE:
ghostAddCounter = 0
newGhost = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-GHOSTSIZE), 0 - GHOSTSIZE, GHOSTSIZE, GHOSTSIZE),
'speed': (GHOSTSIZE),
'surface':pygame.transform.scale(ghostImage, (GHOSTSIZE, GHOSTSIZE)),
}
ghosts.append(newGhost)
for s in ghosts:
if not reverseCheat and not slowCheat:
s['rect'].move_ip(0, s['speed'])
elif reverseCheat:
s['rect'].move_ip(0, -5)
elif slowCheat:
s['rect'].move_ip(0, -1)
for s in ghosts[:]:
if s['rect'].top > WINDOWHEIGHT:
health -= 10
DISPLAYSURF.fill(BACKGROUNDCOLOR)
Text('Score: %s' % (score), font, DISPLAYSURF, 10, 0)
Text('Top score: %s' % (topScore), font, DISPLAYSURF, 10, 40)
Text('Health: %s' % (health), font, DISPLAYSURF, 10, 560)
for s in ghosts:
DISPLAYSURF.blit(s['surface'], s['rect'])
pygame.display.update()
mainClock.tick(FPS)
pygame.mixer.music.stop()
gameOverSound.play()
Text('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
pygame.display.update()
keyToPlayAgain()
pygame.display.update()
gameOverSound.stop()
The problem is that you draw your cannons, update the display, then clear the display, draw the other stuff, and update the display again. You basically never see the falling ghosts and the cannons at the same time. This results in the flickering you see.
So remove pygame.display.update() from this for loop
for cannonx, cannony in ((100, 500), (500, 500)):
...
pygame.display.update()
and put DISPLAYSURF.fill(BACKGROUNDCOLOR) at the top of your while loop (or at least before you draw anything):
while True:
for event in pygame.event.get():
...
mousex, mousey = pygame.mouse.get_pos()
DISPLAYSURF.fill(BACKGROUNDCOLOR)
for cannonx, cannony in ((100, 500), (500, 500)):
...
It's best to clear the background once at the start of your code that draws everything, and call pygame.display.update() once at the end of that drawing code.