Why does my pygame button not always work? - python

My first few buttons work fine but my CSTWindow one only works sometimes. I am reluctant to post as I am self taught and the code wont be flawless, any advice would be much appreciated on how to make this button work all the time and not just every 10ish clicks. Parts of my code is below. Again I am self taught it is not perfect!
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("Ariel", 20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(background, (x,y))
largeText = pygame.font.SysFont("Arial",45)
TextSurf, TextRect = text_objects("Crime Scene and Evidence Examination Game", largeText)
TextRect.center = ((display_width/2),(display_height/1.2))
gameDisplay.blit(TextSurf, TextRect)
button("Scene Selection",150,540,100,50,blue,bright_blue,game_loop)
button("Quit",550,540,100,50,red,bright_red,quitgame)
pygame.display.update()
def CSTWindow():
CSTWindow = True
while CSTWindow:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print("Crime Scene")
def TutorialWindow():
tutorial = True
while tutorial:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen = pygame.display.set_mode((display_width,display_height))
screen.fill(white)
screen.blit(TutorialBG, (x,y))
button("Crime Scene",150,540,100,50,blue,bright_blue,CSTWindow)
pygame.display.update()
def game_loop():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(blue)
button("Tutorial",(370), (100),100, 50, lightBlue, bright_blue,TutorialWindow)
pygame.display.update()
clock.tick(60)

Maybe it will work better with an image, this is what i wrote:
def button(x, y, w, h, inactive, active, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
gameDisplay.blit(active, (x, y))
if click[0] == 1 and action is not None:
action()
else:
gameDisplay.blit(inactive, (x, y))
Btw, I watched the same tutorial as you but I used images instead.

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

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