pygame.quit() giving init.font error while switching files - python

I made a main python file that holds the whole game itself and for each window, I'm using different files. For instance, for the beginning of the game, I want to create a window where you can choose the language with 2 boxes, which makes a variable = 1 or 2. The main file reads the variable and with an if condition the language is defined.
The main problem is that when I want to close the language file and resume with the main one, it pops up an error saying the font is not defined when I did pygame.quit()
MAIN FILE
import pygame
from lib.pygame_functions import *
from pygame.locals import *
import time
import random
def language():
import lib.language.languageVS
from lib.language.languageVS import lang
language()
pygame.quit()
if lang == '1':
from languages.en import *
lang_selection = 1
print(selection_language)
elif lang == '2':
from languages.es import *
lang_selection = 1
print(selection_language)
pygame.init()
white = (255,255,255)
black = (0,0,0)
green = (0, 200, 0)
red = (200, 0, 0)
blue = (0, 0, 200)
bright_green = (0, 255, 0)
bright_red = (255, 0, 0)
bright_blue = (0, 0, 255)
introbackground = pygame.image.load('introbg.png')
gameDisplay = pygame.display.set_mode((800, 600)) #surface
pygame.display.set_caption('Neon Fight') #titutlo
def names():
import lib.playernames.TEXTINPUT
from lib.playernames.TEXTINPUT import a
print(a)
import lib.playernames.TEXTINPUT2
from lib.playernames.TEXTINPUT2 import b
print(b)
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',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def quitgame():
pygame.quit()
quit()
def game():
time.sleep(4)
def startgame():
pygame.quit()
names()
game()
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(gameDisplay, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
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 game_intro():
intro = True
while intro:
gameDisplay.blit(introbackground, (0, 0))
#gameDisplay.fill(white)
mouse = pygame.mouse.get_pos()
#print(mouse)
#BUTTONS
button('Play', 350, 325, 100, 50, green, bright_green, startgame)
button('Instructions', 350, 400, 100, 50, blue, bright_blue)
button('Quit', 350, 475, 100, 50, red, bright_red, quitgame)
pygame.display.update()
#quit_x
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.quit() #desinizialization
quit()
game_intro()
gameExit = False
while not gameExit: #quit_x
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameDisplay.fill(white)
pygame.display.update() #actualizar_surface
pygame.quit() #desinizialization
quit()
lib.language.languageVS
import pygame
from pygame.locals import *
import time
import random
lang = 0
pygame.init() #inizialization
white = (255,255,255)
black = (0,0,0)
green = (0, 200, 0)
red = (200, 0, 0)
blue = (0, 0, 200)
bright_green = (0, 255, 0)
bright_red = (255, 0, 0)
bright_blue = (0, 0, 255)
gameDisplay = pygame.display.set_mode((800, 600)) #surface
pygame.display.set_caption('Neon Fight') #titutlo
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',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def english():
global lang
lang = 1
pygame.quit()
def spanish():
global lang
lang = 2
pygame.quit()
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(gameDisplay, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
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 language():
language = True
while language:
gameDisplay.fill(white)
mouse = pygame.mouse.get_pos()
#print(mouse)
#BUTTONS
button('Play', 350, 325, 100, 50, green, bright_green, spanish)
button('Instructions', 350, 400, 100, 50, blue, bright_blue, english)
pygame.display.update()
#quit_x
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.quit() #desinizialization
quit()
language()
gameExit = False
while not gameExit: #quit_x
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameDisplay.fill(white)
pygame.display.update() #actualizar_surface
TRACEBACK:
Exception has occurred: error
font not initialized
File "F:\APPVISUAL\lib\language\languageVS.py", line 55, in button
smallText = pygame.font.Font('freesansbold.ttf', 20)
File "F:\APPVISUAL\lib\language\languageVS.py", line 73, in language
button('Play', 350, 325, 100, 50, green, bright_green, spanish)
File "F:\APPVISUAL\lib\language\languageVS.py", line 85, in <module>
language()

An easy solution would be to add pygame.init() before
smallText = pygame.font.Font('freesansbold.ttf', 20)

Managed to solve it. Apparently just changing the function worked. I thought that instead of using pygame.quit() to close the pygame module, i could just add everything on a loop and whenever an option is selected the loop stops going on and lets the code end by itself without forcing it. In that way i can import it in the main file and code keep running! This is what the code is in lib.languageVS file:
import pygame
from pygame.locals import *
import time
import random
import sys
lang = 0
pygame.init() #inizialization
white = (255,255,255)
black = (0,0,0)
green = (0, 200, 0)
red = (200, 0, 0)
blue = (0, 0, 200)
bright_green = (0, 255, 0)
bright_red = (255, 0, 0)
bright_blue = (0, 0, 255)
gameDisplay = pygame.display.set_mode((800, 600)) #surface
pygame.display.set_caption('Neon Fight') #titutlo
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',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def english():
global lang
lang = 1
def spanish():
global lang
lang = 2
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(gameDisplay, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
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 language():
language = True
while language == True:
gameDisplay.fill(white)
mouse = pygame.mouse.get_pos()
#print(mouse)
#BUTTONS
button('SPANISH', 350, 325, 100, 50, green, bright_green, spanish)
button('ENGLISH', 350, 400, 100, 50, blue, bright_blue, english)
if lang == 1:
language = False
elif lang == 2:
language = False
pygame.display.update()
#quit_x
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.quit() #desinizialization
language()
##OLD_VERSION
# def language():
# language = True
# while language:
# gameDisplay.fill(white)
# mouse = pygame.mouse.get_pos()
# #print(mouse)
# #BUTTONS
# button('SPANISH', 350, 325, 100, 50, green, bright_green, spanish)
# button('ENGLISH', 350, 400, 100, 50, blue, bright_blue, english)
# pygame.display.update()
# #quit_x
# for event in pygame.event.get():
# if event.type == pygame.QUIT:
# gameExit = True
# pygame.quit() #desinizialization
# if lang == 1:
# pygame.quit()
# elif lang == 2:
# pygame.quit()

Related

How do I get my game to loop when calling the function from a button?

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.

Clicking buttons in pygame

So I have created a small menu that contains a "Start" button and a "quit" button. Obviously what I want is when I click Start, it starts the game loop, and when I hit quit, it quits the game. I already coded something, but it doesn't work. I think the problem is that I don't have a function for game loop and quit.
Here is the whole code:
import pygame
pygame.init()
win = pygame.display.set_mode((1200, 600))
pygame.display.set_caption("WALTHER")
clock = pygame.time.Clock()
BLACK = (0, 0, 0)
WHITE = (255,255,255)
RED = (255, 0, 0)
GREEN = (13, 255, 0)
YELLOW = (0, 255, 20)
BRIGHT_YELLOW = (255, 255, 20)
player = pygame.Rect(40, 45, 30, 30)
vel = 4
vel_left = 5
vel_right = -5
class MovingRect(pygame.Rect):
def __init__(self, x, y, w, h, vel):
# Call the __init__ method of the parent class.
super().__init__(x, y, w, h)
self.vel = vel
def update(self):
self.x += self.vel # Move.
if self.right > 600 or self.left < 320: # If it's not in this area.
self.vel = -self.vel # Invert the direction.
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
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(win, ac, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "Quit":
pygame.quit()
else:
pygame.draw.rect(win, ic, (x, y, w, h))
smallText = pygame.font.Font("freesansbold.ttf",50)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x+(w/2)), (y+(h/2)))
win.blit(textSurf, textRect)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
win.fill(WHITE)
largeText2 = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects("Red Square", largeText2)
TextRect.center = ((600), (100))
win.blit(TextSurf, TextRect)
button("Start", 525, 250, 150, 60, YELLOW, BRIGHT_YELLOW)
button("Quit", 525, 350, 150, 60, YELLOW, BRIGHT_YELLOW)
pygame.display.update()
clock.tick(15)
def message_display(text):
largeText = pygame.font.Font(None , 115)
win.blit(largeText.render(text, True, (RED)), (370,250))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
rotatingrects = [
pygame.Rect(630, 300, 250, 20),
pygame.Rect(920, 300, 250, 20)
]
movingrects = [
MovingRect(320, 120, 30, 30, vel_left),
MovingRect(320, 240, 30, 30, vel_left),
MovingRect(320, 360, 30, 30, vel_left),
MovingRect(570, 180, 30, 30, vel_right),
MovingRect(570, 300, 30, 30, vel_right),
MovingRect(570, 420, 30, 30, vel_right)
]
walls = [
pygame.Rect(0, 0, 1200, 20), pygame.Rect(0, 0, 20, 600),
pygame.Rect(0, 580, 1200, 20), pygame.Rect(1180, 0, 20, 600),
pygame.Rect(300, 0, 20, 530), pygame.Rect(20, 100, 230, 20),
pygame.Rect(70, 200, 230, 20), pygame.Rect(20, 300, 230, 20),
pygame.Rect(70, 400, 230, 20), pygame.Rect(600, 100, 20, 500)
]
run = True
while run:
# Handle the events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
game_intro()
keys = pygame.key.get_pressed()
# Update the player coordinates.
if keys[pygame.K_LEFT] and player.x > 0:
player.x -= vel
if keys[pygame.K_RIGHT] and player.x < 1200 - player.width:
player.x += vel
if keys[pygame.K_UP] and player.y > 0:
player.y -= vel
if keys[pygame.K_DOWN] and player.y < 600 - player.height:
player.y += vel
# Game logic for walls and moving objects
for wall in walls:
# Check if the player rect collides with a wall rect.
if player.colliderect(wall):
print("Game over")
message_display("Game Over")
for movingrect in movingrects:
movingrect.update() # Movement and bounds checking.
if player.colliderect(movingrect):
print("Game over")
message_display("Game Over")
for rotatingrect in rotatingrects:
if player.colliderect(rotatingrect):
print("Game over")
# Drawing everything
win.fill(WHITE)
pygame.draw.rect(win, RED, player)
# Drawing walls and moving objects
for rotatingrect in rotatingrects:
pygame.draw.rect(win, BLACK, rotatingrect)
for wall in walls:
pygame.draw.rect(win, BLACK, wall)
for movingrect in movingrects:
pygame.draw.rect(win, GREEN, movingrect)
pygame.display.update()
clock.tick(60)
pygame.quit()
I think the problem is here:
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(win, ac, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "Quit":
pygame.quit()
else:
pygame.draw.rect(win, ic, (x, y, w, h))
I just want to do if action == "Start":
play the game
if action == "Quit":
quit the game
Define two callback functions which you need to pass as the action argument to the button function.
In the quit_game function, you can call pygame.quit and sys.exit to close the window. The start_game function needs to be defined in the game_intro function, because we have to access the intro variable, with the help of the nonlocal keyword, and set it to False, so that the game_intro function will be terminated and the main loop can start.
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(win, ac, (x, y, w, h))
if click[0] == 1 and action is not None:
action() # Call the callback function.
# etc. ...
def quit_game():
pygame.quit()
sys.exit() # `import sys` at the top of the file.
def game_intro():
intro = True
def start_game():
# Set the intro variable in the enclosing scope to False.
nonlocal intro
intro = False
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
win.fill(WHITE)
largeText2 = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects("Red Square", largeText2)
TextRect.center = ((600), (100))
win.blit(TextSurf, TextRect)
# Pass the two callback functions to `button`.
button("Start", 525, 250, 150, 60, YELLOW, BRIGHT_YELLOW, start_game)
button("Quit", 525, 350, 150, 60, YELLOW, BRIGHT_YELLOW, quit_game)
pygame.display.update()
clock.tick(15)
Also, don't call game_intro inside the main while loop.
game_intro()
run = True
while run:

Buttons and text flickering

I copied most of this code from an earlier script which worked fine, but when I load up the game, pretty much all the elements are flickering.
Here is the Minimal complete verifiable example here:
import pygame
pygame.init()
displayWidth = 1280
displayHeight = 720
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Grow')
black = (0, 0, 0)
brown = (100, 100, 0)
green = (0, 200, 0)
lightGreen = (0, 255, 0)
red = (200, 0, 0)
lightRed = (255, 0, 0)
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)
clock = pygame.time.Clock()
FPS = 60
def gameIntro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(brown)
message_to_screen('Welcome to Tanks', green, -100, 'large')
message_to_screen('The objective is to shoot and destroy', black, -30)
message_to_screen('Shoot and destroy the enemy tank before they destroy you', black, 10)
message_to_screen('The more enemies you destroy, the harder they get', black, 50)
button('quit', 500, 500, 100, 50, red, lightRed, action = 'quit')
button('play', 200, 500, 100, 50, green, lightGreen, action = 'play')
pygame.display.update()
clock.tick(0)
def gameLoop():
pygame.quit()
quit()
def button(text, x, y, width, height, inactive_color, active_color, action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
if click[0] == 1 and action != None:
if action == 'quit':
pygame.quit()
quit()
if action == 'play':
gameLoop()
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
text_to_button(text, black, x, y, width, height)
def text_to_button(msg, colour, buttonx, buttony, buttonwidth, buttonheight, size = 'small'):
textSurf, textRect = text_objects (msg, colour, size)
textRect.center = ((buttonx + (buttonwidth/2)), buttony + (buttonheight/2))
gameDisplay.blit(textSurf, textRect)
pygame.display.update()
def message_to_screen(msg, colour, y_displace = 0, size = 'small'):
textSurf, textRect = text_objects (msg, colour, size)
textRect.center = (displayWidth / 2), (displayHeight / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
pygame.display.update()
def text_objects(text, colour, size):
if size == 'small':
textSurface = smallfont.render (text, True, colour)
elif size == 'medium':
textSurface = medfont.render (text, True, colour)
elif size == 'large':
textSurface = largefont.render (text, True, colour)
return textSurface, textSurface.get_rect()
gameIntro()
For some reason, in the gameIntro function, when I call the message_to_screen and button functions, they all start flickering (everything except the first function called). Changing the order of the functions changes which one will stop flickering. Everything else works fine. The buttons change colour when the cursor is above them and they can still be clicked and have functionality
Don't call pygame.display.update() multiple times in each iteration of your game loop. It will lead to the screen flickering you see.
Simply remove the pygame.display.update() calls in the message_to_screen and text_to_button functions.

How do I get random enemies to appear from list?

I'm trying to get a random car to appear from a list of cars saved in variables. The issue seems to be it chooses a random car from the list and doesn't change it while the game is being played. I'd like to change the car each time the previous car goes off screen.
Each time the game starts it chooses one car from the random list, but does not change the car each time the game loop runs.
I believe the problem lies in this bit of code
randomCars = [car1, car2, car3, car4, car5, car6, car7, car8]
enemy = random.choice(randomCars)
I have pasted the full code below:
import pygame
import time
import random
pygame.init()
#############
#############
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)
block_color = (53, 115, 255)
crash_sound = pygame.mixer.Sound("crash.mp3")
car_width = 55
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Super Racer')
clock = pygame.time.Clock()
gameIcon = pygame.image.load('carIcon.png')
backgroundImage = pygame.image.load("background.png")
backgroundImage = pygame.transform.scale(backgroundImage, (800, 600))
gameDisplay.blit(backgroundImage, (0, 0))
pygame.display.set_icon(gameIcon)
pause = False
# crash = True
def score(count):
font = pygame.font.SysFont("comicsansms", 25)
text = font.render("SCORE: " + str(count), True, red)
gameDisplay.blit(text, (0, 0))
def load_image(name_img):
car = pygame.image.load(name_img)
car = pygame.transform.scale(car, (60, 100)) # resize graphic
return car.convert_alpha() # remove whitespace from graphic
carImg = load_image('racecar.png')
enemies_list = ['diablo.png', 'aventador.png', 'nsx.png', 'bike.png', 'Mach6.png', 'speeder.png', 'Stingray.png', 'slr.png' ] # add all other cars
randomCars = [load_image(img) for img in enemies_list]
def things(enemy, thingx, thingy, thingw, thingh, color):
gameDisplay.blit(enemy, [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 crash():
####################################
pygame.mixer.Sound.play(crash_sound)
pygame.mixer.music.stop()
####################################
largeText = pygame.font.SysFont("comicsansms", 115)
TextSurf, TextRect = text_objects("You Crashed", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
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()
click = pygame.mouse.get_pressed()
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:
action()
else:
pygame.draw.rect(gameDisplay, ic, (x, y, w, h))
smallText = pygame.font.SysFont("comicsansms", 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
pygame.mixer.music.unpause()
pause = False
def paused():
############
pygame.mixer.music.pause()
#############
largeText = pygame.font.SysFont("comicsansms", 115)
TextSurf, TextRect = text_objects("Paused", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Continue", 150, 450, 100, 50, green, bright_green, unpause)
button("Quit", 550, 450, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.SysFont("comicsansms", 115)
TextSurf, TextRect = text_objects("Super Racer", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
button("LEGGO!", 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 pause
enemy = random.choice(randomCars)
############
pygame.mixer.music.load('bgmusic.mp3')
pygame.mixer.music.play(-1)
############
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
enemy_speed = 4
thing_width = 55
thing_height = 95
enemy = random.choice(randomCars)
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.blit(backgroundImage, (0, 0))
things(enemy, thing_startx, thing_starty, thing_width, thing_height, block_color)
thing_starty += enemy_speed
car(x, y)
score(dodged)
if x > display_width - car_width or x < 0:
crash()
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0, display_width)
dodged += 1
#enemy_speed += .25
if dodged % 5 == 0:
enemy_speed += (dodged * 1)
if y < thing_starty + thing_height:
#print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width:
#print('x crossover')
crash()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
Here's a minimal example. Just use random.choice to get a new car out of the list as soon as the current car leaves the screen.
import random
import pygame
pygame.init()
CAR_IMG1 = pygame.Surface((30, 50))
CAR_IMG1.fill((10, 150, 200))
CAR_IMG2 = pygame.Surface((30, 50))
CAR_IMG2.fill((210, 150, 0))
CAR_IMG3 = pygame.Surface((30, 50))
CAR_IMG3.fill((10, 250, 0))
CARS = [CAR_IMG1, CAR_IMG2, CAR_IMG3]
def main():
screen = pygame.display.set_mode((640, 480))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
car = random.choice(CARS)
pos_x = random.randrange(screen_rect.width-30)
pos_y = -50
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pos_y += 15
if pos_y > screen_rect.height:
car = random.choice(CARS)
pos_x = random.randrange(screen_rect.width-30)
pos_y = -50
screen.fill((30, 30, 30))
screen.blit(car, (pos_x, pos_y))
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
pygame.init()
main()
pygame.quit()
First initialize your list of enemy car images from which to choose one.
randomCars = [carImg1, carImg2, carImg3, carImg4]
Inside the game_loop() function but outside of the main loop set enemy = random.choice(randomCars)
Inside the main loop of the game_loop() function check to see if the enemy went off the screen. If so, set the enemy variable to a new random car.
if thing_starty > display_height:
# Reset enemy image
enemy = random.choice(randomCars)
# Reset thing co-ordinates
thing_starty = -600
thing_startx = random.randrange(0, display_width)
If the enemy = random.choice(randomCars) line of code doesn't work you could also try indexing the randomCars list with a random integer.
randomCarsIndex = random.randint(0, len(randomCars) - 1)
enemy = randomCars[randomCarsIndex]
Hope this helps!

Pygame.time.set_time, I want to make it occur at specific point

import pygame
import time
import random
pygame.mixer.pre_init(44100, 16, 2, 4096)
pygame.init()
boop_sound = pygame.mixer.Sound("boop.wav")
display_width = 800
display_height = 600
white = (255,255,255)
black = (0,0,0)
blue = (0, 0, 150)
red = (200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0, 255, 0)
clock = pygame.time.Clock()
smallfont = pygame.font.SysFont("Rockwell", 25)
medfont = pygame.font.SysFont("Rockwell", 35)
largefont = pygame.font.SysFont("Rockwell", 50)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("How fast can you tap?")
##icon = pygame.image.load("apple.png")#should be 32x32
##pygame.display.set_icon(icon)
pygame.display.update()
def score(score):
text = smallfont.render("Clicks: "+str(score), True, blue)
gameDisplay.blit(text, [2,0])
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("How many times can you",
blue,
-80,
"large")
message_to_screen("click the button before the time runs out?",
blue,
-10,
"medium")
#message_to_screen("Press C to play, P to pause or Q to quit.",black,180)
button("Play", 150, 500, 100, 50, green, light_green, action="Play")
button("How to play", 325,500,150,50, yellow, light_yellow, action="How to play")
button("Quit", 550,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def game_over():
game_over = True
while game_over:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Out Of Time!",
red,
-100,
"large")
message_to_screen("You clicked: " + str(click) + " times",
blue,
-30)
button("Play Again", 325, 440, 150, 50, green, light_green, action="Play")
button("Quit", 350,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = ((buttonx +((buttonwidth/2)), buttony+(buttonheight/2)))
gameDisplay.blit(textSurf, textRect)
def message_to_screen(msg,color, y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
#screen_text = font.render(msg, True, color)
#gameDisplay.blit(screen_text, [display_width/2, display_height/2])
textRect.center = (display_width/ 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
def game_controls():
gcont = True
while gcont:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("How to play", blue, -100,"large")
message_to_screen("You have to click the button as many times", black, -40)
message_to_screen("as you possible can before the time runs out", black, -20)
button("Play", 150, 500, 100, 50, green, light_green, action="Play")
button("Main", 350,500,100,50, yellow, light_yellow, action="Main")
button("Quit", 550,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def button(text, x, y, width, height, inactive_color, active_color, action = None):
cur = pygame.mouse.get_pos()
clicked = pygame.mouse.get_pressed()
global click
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
if clicked[0] == 1 and action != None:
if action == "Quit":
pygame.quit()
quit()
if action == "How to play":
game_controls()
if action == "Play":
gameLoop()
if action == "Main":
game_intro()
if action == "Click":
click += 1
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
text_to_button(text, black, x, y, width, height)
ENDTIMER = pygame.USEREVENT+1
def gameLoop():
gameExit = False
gameOver = False
FPS = 15
click = 0
global click
timed = pygame.time.set_timer(ENDTIMER, 25000)
while not gameExit:
gameDisplay.fill(white)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.mixer.Sound.play(boop_sound)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action="Click")
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
elif event.type == ENDTIMER:
game_over()
score(click)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
game_intro()
gameLoop()
I am trying to make it so that pygame.time.set_time(), will only run after click > 0. I have tried placing the pygame.time.set_time in an if statement, but that did not work. Any responses are greatly appreciated! When placing the timer start in the MOUSEBUTTONDOWN event it will only start when the mouse is clicked, however everytime i click it resets.
def gameLoop():
ENDTIMER = pygame.USEREVENT+1
gameExit = False
gameOver = False
FPS = 15
click = 0
global click
timer_on =False
while not gameExit:
gameDisplay.fill(white)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.MOUSEBUTTONDOWN:
if not timer_on:
timed = pygame.time.set_timer(ENDTIMER, 25000)
pygame.mixer.Sound.play(boop_sound)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action="Click")
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
elif event.type == ENDTIMER:
gameExit = True
score(click)
pygame.display.update()
clock.tick(FPS)
game_over()
pygame.quit()
quit()

Categories