Related
I'm trying to fix my game. When the game is over, it calls a crash() function. It gives the user the option to play again or quit. When calling my game_loop function in the "Play Again" button inside the crash() function, the game will not restart. Any suggestions? Thanks in advance.......................
import math
import random
import time
import pygame
from pygame import mixer
# Intialize the pygame
pygame.init()
# next setup the display
display_width = 800
display_height = 600
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('waterbackground.jpg')
# game clock to time frames per second
clock = pygame.time.Clock()
# Sound
mixer.music.load("ocean.wav")
mixer.music.play(-1)
# setup colors needed in the game
black = (0,0,0)
white = (255, 255, 255)
red = (200, 0, 0)
bright_red = (255,0,0)
block_color = (53,115,255)
green = (0,200,0)
bright_green = (0,255,0)
# Caption and Icon
pygame.display.set_caption("Pirate War")
icon = pygame.image.load('pirateship.png')
pygame.display.set_icon(icon)
# cannon
cannonImg = pygame.image.load('cannonball.png')
cannonX = 0
cannonY = 480
cannonX_change = 0
cannonY_change = 10
cannon_state = "ready"
# Player
playerImg = pygame.image.load('cannon.png')
playerX = 370
playerY = 480
playerX_change = 0
# Score
score_value = 0
# add explosion sound
crash_sound = pygame.mixer.Sound("explosion.wav")
# ship
shipImg = []
shipX = []
shipY = []
shipX_change = []
shipY_change = []
num_of_ships = 6
for i in range(num_of_ships):
shipImg.append(pygame.image.load('pirateship.png'))
shipX.append(random.randint(0, 736))
shipY.append(random.randint(50, 150))
shipX_change.append(4)
shipY_change.append(40)
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
testY = 10
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
credits_font = pygame.font.Font('freesansbold.ttf', 24)
# text object function called by message display function
def text_objects(text, font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (255, 255, 255))
screen.blit(score, (x, y))
def game_over_text():
over_text = over_font.render("GAME OVER!", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
crash()
def game_credits_text(text):
over_text = over_font.render(text, True, (255, 255, 255))
screen.blit(over_text, (200, 150))
def game_credits_text_small(text):
credits_text = credits_font.render(text, True, (255, 255, 255))
screen.blit(credits_text, (20, 350))
def game_intro_text_small(text):
credits_text = credits_font.render(text, True, (255, 255, 255))
screen.blit(credits_text, (125, 375))
def player(x, y):
screen.blit(playerImg, (x, y))
def ship(x, y, i):
screen.blit(shipImg[i], (x, y))
def fire_cannon(x, y):
global cannon_state
cannon_state = "fire"
screen.blit(cannonImg, (x + 16, y + 10))
def isCollision(shipX, shipY, cannonX, cannonY):
distance = math.sqrt(math.pow(shipX - cannonX, 2) + (math.pow(shipY - cannonY, 2)))
if distance < 27:
return True
else:
return False
# function to setup message display
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 70)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
def crash():
#add crash sound
pygame.mixer.music.stop()
pygame.mixer.Sound.play(crash_sound)
game_credits_text("Game Over!")
game_credits_text_small("Created by: Dominique Kellam, Hayley Cull and Dewayne Bowen")
while True:
# check for quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill((0, 0, 0))
#add buttons to start screen
button("Play Again",150, 450, 100, 50, green, bright_green, game_loop)
button("Quit",550, 450, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
def button(msg, x, y, w, h, ic, ac, action=None):
mouse = pygame.mouse.get_pos() # returns a list of [x,y]
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y: #check is mouse over button
# redraw the rectange with active color when mouseover
pygame.draw.rect(screen, ac, (x, y, w, h))
#check for a click
if click[0] == 1 and action!=None:
action()
else:
pygame.draw.rect(screen, ic, (x, y, w, h))
# now display text on top of button that was just redrawn
smallText = pygame.font.Font('freesansbold.ttf', 20)
TextSurf, TextRect = text_objects(msg, smallText)
TextRect.center = ((x+(w/2)), (y+(h/2)))
screen.blit(TextSurf, TextRect)
def quitgame():
pygame.quit()
quit()
# start screen code
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Pirate War", largeText)
game_intro_text_small("[space bar] - fire cannon, [<] [>] arrows to move")
TextRect.center = ((display_width/2), (display_height/2))
screen.blit(TextSurf, TextRect)
#add buttons to start screen
button("Go!",150, 450, 100, 50, green, bright_green, game_loop)
button("Quit",550, 450, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
def game_loop():
global playerX
global playerX_change
global cannonX
global cannonY
global cannon_state
global score_value
# Game Loop
running = True
while running:
# RGB = Red, Green, Blue
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 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 cannon_state == "ready":
cannonSound = mixer.Sound("cannon_x.wav")
cannonSound.play()
# Get the current x cordinate of the spaceship
cannonX = playerX
fire_cannon(cannonX, cannonY)
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
# ship Movement
for i in range(num_of_ships):
# Game Over
if shipY[i] > 440:
for j in range(num_of_ships):
shipY[j] = 2000
game_over_text()
break
shipX[i] += shipX_change[i]
if shipX[i] <= 0:
shipX_change[i] = 1 #######SHIP MOVEMENT
shipY[i] += shipY_change[i]
elif shipX[i] >= 736:
shipX_change[i] = -1 ######SHIP MOVEMENT
shipY[i] += shipY_change[i]
# Collision
collision = isCollision(shipX[i], shipY[i], cannonX, cannonY)
if collision:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
cannonY = 480
cannon_state = "ready"
score_value += 1
shipX[i] = random.randint(0, 736)
shipY[i] = random.randint(50, 150)
ship(shipX[i], shipY[i], i)
# cannon Movement
if cannonY <= 0:
cannonY = 480
cannon_state = "ready"
if cannon_state == "fire":
fire_cannon(cannonX, cannonY)
cannonY -= cannonY_change
player(playerX, playerY)
show_score(textX, testY)
pygame.display.update()
game_intro()
You are setting the ship y to 2000 which is > 400 so it just goes back to crash. Change this to zero and it will work.
The issue that I am having is every time I run my game the start screen won't work right, for example, all click on the GO button and it won't let me start my game yet everything seems correct and in place, if anyone can please help it would very much be appreciated
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")
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')
clock = pygame.time.Clock()
# 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 = 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 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
screen.blit(bg, (0, 0))
pygame.display.flip()
Here is my button the Quit button works fine its just the GO button that when pressed won't let me start my game my only guess could be unless I placed something in the wrong place?
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(screen, iC, (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(screen, aC, (x , y, w, h))
if 260 + 100 > mouse[0] > 260 and 40 + 50 > mouse[1] > 40:
pygame.draw.rect(screen, BLUE, (260, 40, 100, 50))
else:
pygame.draw.rect(screen, DARK_BLUE, (260, 40, 100, 50))
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 game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(YELLOW_AND_GREEN)
text = normalfont.render("Super Racer!", 8, (0, 66, 37))
screen.blit(text, (165 - (text.get_width() / 5), 100))
button("GO!", 60, 40, 100, 50, RED, LIGHT_RED, "Play")
button("QUIT!", 260, 40, 100, 50, BLUE, DARK_BLUE, "Quit")
pygame.display.update()
clock.tick(15)
# Main game loop
def game_loop():
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
# 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)
finish_line_rect = pygame.Rect(50, 70, 235, 32)
game_intro()
score(players_finished)
# 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
inish_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):
font = pygame.font.SysFont("Impact", 15)
text = font.render(finish_text, 5, (0, 66, 37))
screen.blit(text, (90 - (text.get_width() / 2), -2))
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:
print(screen.blit(text_two, (130, 460)))
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = None
pygame.quit()
In the game loop, you're not calling the screen update. You also need to render the cars in the loop.
# Main game loop
def game_loop():
print(".......GAME LOOP........")
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
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))
#.............
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
# 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", 15)
textrect = font.render(finish_text, False, (0, 66, 37))
print('x', (SCREENWIDTH - text.get_width()) / 2)
screen.blit(textrect, (0,0))
screen.blit(textrect, ((SCREENWIDTH - textrect.get_width()) // 2, -5))
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, (130, 460))
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = 0
pygame.display.update()
clock.tick(60)
game_intro()
score(players_finished)
pygame.quit()
Try:
if action == "Play":
game_loop()
return
I think there is something wrong with your indentation of the code. You have pygame.quit() at the global level. So, you run pygame.init(), then define some functions, then pygame.quit()
Comment out the pygame.quit() line and see what happens.
I am trying to get a text to say "Game Over" for 5 seconds once a car reaches the finish line.
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")
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')
#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)
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 = 250
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 = 50
playerY_three = 450
playerCar_position_three = 0
#player4
playerIMG_four = pygame.image.load("image/yellow_car.png")
playerX_four = 200
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 = 0
placings = ["1st", "2nd", "3rd", "4th"]
def text_objects(text, font):
textSurface = font.render(text, True, RED)
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)
screen.blit(bg, (0, 0))
pygame.display.flip()
**Here is the function on where am trying to show the text temporary on the screen**
def Game_over():
if (players_finished):
clock.tick(1)
pygame.time.delay(5000)
font = pygame.font.SysFont("Impact", 25)
text = font.render("Game over!", 4, (0, 66, 37))
screen.blit(text, (185 - (text.get_width() / 2), 120))
pygame.display.flip()
# Main game loop
run = True
clock = pygame.time.Clock()
#TIP - lots of our actions take place in our while loop cause we want the function/program to run consistently
while run:
# Drawing on Screen
screen.fill(GREEN)
# 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", 35)
text = font.render("Finish line!", 4, (150, 50, 25))
screen.blit(text, (180 - (text.get_width() / 2), -8))
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.1
if keys[pygame.K_q]:
playerCar_position = 0.2
if keys[pygame.K_2]:
CarSound_two.play()
playerCar_position_two = -0.1
if keys[pygame.K_w]:
playerCar_position_two = 0.2
if keys[pygame.K_3]:
CarSound_three.play()
playerCar_position_three = -0.1
if keys[pygame.K_e]:
playerCar_position_three = 0.2
if keys[pygame.K_4]:
CarSound_four.play()
playerCar_position_four = -0.1
if keys[pygame.K_r]:
playerCar_position_four = 0.2
# 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)
finish_line_rect = pygame.Rect(50, 70, 235, 32)
# 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!")
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
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
if (players_finished and finish_text):
font = pygame.font.SysFont("Impact", 25)
text = font.render(finish_text, 4, (0, 66, 37))
screen.blit(text, (185 - (text.get_width() / 2), 90))
Game_over()
pygame.display.update()
#print("Player two has crossed into finish line first other car lost!")
#finish_text = "Player 4 is " + placings[players_finished]
pygame.display.flip()
pygame.quit()
add a variable at the start of your code with the name tick_var and if you want a fixed tickrate remove it from the parameter of the function if not change your code and att the tickrate as a paramter of the function when used.
def Game_over(tickrate):
global tick_var
tick_var +=1
if(tick_var>5*tickrate):
if (players_finished):
clock.tick(tickrate)
font = pygame.font.SysFont("Impact", 25)
text = font.render("Game over!", 4, (0, 66, 37))
screen.blit(text, (185 - (text.get_width() / 2), 120))
pygame.display.flip()
What I'am trying to do is once a car has crossed the finish line I would want it to say which car won the race but how could I add that to my game? The code works fine just trying to see how I could add some more features to it like a signal or some type of notification saying which car passed the finish line first.
import pygame
pygame.init()
#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)
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 = 250
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 = 50
playerY_three = 450
playerCar_position_three = 0
#player4
playerIMG_four = pygame.image.load("image/yellow_car.png")
playerX_four = 200
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))
# Main game loop
run = True
clock = pygame.time.Clock()
#TIP - lots of our actions take place in our while loop cause we want the function/program to run consistently
while run:
# Drawing on Screen
screen.fill(GREEN)
# 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, [65, 70], [300, 70], 5)
font = pygame.font.SysFont("Papyrus", 45)
text = font.render("Finish line!", 1, (150, 50, 25))
screen.blit(text, (195 - (text.get_width() / 2), 15))
**Here is where the finish line code is at just want too add some type of notafication saying which car has crossed the finsh line first!**
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]:
playerCar_position = -0.1
if keys[pygame.K_q]:
playerCar_position = 0.1
if keys[pygame.K_2]:
playerCar_position_two = -0.1
if keys[pygame.K_w]:
playerCar_position_two = 0.1
if keys[pygame.K_3]:
playerCar_position_three = -0.1
if keys[pygame.K_e]:
playerCar_position_three = 0.1
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
# Refresh Screen
pygame.display.flip()
pygame.quit()
Imagine the finish line is actually a rectangle. Given the finish line goes from [65, 70] to [300, 70], this gives us a rectangle at (65,70) that's 235 pixels wide. Just to make things a bit safer, we can use a much wider rectangle for the line, in case a car is moving many pixels in an update... just so it can't "jump" the line without ever entering it.
finish_line_rect = pygame.Rect( 65,70, 235,32 ) # but 32 pixels wide
Then when each car moves, you can use pygame.Rect.collidepoint() with the x,y of each car to see if it overlaps with the finish_line_rect.
For example:
# Move the Players' cars
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
# Draw the Players' cars
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 ) ):
print( "Player (one) has crossed into finish rectangle" )
if ( finish_line_rect.collidepoint( playerX_two, playerY_two ) ):
print( "Player two has crossed into finish rectangle" )
# ETC.
First off, I think you should create a "car" class as to not duplicate so much code and make it easier to work with. Regarding the finish line, I would do the following:
#Create an array with all cars X value
CarPositions = [Car1_x, Car2_x, Car3_x, Car4_x]
#Define X value of Finishline
Finishline = 600
def CheckPosition(CarPositions, Finishline):
for i in range(len(CarPositions)):
if CarPositions[i] >= Finishline:
return CarPositions[i]
You should have your array of X positions in numerical order i.e. Car 1 is before Car 2 in the array. That way the i in the for loop represents which number car has passed.
so here is my code:
import math
import random
import time
import pygame
from pygame import mixer
import pygame_functions
from pygame_functions import *
# Initialises pygame
pygame.init()
pygame.display.init()
#Difficulty
num_of_enemies = 0
set_positive_enemyX_change = 0
set_negative_enemyX_change = 0
#Menu
def menu(num_of_enemies, set_positive_enemyX_change, set_negative_enemyX_change):
screenSize(1000, 1000)
# text, fontSize, xpos, ypos, fontColour='black', font='Arial', background='clear'
difficultyLabel = makeLabel("Which level of difficulty would you like to play on ?<br>The types are :<br>- easy<br>- medium<br>- hard<br>- insane", 40, 10, 10, "blue", "Agency FB", "yellow")
showLabel(difficultyLabel)
# x, y, width, case, text, max length, fontsize
inputBox = makeTextBox(10, 270, 300, 0, "Enter difficulty level here", 0, 24)
showTextBox(inputBox)
difficultyInput = textBoxInput(inputBox)
easyLabel = makeLabel("easy settings applied", 40, 20, 310, "white", "Agency FB", )
mediumLabel = makeLabel("medium settings applied", 40, 20, 310, "white", "Agency FB",)
hardLabel = makeLabel("hard settings applied", 40, 20, 310, "white", "Agency FB", )
insaneLabel = makeLabel("insane settings applied", 40, 20, 310, "white", "Agency FB")
startingLabel = makeLabel("Starting game", 40, 40, 310, "red", "Agency FB")
if difficultyInput == "easy":
showLabel(easyLabel)
num_of_enemies = 4
set_positive_enemyX_change = 1
set_negative_enemyX_change = -1
end()
if difficultyInput == "medium":
showLabel(mediumLabel)
num_of_enemies = 6
set_positive_enemyX_change = 1.5
set_negative_enemyX_change = -1.5
end()
showLabel(startingLabel)
if difficultyInput == "hard":
showLabel(hardLabel)
num_of_enemies = 7
set_positive_enemyX_change = 2
set_negative_enemyX_change = -2
end()
if difficultyInput == "insane":
showLabel(insaneLabel)
num_of_enemies = 8
set_positive_enemyX_change = 3.5
set_negative_enemyX_change = -3.5
end()
else:
menu(num_of_enemies, set_positive_enemyX_change, set_negative_enemyX_change)
menu(num_of_enemies, set_positive_enemyX_change, set_negative_enemyX_change)
# Creates the screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('hyperspace.png')
# Sound
mixer.music.load("background.wav")
mixer.music.play(-1)
global deathSound
global liveLossSound
liveLossSound = mixer.Sound("Death sound in Minecraft.wav")
deathSound = mixer.Sound("Pacman-death.wav")
liveLossSoundBoolean = True
deathSoundBoolean = True
# Caption and Icon
pygame.display.set_caption("Space Invader")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(2)
enemyY_change.append(20)
# 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 = 5
bullet_state = "ready"
# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)
textSX = 10
textSY = 10
# Lives
lives_value = 3
textLX = 650
textLY = 10
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (255, 255, 255))
screen.blit(score, (x, y))
def show_lives(x, y):
lives = font.render("Lives : " + str(lives_value), True, (255, 255, 255))
screen.blit(lives, (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 play_liveLossSound():
liveLossSound.play()
liveLossSoundBoolean = False
def play_deathSound(deathSound):
deathSound.play()
deathSoundBoolean = False
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(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
running = True
while running:
# RGB = Red, Green, Blue
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 keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -2 #5
if event.key == pygame.K_RIGHT:
playerX_change = 2 #5
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bulletSound = mixer.Sound("laser.wav")
bulletSound.play()
# Gets the current x co-ordinate 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):
if enemyY[i] > 200: # was 440
lives_value -= 1
show_lives(textLX, textLY)
pygame.display.update()
if lives_value < 1:
for j in range(num_of_enemies):
enemyY[j] = -2000
if deathSoundBoolean:
play_deathSound(deathSound)
game_over_text()
time.sleep(5)
running = False
elif lives_value >= 1:
if liveLossSoundBoolean:
play_liveLossSound()
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
# Bouncing enemies off of edge of window // enemy speed
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = set_positive_enemyX_change
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = set_negative_enemyX_change
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
bulletY = 480
bullet_state = "ready"
score_value += 1
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state is "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
show_score(textSX, textSY)
show_lives(textLX, textLY)
pygame.display.update()
I am using this library from github https://github.com/StevePaget/Pygame_Functions/wiki ( i only used methods from this library from lines 18-63 )
I am trying to load the pygame window for my actual game after ( lines 66+) after the menu() function has finished
The problem is that I am getting these errors for no apparent reason, I am most concerned with the video initialisation error as it seems irrelevant to my program, the other errors I just do not understand as my program should logically work, as far as I understand.
You get the error video system not initialized because you called pygame.quit() beforehand (it's called by the end() function).
It even says so in the wiki of the library you use:
end()
Note: Any graphical commands which appear after the window has closed will raise an error.
There's usually no reason to call pygame.quit() at all, so I suggest to just remove it.
If you really want to close a window and open a new one, you can initialze the pygame module again (pygame.init()) and create a new window (pygame.display.set_mode(...)). But usually you're better of to restructure your code.