Pygame button get.pressed() - python

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()

Related

Pygame.mouse.get_pressed() wont detect most of my clicks

So this is my code :
import pygame
import pygame as pg
pygame.init()
displayWidth = 800
displayHeight = 600
### colour codes ###
bgColour = (245, 230, 255)
grey = (150, 150, 150)
darkGrey = (100, 100, 100)
darkBlack = (0,0,0)
clock = pygame.time.Clock()
mouse_clicked = False
display = pygame.display.set_mode((displayWidth, displayHeight))#sets height and width of screen
pygame.display.set_caption('Fashion!')
def screenDisplay(): #subroutine to display screens
display = pygame.display.set_mode((displayWidth, displayHeight))#sets height and width of screen
pygame.display.set_caption('Fashion!') #sets screen title
display.fill(bgColour)
def text_objects(text, font): #font colour
textSurface = font.render(text, True, darkBlack)
return textSurface, textSurface.get_rect()
def textDisplay(s,t,x,y): #subroutine for displaying text on screen
smallText = pygame.font.SysFont("",s) #creates front and font size
textSurf, textRect = text_objects(t, smallText) #inputs text
textRect.center = (x,y) #centres text
display.blit(textSurf, textRect) #displays test
def button(msg,s,x,y,w,h,ic,ac,action=None): #format for button
mouse = pygame.mouse.get_pos() #gets mouse position (tracks cursor)
click = pygame.mouse.get_pressed() #gets status of mouse (tracks click)
print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y: #draws rectangle for button
pygame.draw.rect(display, ac,(x,y,w,h)) #draws rectangle after colour if mouse is on area
if click[0] == 1 and action != None: #performs function on click
action()
else:
pygame.draw.rect(display,ic,(x,y,w,h)) #draws rectangle initial colour if mouse isnt on area
smallText = pygame.font.SysFont("",s) #adds text to button
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
display.blit(textSurf, textRect)
smallText = pygame.font.SysFont("",s) #adds text to button
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
display.blit(textSurf, textRect)
def menuDisplay():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screenDisplay()
button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
button("OUTFIT", 60,200,250,400,100,grey,darkGrey,page)
button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
button("QUIT", 40,300,530,200,50,grey,darkGrey,page)
pygame.display.update()
clock.tick(30)
def page():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screenDisplay()
pygame.display.update()
clock.tick(30)
menuDisplay()
It prints the get pressed but it only returns [0,0,0] until at random times (sometimes straight away sometimes after 10 clicks sometimes after like 50 clicks) it registers [1,0,0]. it has never worked even on other computers.
It didn't work when I didnt have a clock either so like that didnt change anything.
I am so sad and stressed please help πŸ’”πŸ™
The issue is the call to pygame.display.set_mode in screenDisplay. Note, pygame.display.set_mode reinitialize the window and causes losing all mouse event states.
screenDisplay is called in the main application loop. It is a wast of performance and bad style to initialize the display in every frame.
Do not call screenDisplay in the main application loop, just clear the display by display.fill(bgColour) to solve the issue:
def menuDisplay():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# screenDisplay() <-- DELETE
display.fill(bgColour)
button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
button("OUTFIT", 60,200,250,400,100,grey,darkGrey,page)
button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
button("QUIT", 40,300,530,200,50,grey,darkGrey,page)
pygame.display.update()
clock.tick(30)
Do the same in page()
def page():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# screenDisplay() <-- DELETE
display.fill(bgColour)
pygame.display.update()
clock.tick(30)
I changed some things and this works:
import pygame
pygame.init()
displayWidth = 800
displayHeight = 600
### colour codes ###
bgColour = (245, 230, 255)
grey = (150, 150, 150)
darkGrey = (100, 100, 100)
darkBlack = (0,0,0)
smallText = pygame.font.SysFont("",32)
display = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Fashion!')
def text_objects(text, font): #font colour
textSurface = font.render(text, True, darkBlack)
return textSurface, textSurface.get_rect()
def button(msg,s,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(display, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(display, ic,(x,y,w,h))
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
display.blit(textSurf, textRect)
def menuDisplay():
display.fill(bgColour)
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
button("OUTFIT", 60,200,250,400,100,grey,darkGrey,page)
button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
button("QUIT", 40,300,530,200,50,grey,darkGrey,page)
pygame.display.update()
def page():
display.fill(bgColour)
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.draw.rect(display,grey,(50,50,50,50) )
pygame.display.update()
menuDisplay()

pygame button cannot run

(English isn’t my first language, so please excuse any mistakes.)
(Thanks for everyone!!)
When I click the button"1", BE01 will appear but if I don't click, scene01Img will return.
I tried use gameExit = true in def BE01():, but it doesn't work.
pygame.init()
clock = pygame.time.Clock()
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 BE01():
gameDisplay.fill(white)
gameDisplay.blit(BE01Img,(0,0))
button("BACK",350,450,100,50,black,gray,game_intro)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(introImg,(0,0))
button("START",350,450,100,50,black,gray,game_loop)
pygame.display.update()
clock.tick(15)
def quitgame():
pygame.quit()
quit()
def game_loop():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(scene01Img,(0,0))
button("1",200,450,100,50,black,gray,BE01)
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
After click the button"1", BE01 will appear and run the another program, scene01 shouldn't appear.
Every scene should have own loop and when you press button then you should go to new loop.
If you want to change elements in one loop then put old elements in some function (ie. draw_intro) and new elements in other function (ie. draw_other) - at start uses draw_intro in loop and when you press button then replace this function with draw_other
In Python you can assign function name (without ()) to variable
show = print
and later use this name (using ())
show("Hello World")
You can do the same with draw_intro, draw_other.
Inside game loop (before while)you can set
global draw
draw = draw_intro
and use it inside while
draw()
When you press button then it should replace funtion
draw = draw_other
Here full working code - I only removed all blit(image) to run it easily without images.
import pygame
black = (0,0,0)
white = (255,255,255)
gray = (128,128,128)
red = (255,0,0)
pygame.init()
gameDisplay = pygame.display.set_mode( (800,600))
clock = pygame.time.Clock()
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 = smallText.render(msg, True, red)
textRect = textSurf.get_rect()
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def change_draw(new_draw):
global draw
draw = new_draw
def draw_BE01():
gameDisplay.fill(white)
#gameDisplay.blit(BE01Img,(0,0))
button("BACK",350,450,100,50,black,gray,lambda:change_draw(draw_intro))
def draw_intro():
gameDisplay.fill(white)
#gameDisplay.blit(introImg,(0,0))
button("START",350,450,100,50,black,gray,lambda:change_draw(draw_other))
def draw_other():
gameDisplay.fill(white)
#gameDisplay.blit(scene01Img,(0,0))
button("1",200,450,100,50,black,gray,lambda:change_draw(draw_BE01))
def quitgame():
pygame.quit()
quit()
def game_loop():
global draw
draw = draw_intro
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
EDIT:
If you didn't use lamda before then you can do it without lambda but you will need change_draw_to_intro, change_draw_to_other, change_draw_to_BE01 instead of single change_draw
import pygame
black = (0,0,0)
white = (255,255,255)
gray = (128,128,128)
red = (255,0,0)
pygame.init()
gameDisplay = pygame.display.set_mode( (800,600))
clock = pygame.time.Clock()
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 = smallText.render(msg, True, red)
textRect = textSurf.get_rect()
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def change_draw_to_intro():
global draw
draw = draw_intro
def change_draw_to_other():
global draw
draw = draw_other
def change_draw_to_BE01():
global draw
draw = draw_BE01
def draw_BE01():
gameDisplay.fill(white)
#gameDisplay.blit(BE01Img,(0,0))
button("BACK",350,450,100,50,black,gray,change_draw_to_intro)
def draw_intro():
gameDisplay.fill(white)
#gameDisplay.blit(introImg,(0,0))
button("START",350,450,100,50,black,gray,change_draw_to_other)
def draw_other():
gameDisplay.fill(white)
#gameDisplay.blit(scene01Img,(0,0))
button("1",200,450,100,50,black,gray,change_draw_to_BE01)
def quitgame():
pygame.quit()
quit()
def game_loop():
global draw
draw = draw_intro
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()

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.

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()

Quitting pygame without quitting idle

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.

Categories

Resources