Quitting pygame without quitting idle - python

import pygame
import sys
pygame.init()
displayHeight = 600
displayWidth = 800
gameDisplay = pygame.display.set_mode((displayWidth,displayHeight))
pygame.display.set_caption('Pythoral Reef')
green = (0, 100, 0)
white = (255,255,255)
blue = (39, 64, 139)
black = (0,0,0)
clock = pygame.time.Clock()
img = pygame.image.load('coral reef.jpg')
play = False
instructions = False
done = False
def checkClick():
global instructions, play, done
if pygame.mouse.get_pos()[0] > 50 and pygame.mouse.get_pos()[0] < 250 and pygame.mouse.get_pos()[1] > 400 and pygame.mouse.get_pos()[1] < 500:
instructions = True
elif pygame.mouse.get_pos()[0] > 300 and pygame.mouse.get_pos()[0] < 500 and pygame.mouse.get_pos()[1] > 400 and pygame.mouse.get_pos()[1] < 500:
play = True
elif pygame.mouse.get_pos()[0] > 550 and pygame.mouse.get_pos()[0] < 750 and pygame.mouse.get_pos()[1] > 400 and pygame.mouse.get_pos()[1] < 500:
done = True
def evalOption():
global instructions, play, done, gameExit
if instructions == True:
print 'instructions'
instructions = False
elif play == True:
pygame.display.quit()
elif done == True:
pygame.quit()
sys.exit()
def textObjects(text, font, color):
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect()
def messageDisplay(text):
largeText = pygame.font.Font('freesansbold.ttf', 90)
TextSurf, TextRect = textObjects(text, largeText, blue)
TextRect.center = ((displayWidth/2, displayHeight/4))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def optionsDisplay(x, text, size):
smallText = pygame.font.Font('freesansbold.ttf', size)
TextSurf, TextRect = textObjects(text, smallText, white)
TextRect.center = ((x, 450))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def nameDisplay(x, y, text):
smallText = pygame.font.Font('freesansbold.ttf', 35)
TextSurf, TextRect = textObjects(text, smallText, green)
TextRect.center = ((x, y))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def rectangle(color, x, y):
pygame.draw.rect(gameDisplay, color, [x, y, 200, 100])
def menu():
gameExit = False
if gameExit == False:
gameDisplay.blit(img, [0, 0])
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.quit()
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
checkClick()
evalOption()
messageDisplay('PYTHORAL REEF')
rectangle(black, 50, 400)
rectangle(black, 300, 400)
rectangle(black, 550, 400)
optionsDisplay(150, 'INSTRUCTIONS', 22)
optionsDisplay(400, 'PLAY', 35)
optionsDisplay(650, 'QUIT', 35)
nameDisplay(displayWidth/2, 260, 'NICK MONTELEONE')
nameDisplay(displayWidth/2, 225, 'BY')
nameDisplay(displayWidth/2, 295, '2015')
pygame.display.update
menu()
pygame.quit()
This is my code for a menu screen for a text adventure game that I am making. I wanted to use this as the menu screen so when you click play it will exit out of pygame and return to the python shell to run the game. However, when I quit in the function evalOption() by clicking on play, it will print error: font not initialized as if the program is still trying to run. Does anyone know how to fix this so that I can quit out of pygame, but still run a module in python. This program will eventually be imported into my real text adventure module. Here is the link to the coral reef background if needed: https://www.google.com/search?q=coral+reef&espv=2&biw=1440&bih=799&source=lnms&tbm=isch&sa=X&ved=0ahUKEwix_OmD7s_JAhXGWD4KHXW-CrsQ_AUIBigB#imgrc=_dFX3xqK97FGNM%3A
Any help would be much appreciated!

The error is raised because your code tries to draw to the screen after you called pygame.quit().
Instead of
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.quit()
quit()
just use
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
return
to exit your mainloop.

Related

How do you make images in pygame and make them move?

I have been working on a game for a school project and I have these blocks come down the screen and you need to dodge them. I need to turn the blank drawn rectangles coming down the screen into a picture of a car I have.
This is my code so far:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
#^^NEED TO CHANGE TO AN IMAGE CALLED TAXI.PNG CAN SOMEONE PLEASE FIX FOR ME
def man(x,y):
gameDisplay.blit(manImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, 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(gameDisplay, ac,(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():
pygame.mixer.music.play(-1)
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.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
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.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
#gameDisplay.fill(white)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
objects(object_startx, object_starty, object_width, object_height, cyan)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
if x > display_width - man_width or x < 0:
crash()
if object_starty > display_height:
object_starty = 0 - object_height
object_startx = random.randrange(0, display_width)
dodged += 1
object_speed += 0.7
object_width += (dodged * 1)
if y < object_starty+object_height:
print('y crossover')
if x > object_startx and x < object_startx + object_width or x+man_width > object_startx and x + man_width < object_startx+object_width:
print('x crossover')
crash()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
If someone could fix it so it displays taxi.png instead of the rectangles as objects it would be greatly appreciated.
To draw the picture of the car instead of a rectangle, just do the same thing that you are doing with the man.
Under the line that is manImg = pygame.image.load('skater1.png'), put this line: carImg= pygame.image.load('taxi.png') This will load the picture of the car and it will be called carImg.
Now, you need to draw that picture onto the screen. Replace your objects function:
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
with a function to draw a car.
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
Notice how it is very similar to the man function, the only difference is the image that is drawn.
The last thing you need to do is actually call that drawCar function. Replace this line
objects(object_startx, object_starty, object_width, object_height, cyan)
with this one: drawCar(object_startx,object_starty)
I would recommend doing these changes yourself, it will help you learn. But if you're in a hurry, the final code, with all of these changes made, should be:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
carImg= pygame.image.load('taxi.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
def man(x,y):
gameDisplay.blit(manImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, 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(gameDisplay, ac,(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():
pygame.mixer.music.play(-1)
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.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
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.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
#gameDisplay.fill(white)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
drawCar(object_startx,object_starty)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
When you follow tutorials online, don't just copy and paste the code. Make sure that you understand what is happening so that in the future, you can do it yourself.

NameError: name 'textSuface' is not defined

After the player rect has collided with the window width I am now getting an error suggesting that textSurface has not been defined even though it has been defined under def message_display(text):
The help would be greatly appreciated.
Here is my source code:
https://pythonprogramming.net/displaying-text-pygame-screen/?completed=/adding-boundaries-pygame-video-game/
And here is the source video:
https://www.youtube.com/watch?v=dX57H9qecCU&index=5&list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO
Contrasting here is my code:
# This just imports all the Pygame modules
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
# This initates your colors
black = (0,0,0)
# You have 256 color options so you only use 255 because one of those is 0
white = (255,255,255)
red = (255,0,0)
plyrImg_width = 30
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Bit Racer')
clock = pygame.time.Clock()
plyrImg = pygame.image.load('Sprite-01 double size.png')
def player(x,y):
gameDisplay.blit(plyrImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSuface, 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()
time.sleep(2)
game_loop()
def killed():
message_display('You Died')
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
gameExit = False
while not gameExit:
# This handles any and all events in the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print(event)
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.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
# Make sure to write the background before the player
gameDisplay.fill(white)
player(x,y)
if x > display_width - plyrImg_width or x < 0:
killed()
pygame.display.update()
clock.tick(60)
# This is how you un-initiate pygame
# This is what closes the window so always have this
# If you want to end your game loop enter this
game_loop()
pygame.quit()
quit()
Try to spell it correctly. Surface, not suface.

Pygame button get.pressed()

I am just new in pygame, this is my code, pieces. I have main button function, and in gameloop i i successfully create a interactive button, and i don't know exactly, how can i press the button in gameloop ("Start playing") and fill my gameDisplay, for example...white color. Thanks in advance
...........................................................................................................................................................
import pygame,sys
pygame.init()
#############
pygame.mixer.music.load('Invincible.mp3')
pygame.mixer.music.play()
#############
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)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('One Day After')
clock = pygame.time.Clock()
gameIcon = pygame.image.load('gameicon.jpg')
pygame.display.set_icon(gameIcon)
pause = False
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def GameOver():
####################################
pygame.mixer.Sound.play("smb_gameover.wav")
pygame.mixer.music.stop()
####################################
largeText = pygame.font.SysFont("comicsansms",115)
TextSurf, TextRect = text_objects("Game Over", 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:
pygame.mixer.music.stop()
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()
sys.exit()
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():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pilt1 = pygame.image.load('apoc2.jpg').convert()
gameDisplay.blit(pilt1, [0,0])
pygame.display.flip()
button("Start",150,450,100,50,green,bright_green,game_loop)
button("Quit",550,450,100,50,red,bright_red,quitgame)
pygame.display.update()
def game_loop():
global pause
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
quit()
gameDisplay.fill(white)
gameDisplaypic = pygame.image.load('back.jpg').convert()
gameDisplay.blit(gameDisplaypic, [0,0])
tekst = "This game will go as far as you choose!"
meie_font = pygame.font.SysFont("Arial", 36)
teksti_pilt = meie_font.render(tekst, False, (50,50,155))
gameDisplay.blit(teksti_pilt, (100, 250))
tekst2 = "You are the smith of your destiny"
meie_font = pygame.font.SysFont("Arial", 36)
teksti_pilt = meie_font.render(tekst2, False, (50,50,155))
gameDisplay.blit(teksti_pilt, (100, 400))
button("Start playing",300,500,150,50,green,bright_green)
pygame.display.update()
game_intro()
game_loop()
pygame.quit()
quit()
I hope this program will help.
import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400,400))
white=(255,255,255)
blue=(0,0,255)
bright_red = (255,0,0)
red = (200,0,0)
black=(0,0,0)
color=white
def changecolor(newcolor):
global color
color=newcolor
while True:
screen.fill(color)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONUP:
# Whenever somebody clicks on the screen the color
# will change from the initial color to the color
# value you send to the function. Using this you could
# make it specifically for your button. Like calling
# the change color function whenever the button is clicked.
changecolor(blue)
pygame.display.update()
You can use state variables (True/False) to control which element to display and you can change those varibles using button.
In example I have
display_text = True
display_button_1 = True
display_button_2 = False
to control when display text and two buttons.
First button change values and it hides text and first button, and it shows second button.
There is one problem - your button function is ugly and it use get_buttons() so when I hold pressed button and I remove one button and put another in the same place then it automatically click second button. You should use event.type == MOUSEBUTTONUP (as suggest #Hilea) to fix this.
import pygame
import sys # every import in separated line
# --- constants ---
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)
# --- functions ---
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(gameDisplay, ac,(x,y,w,h))
if click[0] == 1 and action != None:
pygame.mixer.music.stop()
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()
sys.exit()
quit()
def hide_text():
global display_text
global display_button_1
global display_button_2
display_text = False
display_button_1 = False
display_button_2 = True
def game_loop():
global display_text
global display_button_1
global display_button_2
gameExit = False
display_text = True
display_button_1 = True
display_button_2 = False
meie_font = pygame.font.SysFont("Arial", 36)
tekst = "This game will go as far as you choose!"
teksti_pilt = meie_font.render(tekst, False, (50,50,155))
tekst2 = "You are the smith of your destiny"
teksti_pilt = meie_font.render(tekst2, False, (50,50,155))
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
gameDisplay.fill(white)
if display_text:
gameDisplay.blit(teksti_pilt, (100, 250))
gameDisplay.blit(teksti_pilt, (100, 400))
if display_button_1:
button("Start playing", 300,500,150,50,green,bright_green, hide_text)
if display_button_2:
button("Exit", 300,100,150,50,green,bright_green, pygame.quit)
pygame.display.update()
# --- main ---
pygame.init()
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('One Day After')
clock = pygame.time.Clock()
pause = False
game_loop()
pygame.quit()

What syntax am I not seeing or entering correctly via python?

I've been learning Python the easy (for me) way: simple video game example tutorials from sentdex on youtube. The concepts which I had not already known are made much clearer in the context of something for which I see value like a simple game. Anyway, I have come to an issue; for some reason, I cannot get a menu page to blit. I originally followed the tutorial very closely, with an eye for punctuation, capitalization and proper indentation as I see that seems to be the n00bs most consistent pitfall. However, the tutorial did not work for that section, and the program goes right into the game loop, even when game over. I have tried other methods prescribed throughout here, google, and youtube, but nothing seems to be working! I get a non-descriptive "syntax error", but as far as I can tell, the vital bits are wired up right. I'm sure I'm just being a blind noob, but some simple analysis would be much appreciated on this code!
NOTE: I know I have some danglers like how I imported Pickle but haven't used it yet, those are all just reminders for the next steps, soon to be fleshed out as soon as this menu problem is resolved.
Running python (with pygame) 2.7, since I cant get pygame to work on python 3.
I have both Eric5 and pycharm, I am running Debian Jessie with a backported Cinnamon (And I believe the kernel to, but I might be wrong)
#!/urs/bin/python2.7
import random
import pygame
import time
##import pickle
pygame.init()
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Zoomin' Zigs")
#Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
#asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
menuactive = True
#FUNCTIONS
##def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
##def leftclick():
##
## if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
## mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades (smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
time.sleep(3)
menuscreen()
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
if x+w > mousecoords[0] > x and y+h > mousecoords[1] >y:
pygame.quit()
quit()
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, blue)
gamedisplay.blit(text, (30,100))
################################MENU###################################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
else:
time.sleep(3)
game_loop()
gamedisplay.blit(menuimage (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP###############################################
def game_loop():
#CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
#SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
while not menuactive:
for event in pygame.event.get():
# GAME QUIT EVENT
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades (smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
#OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
#DODGE COUNT
dodged += 1
#CRASHESloop
if y <= smbar_starty+smbar_height and y >= smbar_starty+smbar_height and x <= smbar_startx+car_width and x >= smbar_startx-car_width:
crash()
menuactive = True
pygame.display.update()
clock.tick(60)
########################################################################################
menuscreen()
game_loop()
pygame.quit()
quit()
Hey I saw your code and did necessary changes And Its Working now next time kindly provide us the whole details.
#!/urs/bin/python2.7
import random
import pygame
import time
# import pickle
menuactive = True
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Zoomin' Zigs")
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
# asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
# FUNCTIONS
# def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
# def leftclick():
##
# if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades(smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
# menuscreen()
# def button(x, y, w, h,):
# mousecoords = pygame.mouse.get_pos()
# if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
# pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x + w > mousecoords[0] > x and y + h > mousecoords[1] > y:
# pygame.quit()
# quit()
global menuactive
menuactive = False
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, blue)
gamedisplay.blit(text, (30, 100))
################################MENU######################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
global menuactive
while menuactive:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
menuactive = False
else:
# time.sleep(3)
game_loop()
gamedisplay.blit(menuimage, (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP#################################
def game_loop():
# CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
# SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
global menuactive
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# pygame.quit()
menuactive = False
# CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades(smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
# OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
# DODGE COUNT
dodged += 1
# CRASHESloop
if y <= smbar_starty + smbar_height and y >= smbar_starty + smbar_height and x <= smbar_startx + car_width and x >= smbar_startx - car_width:
crash()
menuactive = False
pygame.display.update()
clock.tick(60)
##########################################################################
if __name__ == '__main__':
pygame.init()
menuscreen()
# game_loop()
pygame.quit()
quit()

Cannot get button to toggle a change in pygame

I am wondering why it is that my "GO" button will not toggle the
def game_start()
permanently, it toggles it while holding the button, but when you let go of the button its goes back to the main menu?
I am also curious to if there is a way of making the text and buttons vanish when
you press the go button as the game has start?
I am quite new to python so an explanation would be great with any code I have made a mistake on and or need to add/change.
import sys
import pygame
from pygame.locals import *
pygame.init()
size = width, height = 720, 480
speed = [2, 2]
#Colours
black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)
screen = pygame.display.set_mode(size)
#Pictures
road = pygame.image.load(r"C:\Users\John\Desktop\Michael\V'Room External\1.png")
BackgroundPNG = pygame.image.load(r"C:\Users\John\Desktop\Michael\V'Room External\BackgroundPNG.png")
carImg = pygame.image.load(r"C:\Users\John\Desktop\Michael\V'Room External\Sp1.png").convert_alpha()
pygame.display.set_caption("Broom! || BETA::00.0.3")
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(mouse)
print(click)
screen.fill(blue)
screen.blit(BackgroundPNG,(0,0))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("V'Room!", largeText)
TextRect.center = ((width/2),(height/2))
screen.blit(TextSurf, TextRect)
#Button
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
print("GO == 1 ! == None")
x = 350
y = 370
game_start()
else:
pygame.draw.rect(screen, green,(75,400,100,50))
smallText = pygame.font.Font("freesansbold.ttf",20)
TextSurf, TextRect = text_objects("GO", smallText)
TextRect.center = ((75+(100/2)),(400+(50/2)))
screen.blit(TextSurf, TextRect)
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
TextSurf, TextRect = text_objects("Exit", smallText)
TextRect.center = ((550+(100/2)),(400+(50/2)))
screen.blit(TextSurf, TextRect)
pygame.display.flip()
pygame.display.update()
clock.tick(15)
def game_start():
print("Car Loaded Sucessfully")
screen.blit(road, (0,0))
screen.blit(carImg, (350,370))
game_intro()
One of solution is to use game_started variable instead of function game_start() and use it to decide what to draw - title or car and road, GO or STOP button, etc.
I use rectangles in place of bitmaps to make full working example.
import pygame
# --- constants ----
size = width, height = 720, 480
speed = [2, 2]
#Colours
black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)
# --- functions ---
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
largeText = pygame.font.Font('freesansbold.ttf',115)
smallText = pygame.font.Font("freesansbold.ttf",20)
text_vroom, text_vroom_rect = text_objects("V'Room!", largeText)
text_vroom_rect.center = ((width/2),(height/2))
text_go, text_go_rect = text_objects("GO", smallText)
text_go_rect.center = ((75+(100/2)),(400+(50/2)))
text_stop, text_stop_rect = text_objects("STOP", smallText)
text_stop_rect.center = ((75+(100/2)),(400+(50/2)))
text_exit, text_exit_rect = text_objects("Exit", smallText)
text_exit_rect.center = ((550+(100/2)),(400+(50/2)))
game_started = False
intro = True
while intro:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen.fill(blue)
#screen.blit(BackgroundPNG,(0,0))
# road and car - or title
if game_started:
screen.blit(road, (0,0))
screen.blit(carImg, (350,370))
else:
screen.blit(text_vroom, text_vroom_rect)
# Button GO/STOP
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
# toggle True/False
game_started = not game_started
else:
pygame.draw.rect(screen, green,(75,400,100,50))
# draw GO or STOP
if not game_started:
screen.blit(text_go, text_go_rect)
else:
screen.blit(text_stop, text_stop_rect)
# Button EXIT
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
screen.blit(text_exit, text_exit_rect)
pygame.display.flip()
clock.tick(15)
# --- main ---
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Broom! || BETA::00.0.3")
#Pictures
road = pygame.surface.Surface( size )
road.fill(black)
carImg = pygame.surface.Surface( (10,10) )
road.fill(green)
clock = pygame.time.Clock()
game_intro()
EDIT: second solution is to create function (game_running) with own while loop, own buttons, etc.
I had to use pygame.time.wait() because pygame.mouse.get_pressed() is not good function for single click on button. Computer (and while loop) is too fast (for human click) and pygame.mouse.get_pressed() toggle button many times. Better to use pygame.event.get() for single click.
import pygame
# --- constants ----
size = width, height = 720, 480
speed = [2, 2]
#Colours
black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)
# --- functions ---
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
text_vroom, text_vroom_rect = text_objects("V'Room!", largeText)
text_vroom_rect.center = ((width/2),(height/2))
text_go, text_go_rect = text_objects("GO", smallText)
text_go_rect.center = ((75+(100/2)),(400+(50/2)))
text_exit, text_exit_rect = text_objects("Exit", smallText)
text_exit_rect.center = ((550+(100/2)),(400+(50/2)))
running = True
while running:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen.fill(blue)
screen.blit(text_vroom, text_vroom_rect)
# Button GO
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
# wait because `pygame.mouse.get_pressed()` is too fast for human clik
pygame.time.wait(100)
# run game
game_running()
else:
pygame.draw.rect(screen, green,(75,400,100,50))
screen.blit(text_go, text_go_rect)
# Button EXIT
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
screen.blit(text_exit, text_exit_rect)
pygame.display.flip()
clock.tick(15)
def game_running():
text_stop, text_stop_rect = text_objects("STOP", smallText)
text_stop_rect.center = ((75+(100/2)),(400+(50/2)))
text_exit, text_exit_rect = text_objects("Exit", smallText)
text_exit_rect.center = ((550+(100/2)),(400+(50/2)))
running = True
while running:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen.fill(blue)
#screen.blit(BackgroundPNG,(0,0))
# road and car - or title
screen.blit(road, (0,0))
screen.blit(carImg, (350,370))
# Button STOP
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
# return to menu
return
else:
pygame.draw.rect(screen, green,(75,400,100,50))
# draw STOP
screen.blit(text_stop, text_stop_rect)
# Button EXIT
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
screen.blit(text_exit, text_exit_rect)
pygame.display.flip()
clock.tick(15)
# --- main ---
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Broom! || BETA::00.0.3")
# pictures
road = pygame.surface.Surface( size )
road.fill(black)
carImg = pygame.surface.Surface( (10,10) )
road.fill(green)
# fonts
largeText = pygame.font.Font('freesansbold.ttf',115)
smallText = pygame.font.Font("freesansbold.ttf",20)
# others
clock = pygame.time.Clock()
game_intro()

Categories

Resources