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

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

Related

How Could I Make A Function For The Start Game Button To Disable The Start Screen And Load My Main Game?

so I have a game intro here and I was wonder how can I make it so when my ***mouse clicks on the start game button to disable the the game_intro? its currently not doing anything and vid
like how could I make a function for start button when I click it, it should remove the game_intro or disable it and load my main game
this is my game intro right now
#---------------------------------------------------
def button(msg,x,y,w,h,ic,ac):
mouse = pygame.mouse.get_pos()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
else:
pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
if clikc[0] == 1 and action != None:
action()
else:
pygame.draw.rect(window,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 text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
red = (200,0,0)
green = (0,200,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
largeText = pygame.font.Font('BLOODY.ttf',115)
TextSurf, TextRect = text_objects("Stolen Hearts!", largeText)
TextRect.center = ((800/2), (800/2))
window.blit(TextSurf, TextRect)
# make the square brighter if collideded with the buttons
mouse = pygame.mouse.get_pos()
if 150+120 > mouse[0] > 150 and 450+50 > mouse[1] > 450:
pygame.draw.rect(window, bright_green,(150,450,120,50))
else:
pygame.draw.rect(window, green,(150,450,120,50))
if 550+110 > mouse[0] > 550 and 450+50 > mouse[1] > 450:
pygame.draw.rect(window, bright_red,(550,450,110,50))
else:
pygame.draw.rect(window, red,(550,450,110,50))
# ---------------------------------------------------------------------
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects("Start Game", smallText)
textRect.center = ( (150+(120/2)), (450+(50/2)) )
window.blit(textSurf, textRect)
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects("Quit Game", smallText)
textRect.center = ( (150+(910/2)), (450+(50/2)) )
window.blit(textSurf, textRect)
pygame.display.update()
clock.tick(15)
#----------------------------------------------------------
my full code script
You have to remove mistakes in button() and you have to use button() in game_intro()
There is too many to explain so I only show minimal working code.
Buttons works but they still are not ideal. It will have problem if new scene will have buttons in the same place - it will click it automatically - but it would need totally different code. More on GitHub
import pygame
# --- constants --- (UPPER_CASE_NAMES)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
BRIGHT_RED = (255, 0, 0)
BRIGHT_GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
# --- all classes --- (CamelCaseNames)
class Player:
pass
# ... code ...
class Platform:
pass
# ... code ...
# etc.
# --- all functions --- (lower_case_names)
def text_objects(text, font):
image = font.render(text, True, BLACK)
rect = image.get_rect()
return image, rect
def button(window, 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(window, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(window, ic,(x,y,w,h))
image = small_font.render(msg, True, BLACK)
rect = image.get_rect()
rect.center = (x+(w/2), y+(h/2))
window.blit(image, rect)
def game_intro():
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
image, rect = text_objects("Stolen Hearts!", large_font)
rect.center = (400, 400)
window.blit(image, rect)
button(window, "Start Game", 150, 450, 120, 50, GREEN, BRIGHT_GREEN, main_game)
button(window, "Quit Game", 350, 450, 120, 50, RED, BRIGHT_RED, quit_game)
pygame.display.update()
clock.tick(15)
def main_game():
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
image, rect = text_objects("Main Game", large_font)
rect.center = (400, 400)
window.blit(image, rect)
button(window, "Intro", 550, 450, 120, 50, GREEN, BRIGHT_GREEN, game_intro)
button(window, "Quit Game", 350, 450, 120, 50, RED, BRIGHT_RED, quit_game)
pygame.display.update()
clock.tick(15)
def quit_game():
print("You quit game")
pygame.quit()
quit()
# --- main ---
pygame.init()
window = pygame.display.set_mode((800, 800))
# it has to be after `pygame.init()`
#small_font = pygame.font.Font("freesansbold.ttf", 20)
#large_font = pygame.font.Font('BLOODY.ttf', 115)
small_font = pygame.font.Font(None, 20)
large_font = pygame.font.Font(None, 115)
clock = pygame.time.Clock()
game_intro()
BTW: I also organize code in different way
all constants values in one place directly after imports and they use UPPER_CASE_NAMES (PEP8) and
all classes in one place - directly after constants and before pygame.init() - and they use CamelCaseNames (PEP8)
all functions in one place - after classes and before pygame.init() - and they uselower_case_names (PEP8)
See: PEP 8 -- Style Guide for Python Code

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 i program a button in python (without Tkinter)?

I've recently started learning Python3 and I was trying to make a game with Python3 by importing pygame. I tried to make a menu and I am having some struggles with it. I just tried to make it seem like its a button by letting the rectangle change color when you hover over it but its not working. I already tried some things but its not working. Anyhow here is the full code: hastebin link.
This is the part where I tried to make a button:
def game_intro():
intro = True
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf', 90)
TextSurf, TextRect = text_objects("Run Abush Run!", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
mouse = pygame.mouse.get_pos()
if 150+100 > mouse[0] > 150 and 430+50 > mouse[1] > 430:
pygame.draw.rect(gameDisplay, bright_green, (150,430,100,50))
else:
pygame.draw.rect(gameDisplay, green, (150, 430, 100, 50))
smallText = pygame.font.Font('freesansbold.ttf' ,20)
textSurf, textRect = text_objects("START!", smallText)
textRect.center = ( (150+(100/2)), (450+(430/2)) )
gameDisplay.blit(textSurf, textRect)
pygame.draw.rect(gameDisplay, red, (550, 430, 100, 50))
pygame.display.update()
clock.tick(15)
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
The problem here is that you're only doing your mouseover test once, at the start of the function. If the mouse later moves into your rectangle, it won't matter, because you never do the test again.
What you want to do is move it into the event loop. One tricky bit in PyGame event loops is which code you want to run once per event (the inner for event in… loop), and which you only want to run once per batch (the outer while intro loop). Here, I'm going to assume you want to do this once per event. So:
def game_intro():
intro = True
# ... other setup stuff
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
mouse = pygame.mouse.get_pos()
if 150+100 > mouse[0] > 150 and 430+50 > mouse[1] > 430:
pygame.draw.rect(gameDisplay, bright_green, (150,430,100,50))
else:
pygame.draw.rect(gameDisplay, green, (150, 430, 100, 50))
It looks like some of the other stuff you do only once also belongs inside the loop, so your game may still have some problems. But this should get you past the hurdle you're stuck on, and show you how to get started on those other problems.
Here is a button that should suit your needs:
class Button(object):
global screen_width,screen_height,screen
def __init__(self,x,y,width,height,text_color,background_color,text):
self.rect=pygame.Rect(x,y,width,height)
self.x=x
self.y=y
self.width=width
self.height=height
self.text=text
self.text_color=text_color
self.background_color=background_color
def check(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
def draw(self):
pygame.draw.rect(screen, self.background_color,(self.rect),0)
drawTextcenter(self.text,font,screen,self.x+self.width/2,self.y+self.height/2,self.text_color)
pygame.draw.rect(screen,self.text_color,self.rect,3)
Use the draw function to draw your button, and the check function to see if the button is being pressed.
Implemented into a main loop:
button=Button(x,y,width,height,text_color,background_color,text)
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif event.type==pygame.MOUSEBUTTONDOWN:
if button.check():
#what to do when button is pressed
#fill screen with background
screen.fill(background)
button.draw()
pygame.display.flip()
clock.tick(fps)
This is what i did and it works now:
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.Font('freesansbold.ttf', 90)
TextSurf, TextRect = text_objects("Run Abush Run!", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
mouse = pygame.mouse.get_pos()
# print(mouse)
if 150 + 100 > mouse[0] > 150 and 450 + 50 > mouse[1] > 450:
pygame.draw.rect(gameDisplay, bright_green, (150, 450, 100, 50))
else:
pygame.draw.rect(gameDisplay, green, (150, 450, 100, 50))
pygame.draw.rect(gameDisplay, red, (550, 450, 100, 50))
pygame.display.update()
clock.tick(15)
Thank you for the help #abarnert

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

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