I have a menu with 3 buttons. I want one of the buttons to connect to my game page which I have but am not sure how to make this happen. So I want the "game" button to lead to the screen which has the actual game (like the screen where you play the game). i am trying to figure out how to connect a page to a button in this pygame. Thanks
# import images
background = pygame.image.load('background.png')
backgroundX = 0
backgroundX2 = background.get_width()
homeScreen = pygame.image.load('home_screen.png')
obstacle = pygame.image.load('obstacle.png')
obstacleX = 0
obstacleX2 = obstacle.get_width()
instructions = pygame.image.load('instructions.png')
# frame rate
clock = pygame.time.Clock()
# use procedure for game window rather than using it within loop
def redrawGameWindow():
# background images for right to left moving screen
screen.blit(background, (backgroundX, 0))
screen.blit(background, (backgroundX2, 0))
man.draw(screen)
screen.blit(obstacle, (obstacleX, 400))
screen.blit(obstacle, (obstacleX2, 400))
pygame.display.update()
# create class for character (object)
class player(object):
def __init__(self, x, y, width, height): # initialize attributes
self.x = x
self.y = y
self.width = width
self.height = height
self.left = True
self.right = True
self.isJump = False
self.stepCount = 0
self.jumpCount = 10
self.standing = True
def draw(self, screen):
if self.stepCount + 1 >= 27: # 9 sprites, with 3 frames - above 27 goes out of range
self.stepCount = 0
if not self.standing:
if self.left:
screen.blit(leftDirection[self.stepCount // 5], (self.x, self.y), )
self.stepCount += 1
elif self.right:
screen.blit(rightDirection[self.stepCount // 5], (self.x, self.y), )
self.stepCount += 1
else:
if self.right:
screen.blit(rightDirection[0], (self.x, self.y)) # using index, include right faced photo
else:
screen.blit(leftDirection[0], (self.x, self.y))
class enlargement(object):
def __init__(self, x, y, radius, color, facing):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.facing = facing
def draw(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius, 1)
man = player(200, 313, 64, 64)
font = pygame.font.Font(None, 75) # font for home screen
instructionsFont = pygame.font.Font(None, 30) # font for instructions page
# HOME SCREEN
WHITE = (255,255,255)
BLACK = ( 0, 0, 0)
RED = (255, 0, 0)
GREEN = ( 0,255, 0)
BLUE = ( 0, 0,255)
YELLOW = (255,255, 0)
def button_create(text, rect, inactive_color, active_color, action):
font = pygame.font.Font(None, 40)
button_rect = pygame.Rect(rect)
text = font.render(text, True, BLACK)
text_rect = text.get_rect(center=button_rect.center)
return [text, text_rect, button_rect, inactive_color, active_color, action, False]
def button_check(info, event):
text, text_rect, rect, inactive_color, active_color, action, hover = info
if event.type == pygame.MOUSEMOTION:
# hover = True/False
info[-1] = rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN:
if hover and action:
action()
def button_draw(screen, info):
text, text_rect, rect, inactive_color, active_color, action, hover = info
if hover:
color = active_color
else:
color = inactive_color
pygame.draw.rect(screen, color, rect)
screen.blit(text, text_rect)
# ---
def on_click_button_1():
global stage
stage = 'game'
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# --- classes --- (CamelCaseNanes)
# empty
# --- functions --- (lower_case_names_
def button_create(text, rect, inactive_color, active_color, action):
font = pygame.font.Font(None, 40)
button_rect = pygame.Rect(rect)
text = font.render(text, True, BLACK)
text_rect = text.get_rect(center=button_rect.center)
return [text, text_rect, button_rect, inactive_color, active_color, action, False]
def button_check(info, event):
text, text_rect, rect, inactive_color, active_color, action, hover = info
if event.type == pygame.MOUSEMOTION:
# hover = True/False
info[-1] = rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN:
if hover and action:
action()
def button_draw(screen, info):
text, text_rect, rect, inactive_color, active_color, action, hover = info
if hover:
color = active_color
else:
color = inactive_color
pygame.draw.rect(screen, color, rect)
screen.blit(text, text_rect)
# ---
def on_click_button_1():
global stage
stage = 'game'
print('You clicked Button 1')
def on_click_button_2():
global stage
stage = 'options'
print('You clicked Button 2')
def on_click_button_3():
global stage
global running
stage = 'exit'
running = False
print('You clicked Button 3')
def on_click_button_return():
global stage
stage = 'menu'
print('You clicked Button Return')
# --- main --- (lower_case_names)
# - init -
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen_rect = screen.get_rect()
# - objects -
stage = 'menu'
button_1 = button_create("GAME", (300, 100, 200, 75), RED, GREEN, on_click_button_1)
button_2 = button_create("OPTIONS", (300, 200, 200, 75), RED, GREEN, on_click_button_2)
button_3 = button_create("EXIT", (300, 300, 200, 75), RED, GREEN, on_click_button_3)
button_return = button_create("RETURN", (300, 400, 200, 75), RED, GREEN, on_click_button_return)
# - mainloop -
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if stage == 'menu':
button_check(button_1, event)
button_check(button_2, event)
button_check(button_3, event)
elif stage == 'game':
button_check(button_return, event)
elif stage == 'options':
button_check(button_return, event)
# elif stage == 'exit':
# pass
# - draws -
screen.fill(BLACK)
if stage == 'menu':
button_draw(screen, button_1)
button_draw(screen, button_2)
button_draw(screen, button_3)
elif stage == 'game':
button_draw(screen, button_return)
elif stage == 'options':
button_draw(screen, button_return)
# elif stage == 'exit':
# pass
pygame.display.update()
print('You clicked Button 1')
def on_click_button_2():
global stage
stage = 'options'
print('You clicked Button 2')
def on_click_button_3():
global stage
global running
stage = 'exit'
running = False
print('You clicked Button 3')
def on_click_button_return():
global stage
stage = 'menu'
print('You clicked Button Return')
# --- main --- (lower_case_names)
# - init -
pygame.init()
screen = pygame.display.set_mode((800,600))
screen_rect = screen.get_rect()
# - objects -
stage = 'menu'
button_1 = button_create("GAME", (300, 100, 200, 75), RED, GREEN, on_click_button_1)
button_2 = button_create("OPTIONS", (300, 200, 200, 75), RED, GREEN, on_click_button_2)
button_3 = button_create("EXIT", (300, 300, 200, 75), RED, GREEN, on_click_button_3)
button_return = button_create("RETURN", (300, 400, 200, 75), RED, GREEN, on_click_button_return)
# - mainloop -
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if stage == 'menu':
button_check(button_1, event)
button_check(button_2, event)
button_check(button_3, event)
elif stage == 'game':
button_check(button_return, event)
elif stage == 'options':
button_check(button_return, event)
#elif stage == 'exit':
# pass
# - draws -
screen.fill(BLACK)
if stage == 'menu':
button_draw(screen, button_1)
button_draw(screen, button_2)
button_draw(screen, button_3)
elif stage == 'game':
button_draw(screen, button_return)
elif stage == 'options':
button_draw(screen, button_return)
#elif stage == 'exit':
# pass
pygame.display.update()
# - end -
pygame.quit()
run = True
while run:
clock.tick(30)
pygame.display.update()
redrawGameWindow() # call procedure
backgroundX -= 1.4 # Move both background images back
backgroundX2 -= 1.4
obstacleX -= 1.4
obstacleX2 -= 1.4
if backgroundX < background.get_width() * -1: # If our background is at the -width then reset its position
backgroundX = background.get_width()
if backgroundX2 < background.get_width() * -1:
backgroundX2 = background.get_width()
if obstacleX < obstacle.get_width() * -10:
obstacleX = obstacle.get_width
if obstacleX2 < obstacle.get_width() * -10:
obstacleX2 = obstacle.get_width()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
quit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
man.left = True
man.right = False
man.standing = False # false, because man is walking
# verify that character is within window parameters
elif keys[pygame.K_RIGHT]:
man.right = True
man.left = False
man.standing = False # false, because man is walking
else:
man.standing = True
man.stepCount = 0
if not man.isJump:
if keys[pygame.K_SPACE]:
man.isJump = True # when jumping, man shouldn't move directly left or right
man.right = False
man.left = False
man.stepCount = 0
else:
if man.jumpCount >= -10:
neg = 1
if man.jumpCount < 0:
neg = -1
man.y -= (man.jumpCount ** 2) * .5 * neg # to jump use parabola
man.jumpCount -= 1
else:
man.isJump = False
man.jumpCount = 10
pygame.quit()
Every page or stage has similar elements - create items, draw, update, handle events, mainloop - which you can put in class to separate one stage from another.
At start create MenuStage and run its mainloop(). When you press button in MenuStage then create GameStage and runs its mainloop(). To go back from GameStage to MenuStage use button (or other event) to set self.running = False to stop GameStage.mainloop and go back to MenuStage.mainloop
This example doesn't use your code but it shows how Stages would work.
import pygame
# === CONSTANTS === (UPPER_CASE_NAMES)
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# === CLASSES === (CamelCaseNames)
class Player():
def __init__(self, screen, config):
self.screen = screen
self.screen_rect = screen.get_rect()
self.config = config
self.direction = 'right'
self.rect = pygame.Rect(100, 100, 20, 20)
self.speed = 10
def draw(self, surface):
pygame.draw.rect(surface, RED, self.rect)
def update(self):
self.rect.x += self.speed
if self.direction == 'right':
if self.rect.right > self.screen_rect.right:
self.rect.right = self.screen_rect.right
self.speed = -self.speed
self.direction = 'left'
elif self.direction == 'left':
if self.rect.left < self.screen_rect.left:
self.rect.left = self.screen_rect.left
self.speed = -self.speed
self.direction = 'right'
class Stage():
# --- (global) variables ---
# empty
# --- init ---
def __init__(self, screen, config):
self.screen = screen
self.config = config
self.screen_rect = screen.get_rect()
self.clock = pygame.time.Clock()
self.is_running = False
self.widgets = []
self.create_objects()
def quit(self):
pass
# --- objects ---
def create_objects(self):
'''
self.player = Player()
'''
'''
btn = Button(...)
self.widgets.append(btn)
'''
# --- functions ---
def handle_event(self, event):
'''
self.player.handle_event(event)
'''
'''
for widget in self.widgets:
widget.handle_event(event)
'''
def update(self, ):
'''
self.player.update()
'''
'''
for widget in self.widgets:
widget.update()
'''
def draw(self, surface):
#surface.fill(BLACK)
'''
self.player.draw(surface)
'''
'''
for widget in self.widgets:
widget.draw(surface)
'''
#pygame.display.update()
def exit(self):
self.is_running = False
# --- mainloop --- (don't change it)
def mainloop(self):
self.is_running = True
while self.is_running:
# --- events ---
for event in pygame.event.get():
# --- global events ---
if event.type == pygame.QUIT:
self.is_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.is_running = False
# --- objects events ---
self.handle_event(event)
# --- updates ---
self.update()
# --- draws ---
self.screen.fill(BLACK)
self.draw(self.screen)
pygame.display.update()
# --- FPS ---
self.clock.tick(25)
# --- the end ---
self.quit()
class IntroStage(Stage):
def create_objects(self):
self.font = pygame.font.Font(None, 40)
self.text = self.font.render("INTRO STAGE (Press ESC or Click Mouse)", True, BLACK)
self.text_rect = self.text.get_rect(center=self.screen_rect.center)
def draw(self, surface):
surface.fill(GREEN)
surface.blit(self.text, self.text_rect)
def handle_event(self, event):
# close on mouse click
if event.type == pygame.MOUSEBUTTONDOWN:
#self.is_running = False
self.exit()
class MenuStage(Stage):
def create_objects(self):
self.font = pygame.font.Font(None, 40)
self.text = self.font.render("MENU STAGE (Press ESC)", True, BLACK)
self.text_rect = self.text.get_rect(center=self.screen_rect.center)
self.text_rect.top = 10
self.stage_game = GameStage(self.screen, self.config)
self.stage_options = OptionsStage(self.screen, self.config)
self.button1 = button_create("GAME", (300, 200, 200, 50), GREEN, BLUE, self.stage_game.mainloop)
self.button2 = button_create("OPTIONS", (300, 300, 200, 50), GREEN, BLUE, self.stage_options.mainloop)
self.button3 = button_create("EXIT", (300, 400, 200, 50), GREEN, BLUE, self.exit)
def draw(self, surface):
surface.fill(RED)
surface.blit(self.text, self.text_rect)
button_draw(surface, self.button1)
button_draw(surface, self.button2)
button_draw(surface, self.button3)
def handle_event(self, event):
button_check(self.button1, event)
button_check(self.button2, event)
button_check(self.button3, event)
class OptionsStage(Stage):
def create_objects(self):
self.font = pygame.font.Font(None, 40)
self.text = self.font.render("OPTIONS STAGE (Press ESC)", True, BLACK)
self.text_rect = self.text.get_rect(center=self.screen_rect.center)
def draw(self, surface):
surface.fill(RED)
surface.blit(self.text, self.text_rect)
class ExitStage(Stage):
def create_objects(self):
self.font = pygame.font.Font(None, 40)
self.text = self.font.render("EXIT STAGE (Press ESC or Click Mouse)", True, BLACK)
self.text_rect = self.text.get_rect(center=self.screen_rect.center)
def draw(self, surface):
surface.fill(GREEN)
surface.blit(self.text, self.text_rect)
def handle_event(self, event):
# close on mouse click
if event.type == pygame.MOUSEBUTTONDOWN:
#self.is_running = False
self.exit()
class GameStage(Stage):
def create_objects(self):
self.font = pygame.font.Font(None, 40)
self.text = self.font.render("GAME STAGE (Press ESC)", True, BLACK)
self.text_rect = self.text.get_rect(center=self.screen_rect.center)
self.player = Player(self.screen, self.config)
def draw(self, surface):
surface.fill(BLUE)
surface.blit(self.text, self.text_rect)
self.player.draw(surface)
def update(self):
self.player.update()
# === FUNCTIONS === (lower_case_names)
# TODO: create class Button()
def button_create(text, rect, inactive_color, active_color, action):
font = pygame.font.Font(None, 40)
button_rect = pygame.Rect(rect)
text = font.render(text, True, BLACK)
text_rect = text.get_rect(center=button_rect.center)
return [text, text_rect, button_rect, inactive_color, active_color, action, False]
def button_check(info, event):
text, text_rect, rect, inactive_color, active_color, action, hover = info
if event.type == pygame.MOUSEMOTION:
# hover = True/False
info[-1] = rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN:
if hover and action:
action()
def button_draw(screen, info):
text, text_rect, rect, inactive_color, active_color, action, hover = info
if hover:
color = active_color
else:
color = inactive_color
pygame.draw.rect(screen, color, rect)
screen.blit(text, text_rect)
# === MAIN === (lower_case_names)
class App():
# --- init ---
def __init__(self):
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
config = {}
stage = IntroStage(screen, config)
stage.mainloop()
stage = MenuStage(screen, config)
stage.mainloop()
stage = ExitStage(screen, config)
stage.mainloop()
pygame.quit()
#def run(self):
#----------------------------------------------------------------------
if __name__ == '__main__':
App() #.run()
EDIT: Image which I made long time ago:
Related
I am making a game in pygame that requires me to have a drop down box and radio buttons for selection of an option. Any hints as to how to go about this would be appreciated.
Regards,
I recommend implementing a class for graphical UI elements. The class has a constructor (__init__) that defines all required attributes and all required states. A Draw method that draws the entire UI element depending on its current state. The class should have an update method that receives the events, changes the state of the UI:
class OptionBox():
def __init__(self, x, y, w, h, color, ...):
...
def draw(self, surf):
...
def update(self, event_list):
...
See also UI elements and see some examples:
Dropdown menu
Radio Button
Option Box:
import pygame
class OptionBox():
def __init__(self, x, y, w, h, color, highlight_color, font, option_list, selected = 0):
self.color = color
self.highlight_color = highlight_color
self.rect = pygame.Rect(x, y, w, h)
self.font = font
self.option_list = option_list
self.selected = selected
self.draw_menu = False
self.menu_active = False
self.active_option = -1
def draw(self, surf):
pygame.draw.rect(surf, self.highlight_color if self.menu_active else self.color, self.rect)
pygame.draw.rect(surf, (0, 0, 0), self.rect, 2)
msg = self.font.render(self.option_list[self.selected], 1, (0, 0, 0))
surf.blit(msg, msg.get_rect(center = self.rect.center))
if self.draw_menu:
for i, text in enumerate(self.option_list):
rect = self.rect.copy()
rect.y += (i+1) * self.rect.height
pygame.draw.rect(surf, self.highlight_color if i == self.active_option else self.color, rect)
msg = self.font.render(text, 1, (0, 0, 0))
surf.blit(msg, msg.get_rect(center = rect.center))
outer_rect = (self.rect.x, self.rect.y + self.rect.height, self.rect.width, self.rect.height * len(self.option_list))
pygame.draw.rect(surf, (0, 0, 0), outer_rect, 2)
def update(self, event_list):
mpos = pygame.mouse.get_pos()
self.menu_active = self.rect.collidepoint(mpos)
self.active_option = -1
for i in range(len(self.option_list)):
rect = self.rect.copy()
rect.y += (i+1) * self.rect.height
if rect.collidepoint(mpos):
self.active_option = i
break
if not self.menu_active and self.active_option == -1:
self.draw_menu = False
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.menu_active:
self.draw_menu = not self.draw_menu
elif self.draw_menu and self.active_option >= 0:
self.selected = self.active_option
self.draw_menu = False
return self.active_option
return -1
pygame.init()
clock = pygame.time.Clock()
window = pygame.display.set_mode((640, 480))
list1 = OptionBox(
40, 40, 160, 40, (150, 150, 150), (100, 200, 255), pygame.font.SysFont(None, 30),
["option 1", "2nd option", "another option"])
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
selected_option = list1.update(event_list)
if selected_option >= 0:
print(selected_option)
window.fill((255, 255, 255))
list1.draw(window)
pygame.display.flip()
pygame.quit()
exit()
So so far here's my code:
import pygame as pg
pg.init()
clock = pg.time.Clock()
# Generating screen
w_scr = 640
h_scr = 480
size_scr = (w_scr, h_scr)
screen = pg.display.set_mode(size_scr)
# Define color
COLOR_INACTIVE = (100, 80, 255)
COLOR_ACTIVE = (100, 200, 255)
COLOR_LIST_INACTIVE = (255, 100, 100)
COLOR_LIST_ACTIVE = (255, 150, 150)
class DropDown():
# Test List
option_list = ["Calibration", "Test"]
def __init__(self, color_menu, color_option, x, y, w, h):
self.color_menu = color_menu
self.color_option = color_option
self.x = x
self.y = y
self.w = w
self.h = h
# Draw the initial button 'select mode'
def draw_main(self, win, text=''):
pg.draw.rect(win, self.color_menu, (self.x, self.y, self.w, self.h), 0)
if text != '':
font = pg.font.SysFont(None, 30)
msg = font.render(text, 1, (0, 0, 0))
screen.blit(msg, (self.x + (self.w / 2 - msg.get_width() / 2), self.y + (self.h / 2 - msg.get_height() / 2)))
# Draw list of option 'calibration' and 'test'
def draw_opt(self, win, text=[]):
opt_list =[]
if draw:
for i, el in enumerate(text):
opt_list.append(pg.draw.rect(win, self.color_option, (self.x, self.y + (i+1)*self.h, self.w, self.h), 0))
# write each option
font = pg.font.SysFont(None, 30)
msg = font.render(text[i], 1, (0, 0, 0))
screen.blit(msg, (self.x + (self.w / 2 - msg.get_width() / 2),
self.y + (i+1)*self.h + (self.h / 2 - msg.get_height() / 2)))
# Detect when the mouse is within the 'select mode' box
def choose_main(self, pos):
if self.x < pos[0] < self.x + self.w and self.y < pos[1] < self.y + self.h:
return True
else:
return False
# Detect when the mouse is within the option list
def choose_opt(self, pos):
if self.x < pos[0] < self.x + self.w and 2*self.y < pos[1] < 2*self.y + self.h:
return True
else:
return False
That's the definition of necessary class and attributes. Here is how I run it:
# Draw flag initial value
draw = False
# Declare element
list1 = DropDown(COLOR_INACTIVE, COLOR_LIST_INACTIVE, 50, 50, 200, 50)
# Run program
menu = True
while menu:
screen.fill((255, 255, 255))
for event in pg.event.get():
pos = pg.mouse.get_pos()
if event.type == pg.QUIT:
pg.quit()
quit()
# For the menu
if event.type == pg.MOUSEMOTION:
if list1.choose_main(pos):
list1.color_menu = COLOR_ACTIVE
else:
list1.color_menu = COLOR_INACTIVE
# For the option
if event.type == pg.MOUSEMOTION:
if list1.choose_opt(pos):
list1.color_option = COLOR_LIST_ACTIVE
else:
list1.color_option = COLOR_LIST_INACTIVE
if event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1 and list1.choose_main(pos):
if draw == False:
draw = True
elif draw == True:
draw = False
list1.draw_main(screen, "Select Mode")
list1.draw_opt(screen, ["Calibration", "Test"])
pg.display.flip()
clock.tick(30)
pg.quit()
My Problem:
I don't know how to select the list when they are available, in other words,
I don't know how to develop further from this step
How I think it should work?
while (the option list available = True) -> choose one of them -> select it
But I failed to implement the while loop, it just runs in infinite loop, I'm stuck. So please any help is appreciated :)
Note:
I know there are GUI module available for main menu, I've also tried them, but couldn't integrate them correctly due to little to none documentation of the module, I think the closest I can get is by using thorpy, but again there's an error I couldn't solve. So I decided to make my own.
If someone who already created dropdown list module successfully would like to share theirs, I would be so thankful.
The menu title, the options and the status of the menus should be attributes of the DropDownclass:
class DropDown():
def __init__(self, color_menu, color_option, x, y, w, h, font, main, options):
self.color_menu = color_menu
self.color_option = color_option
self.rect = pg.Rect(x, y, w, h)
self.font = font
self.main = main
self.options = options
self.draw_menu = False
self.menu_active = False
self.active_option = -1
# [...]
list1 = DropDown(
[COLOR_INACTIVE, COLOR_ACTIVE],
[COLOR_LIST_INACTIVE, COLOR_LIST_ACTIVE],
50, 50, 200, 50,
pg.font.SysFont(None, 30),
"Select Mode", ["Calibration", "Test"])
The class should have a draw method that draws the entire menu:
class DropDown():
# [...]
def draw(self, surf):
pg.draw.rect(surf, self.color_menu[self.menu_active], self.rect, 0)
msg = self.font.render(self.main, 1, (0, 0, 0))
surf.blit(msg, msg.get_rect(center = self.rect.center))
if self.draw_menu:
for i, text in enumerate(self.options):
rect = self.rect.copy()
rect.y += (i+1) * self.rect.height
pg.draw.rect(surf, self.color_option[1 if i == self.active_option else 0], rect, 0)
msg = self.font.render(text, 1, (0, 0, 0))
surf.blit(msg, msg.get_rect(center = rect.center))
The class should have an update method that receives the events, changes the status of the menus, and returns the index of the selected option:
class DropDown():
# [...]
def update(self, event_list):
mpos = pg.mouse.get_pos()
self.menu_active = self.rect.collidepoint(mpos)
self.active_option = -1
for i in range(len(self.options)):
rect = self.rect.copy()
rect.y += (i+1) * self.rect.height
if rect.collidepoint(mpos):
self.active_option = i
break
if not self.menu_active and self.active_option == -1:
self.draw_menu = False
for event in event_list:
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
if self.menu_active:
self.draw_menu = not self.draw_menu
elif self.draw_menu and self.active_option >= 0:
self.draw_menu = False
return self.active_option
return -1
while run:
event_list = pg.event.get()
for event in event_list:
# [...]
selected_option = list1.update(event_list)
if selected_option >= 0:
# [...]
# [...]
Complete example:
import pygame as pg
class DropDown():
def __init__(self, color_menu, color_option, x, y, w, h, font, main, options):
self.color_menu = color_menu
self.color_option = color_option
self.rect = pg.Rect(x, y, w, h)
self.font = font
self.main = main
self.options = options
self.draw_menu = False
self.menu_active = False
self.active_option = -1
def draw(self, surf):
pg.draw.rect(surf, self.color_menu[self.menu_active], self.rect, 0)
msg = self.font.render(self.main, 1, (0, 0, 0))
surf.blit(msg, msg.get_rect(center = self.rect.center))
if self.draw_menu:
for i, text in enumerate(self.options):
rect = self.rect.copy()
rect.y += (i+1) * self.rect.height
pg.draw.rect(surf, self.color_option[1 if i == self.active_option else 0], rect, 0)
msg = self.font.render(text, 1, (0, 0, 0))
surf.blit(msg, msg.get_rect(center = rect.center))
def update(self, event_list):
mpos = pg.mouse.get_pos()
self.menu_active = self.rect.collidepoint(mpos)
self.active_option = -1
for i in range(len(self.options)):
rect = self.rect.copy()
rect.y += (i+1) * self.rect.height
if rect.collidepoint(mpos):
self.active_option = i
break
if not self.menu_active and self.active_option == -1:
self.draw_menu = False
for event in event_list:
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
if self.menu_active:
self.draw_menu = not self.draw_menu
elif self.draw_menu and self.active_option >= 0:
self.draw_menu = False
return self.active_option
return -1
pg.init()
clock = pg.time.Clock()
screen = pg.display.set_mode((640, 480))
COLOR_INACTIVE = (100, 80, 255)
COLOR_ACTIVE = (100, 200, 255)
COLOR_LIST_INACTIVE = (255, 100, 100)
COLOR_LIST_ACTIVE = (255, 150, 150)
list1 = DropDown(
[COLOR_INACTIVE, COLOR_ACTIVE],
[COLOR_LIST_INACTIVE, COLOR_LIST_ACTIVE],
50, 50, 200, 50,
pg.font.SysFont(None, 30),
"Select Mode", ["Calibration", "Test"])
run = True
while run:
clock.tick(30)
event_list = pg.event.get()
for event in event_list:
if event.type == pg.QUIT:
run = False
selected_option = list1.update(event_list)
if selected_option >= 0:
list1.main = list1.options[selected_option]
screen.fill((255, 255, 255))
list1.draw(screen)
pg.display.flip()
pg.quit()
exit()
See also UI elements
Python 3.
Hello. I made a game which starts off with a main menu and when 'd' is pressed, it will cut to the game screen.
Before I made this main menu, when I would hold space bar, the shapes would rumble. Now when I press 'd' to start the game, the objects are displayed, but holding space bar doesn't do anything, and neither does pressing escape or closing the game. It seems like the keyboard events / game events are not being called anymore once the 'd' is pressed.
Code:
import pygame
import random
import time
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Edit the intensity of the shake (Must be one number apart)
# Ex: a = -100, b = 101. A is negative, B is positive
a = -4
b = 5
up = 10
intensity = (a, b)
startGame = True
# Image Loading
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
done = False
clock = pygame.time.Clock()
class Rectangle():
def __init__(self):
self.x = random.randrange(0, 700)
self.y = random.randrange(0, 500)
self.height = random.randrange(20, 70)
self.width = random.randrange(20, 70)
self.x_change = random.randrange(-3, 3)
self.y_change = random.randrange(-3, 3)
self.color = random.sample(range(250), 4)
def draw(self):
pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height])
def move(self):
self.x += self.x_change
self.y += self.y_change
class Ellipse(Rectangle):
pass
def draw(self):
pygame.draw.ellipse(screen, self.color, [self.x, self.y, self.width, self.height])
def move(self):
self.x += self.x_change
self.y += self.y_change
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def game_intro():
global event
intro = True
keys = pygame.key.get_pressed()
while intro:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(WHITE)
largeText = pygame.font.Font('freesansbold.ttf', 45)
smallText = pygame.font.Font('freesansbold.ttf', 30)
TextSurf, TextRect = text_objects("Welcome to Crazy Rumble.", largeText)
TextRect.center = ((700 / 2), (100 / 2))
TextSurff, TextRectt = text_objects("Press enter to start", smallText)
TextRectt.center = ((700 / 2), (900 / 2))
TextStart, TextRecttt = text_objects("Hold space to make the shapes shake!", smallText)
TextRecttt.center = ((700 / 2), (225 / 2))
screen.blit(TextSurf, TextRect)
screen.blit(TextSurff, TextRectt)
screen.blit(TextStart, TextRecttt)
pygame.display.update()
if event.type == pygame.KEYUP:
intro = False
startGame = True
global intro
my_list = []
for number in range(600):
my_object = Rectangle()
my_list.append(my_object)
for number in range(600):
my_object = Ellipse()
my_list.append(my_object)
# -------- Main Program Loop -----------
while not done:
game_intro()
game_intro = True
if event.type == pygame.KEYUP:
game_intro = False
keys = pygame.key.get_pressed()
# --- Main event loop
while game_intro == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(BLACK)
for rect in my_list:
rect.draw()
rect.move()
for rectElli in my_list:
rectElli.draw()
if keys[pygame.K_SPACE]:
rectElli.y_change = random.randrange(a, b)
rectElli.x_change = random.randrange(a, b)
rectElli.move()
if keys[pygame.K_UP]:
print(up)
print(intensity)
up += 1
if up % 10 == 0:
a -= 1
b -= -1
else:
a, b = -4, 5
pygame.display.flip()
clock.tick(60)
You're just setting keys once with
keys = pygame.key.get_pressed()
You need to put that call inside the loop, so it gets updated after every event.
So i'm trying to set up this thing where a sound effect is made whenever the player "hovers" their mouse above a label.
This is the image: https://gyazo.com/ca251495b348ab8cd27f7328c84518e8
I've tried looking for solutions, I have found one previously but it did not work when adding sound to it.
import math, random, sys
import enum
import pygame, time
from pygame.locals import*
from sys import exit
from pygame import mixer
#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
mixer.init()
#define display
W, H = 1600,900
HW, HH = (W/2), (H/2)
AREA = W * H
#bsound effects
buttonsound1 = pygame.mixer.Sound("ButtonSound1.wav")
#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
FPS = 54
progress = 0
background = pygame.Surface(DS.get_size())
smallfont = pygame.font.SysFont("century gothic",25)
#background image
bg = pygame.image.load("Daytime.jpg").convert()
loadingimg = pygame.image.load("LoadingScreen.png").convert()
pause = pygame.image.load("Pause screen.png").convert()
gameover = pygame.image.load("Game Over.png").convert()
mainmenu = pygame.image.load("Main_Menu4.png").convert()
#mainmenu = pygame.transform.smoothscale(mainmenu, (W,H))
loadingimg = pygame.transform.smoothscale(loadingimg, (W,H))
#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)
walkLeft = [pygame.image.load('Moving1.png'), pygame.image.load('Moving2.png'), pygame.image.load('Moving3.png'), pygame.image.load('Moving4.png'), pygame.image.load('Moving5.png'), pygame.image.load('Moving6.png'), pygame.image.load('Moving7.png'), pygame.image.load('Moving8.png'), pygame.image.load('Moving9.png')]
walkRight = []
for i in walkLeft:
walkRight.append(pygame.transform.flip(i, True, False))
char = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.transform.flip(char2, True, False)
x = 0
y = 500
height = 40
width = 87
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0
run = True
# FUNCTIONS
def event_handler():
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(green)
self.image_hovered = pygame.Surface((width, height))
#buttonsound1.play()
self.image = self.image_normal
self.rect = self.image.get_rect()
font = pygame.font.Font('freesansbold.ttf', 15)
text_image = font.render(text, True, WHITE)
text_rect = text_image.get_rect(center = self.rect.center)
self.image_normal.blit(text_image, text_rect)
self.image_hovered.blit(text_image, text_rect)
# you can't use it before `blit`
self.rect.topleft = (x, y)
self.hovered = False
#self.clicked = False
def update(self):
if self.hovered:
buttonsound1.play()
else:
self.image = self.image_normal
def draw(self, surface):
surface.blit(self.image, self.rect)
def handle_event(self, event):
if event.type == pygame.MOUSEMOTION:
self.hovered = self.rect.collidepoint(event.pos)
buttonsound1.play()
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hovered:
buttonsound1.play()
print('Clicked:', self.text)
if self.command:
self.command()
class GameState( enum.Enum ):
Loading = 0
Menu = 1
Settings = 2
Playing = 3
GameOver = 4
#set the game state initially.
game_state = GameState.Loading
#LOADING
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
return textSurface, textSurface.get_rect()
def loading(progress):
if progress < 100:
text = smallfont.render("Loading: " + str(int(progress)) + "%", True, WHITE)
else:
text = smallfont.render("Loading: " + str(100) + "%", True, WHITE)
DS.blit(text, [50, 660])
def message_to_screen(msh, color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = HW, HH + y_displace
DS.blit(textSurf, textRect)
while (progress/4) < 100:
event_handler()
DS.blit(loadingimg, (0,0))
time_count = (random.randint(1,1))
increase = random.randint(1,20)
progress += increase
pygame.draw.rect(DS, green, [50, 700, 402, 29])
pygame.draw.rect(DS, grey, [50, 701, 401, 27])
if (progress/4) > 100:
pygame.draw.rect(DS, green, [50, 700, 401, 28])
else:
pygame.draw.rect(DS, green, [50, 700, progress, 28])
loading(progress/4)
pygame.display.flip()
time.sleep(time_count)
#changing to menu
game_state = GameState.Menu
Menumusic = pygame.mixer.music.load("MainMenu.mp3")
Menumusic = pygame.mixer.music.play(-1, 0.0)
def main_menu():
DS.blit(mainmenu, (0, 0))
pygame.display.update()
btn1 = Button('Hello', 812.5, 250, 100, 50)
btn2 = Button('World', 825, 325, 100, 50)
btn3 = Button('Hello', 825, 450, 100, 50)
btn4 = Button('World', 825, 575, 100, 50)
btn5 = Button('World', 825, 675, 100, 50)
btn6 = Button('Hello', 825, 790, 100, 50)
while run:
event_handler()
btn1.update()
btn2.update()
# --- draws ---
btn1.draw(DS)
btn2.draw(DS)
btn3.draw(DS)
btn4.draw(DS)
btn5.draw(DS)
btn6.draw(DS)
pygame.display.update()
main_menu()
What I'm expecting is a sound effect to be made whenever the mouse goes over a label, however, the output from the program is that nothing plays or happens.
I think the issue is the processing of the events in event_handler(), which consumes all the events. Then the Button class handle_event() function is starved of events (also this function is never called). It's a good idea to handle events in a single place in the code, and call out from there.
If the OP's code did work, it looks to be constantly re-playing the sounds too. The mouse-move generates a lot of events, so the triggering of playing the sound needs to only play on the initial entry into the button's rectangle. Whereas the mouse movement handler is re-playing on every event inside the button's rect.
Below is some example code where I took your buttons, and modified them to handle the hovering in a "edge-triggered" manner. This means it only triggers when the "hovered" state first becomes true, not while it's true (which would be "level-triggered")
Note: It does not actually play the sound, as I don't have a sound-file handy. It just does a print().
import pygame
#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
pygame.mixer.init()
#define display
W, H = 200, 200
HW, HH = (W/2), (H/2)
AREA = W * H
#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
#pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
pygame.display.set_mode((0, 0) )
FPS = 54
#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(green)
self.image_hovered = pygame.Surface((width, height))
self.image_hovered.fill(grey)
self.image = self.image_normal
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.hovered= False # is the mouse over this button?
def update(self):
pass
def handleMouseOver( self, mouse_position ):
""" If the given co-ordinate inside our rect,
Do all the mouse-hovering work """
# Check button position against mouse
# Change the state *once* on entry/exit
if ( self.mouseIsOver( mouse_position ) ):
if ( self.hovered == False ):
self.image = self.image_hovered
self.hovered = True # edge-triggered, not level triggered
# Do we want to check pygame.mixer.get_busy() ?
if ( pygame.mixer.get_busy() == False ):
print( self.text + " DO buttonsound1.play() ")
else:
if ( self.hovered == True ):
self.image = self.image_normal
self.hovered = False
def mouseIsOver( self, mouse_position ):
""" Is the given co-ordinate inside our rect """
return self.rect.collidepoint( mouse_position )
def draw(self, surface):
surface.blit(self.image, self.rect)
def main_menu():
run = True
btn1 = Button('Hello1', 50, 50, 40, 40)
btn2 = Button('World2', 100, 50, 40, 40)
btn3 = Button('Hello3', 50, 100, 40, 40)
btn4 = Button('World4', 100, 100, 40, 40)
# Put the buttons into a list so we can loop over them, simply
buttons = [ btn1, btn2, btn3, btn4 ]
while run:
# draw the buttons
for b in buttons:
b.draw( DS ) # --- draws ---
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEMOTION:
mouse_position = event.pos
for b in buttons:
b.handleMouseOver( mouse_position )
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_position = event.pos
for b in buttons:
if ( b.mouseIsOver( mouse_position ) ):
print('Clicked:', b.text)
#if b.command:
# b.command()
pygame.display.update()
main_menu()
pygame.quit()
So im setting up a main menu for the program I'm making and I was planning to have a beeping sound for whenever a mouse hovers above a button.
The thing is, I have the button labels on my image already, so i don't really know how i could incorporate this.
import math, random, sys
import enum
import pygame, time
from pygame.locals import*
from sys import exit
from pygame import mixer
#initialising python
pygame.init()
#pygame.mixer.init()
pygame.mixer.pre_init(44100,16,2,4096)
mixer.init()
#define display
W, H = 1600,900
HW, HH = (W/2), (H/2)
AREA = W * H
#bsound effects
buttonsound1 = pygame.mixer.Sound("ButtonSound1.wav")
#initialising display
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W, H))
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
FPS = 54
progress = 0
background = pygame.Surface(DS.get_size())
smallfont = pygame.font.SysFont("century gothic",25)
#background image
bg = pygame.image.load("Daytime.jpg").convert()
loadingimg = pygame.image.load("LoadingScreen.png").convert()
pause = pygame.image.load("Pause screen.png").convert()
gameover = pygame.image.load("Game Over.png").convert()
mainmenu = pygame.image.load("Main_Menu4.png").convert()
#mainmenu = pygame.transform.smoothscale(mainmenu, (W,H))
loadingimg = pygame.transform.smoothscale(loadingimg, (W,H))
#define some colours
BLACK = (0,0,0,255)
WHITE = (255,255,255,255)
green = (0,140,0)
grey = (180,180,180)
walkLeft = [pygame.image.load('Moving1.png'), pygame.image.load('Moving2.png'), pygame.image.load('Moving3.png'), pygame.image.load('Moving4.png'), pygame.image.load('Moving5.png'), pygame.image.load('Moving6.png'), pygame.image.load('Moving7.png'), pygame.image.load('Moving8.png'), pygame.image.load('Moving9.png')]
walkRight = []
for i in walkLeft:
walkRight.append(pygame.transform.flip(i, True, False))
char = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.image.load('Moving1.png').convert_alpha()
char2 = pygame.transform.flip(char2, True, False)
x = 0
y = 500
height = 40
width = 87
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0
run = True
# FUNCTIONS
def event_handler():
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(green)
self.image_hovered = pygame.Surface((width, height))
#buttonsound1.play()
self.image = self.image_normal
self.rect = self.image.get_rect()
font = pygame.font.Font('freesansbold.ttf', 15)
text_image = font.render(text, True, WHITE)
text_rect = text_image.get_rect(center = self.rect.center)
self.image_normal.blit(text_image, text_rect)
self.image_hovered.blit(text_image, text_rect)
# you can't use it before `blit`
self.rect.topleft = (x, y)
self.hovered = False
#self.clicked = False
def update(self):
if self.hovered:
buttonsound1.play()
else:
self.image = self.image_normal
def draw(self, surface):
surface.blit(self.image, self.rect)
def handle_event(self, event):
if event.type == pygame.MOUSEMOTION:
self.hovered = self.rect.collidepoint(event.pos)
buttonsound1.play()
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hovered:
buttonsound1.play()
print('Clicked:', self.text)
if self.command:
self.command()
class GameState( enum.Enum ):
Loading = 0
Menu = 1
Settings = 2
Playing = 3
GameOver = 4
#set the game state initially.
game_state = GameState.Loading
#LOADING
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
return textSurface, textSurface.get_rect()
def loading(progress):
if progress < 100:
text = smallfont.render("Loading: " + str(int(progress)) + "%", True, WHITE)
else:
text = smallfont.render("Loading: " + str(100) + "%", True, WHITE)
DS.blit(text, [50, 660])
def message_to_screen(msh, color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = HW, HH + y_displace
DS.blit(textSurf, textRect)
while (progress/4) < 100:
event_handler()
DS.blit(loadingimg, (0,0))
time_count = (random.randint(1,1))
increase = random.randint(1,20)
progress += increase
pygame.draw.rect(DS, green, [50, 700, 402, 29])
pygame.draw.rect(DS, grey, [50, 701, 401, 27])
if (progress/4) > 100:
pygame.draw.rect(DS, green, [50, 700, 401, 28])
else:
pygame.draw.rect(DS, green, [50, 700, progress, 28])
loading(progress/4)
pygame.display.flip()
time.sleep(time_count)
#changing to menu
game_state = GameState.Menu
Menumusic = pygame.mixer.music.load("MainMenu.mp3")
Menumusic = pygame.mixer.music.play(-1, 0.0)
def main_menu():
DS.blit(mainmenu, (0, 0))
pygame.display.update()
btn1 = Button('Hello', 812.5, 250, 100, 50)
btn2 = Button('World', 825, 325, 100, 50)
btn3 = Button('Hello', 825, 450, 100, 50)
btn4 = Button('World', 825, 575, 100, 50)
btn5 = Button('World', 825, 675, 100, 50)
btn6 = Button('Hello', 825, 790, 100, 50)
while run:
event_handler()
btn1.update()
btn2.update()
# --- draws ---
btn1.draw(DS)
btn2.draw(DS)
btn3.draw(DS)
btn4.draw(DS)
btn5.draw(DS)
btn6.draw(DS)
pygame.display.update()
main_menu()
This is my whole code and I'm not sure what to do with adding buttons.
My image: https://gyazo.com/ca251495b348ab8cd27f7328c84518e8
It doesn't matter where you have button label - you need only its positon and size (x,y,width,height) or its pygame.Rect to compare with mouse position.
Rect has even function collidepoint to check collision with point and it can be mouse position.
if button_rect.collidepoint(mouse_position):
print("Mouse over button")
EDIT:
It is my code from GitHub with simple example with hovering button using class Button which changes color when mouse is over button (hover). It uses Rect.coolidepoint in Button.handle_event(). Maybe it can help you.
import pygame
# === CONSTANTS === (UPPER_CASE names)
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# === CLASSES === (CamelCase names)
class Button():
def __init__(self, text, x=0, y=0, width=100, height=50, command=None):
self.text = text
self.command = command
self.image_normal = pygame.Surface((width, height))
self.image_normal.fill(GREEN)
self.image_hovered = pygame.Surface((width, height))
self.image_hovered.fill(RED)
self.image = self.image_normal
self.rect = self.image.get_rect()
font = pygame.font.Font('freesansbold.ttf', 15)
text_image = font.render(text, True, WHITE)
text_rect = text_image.get_rect(center = self.rect.center)
self.image_normal.blit(text_image, text_rect)
self.image_hovered.blit(text_image, text_rect)
# you can't use it before `blit`
self.rect.topleft = (x, y)
self.hovered = False
#self.clicked = False
def update(self):
if self.hovered:
self.image = self.image_hovered
else:
self.image = self.image_normal
def draw(self, surface):
surface.blit(self.image, self.rect)
def handle_event(self, event):
if event.type == pygame.MOUSEMOTION:
self.hovered = self.rect.collidepoint(event.pos)
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hovered:
print('Clicked:', self.text)
if self.command:
self.command()
# === FUNCTIONS === (lower_case names)
# empty
# === MAIN === (lower_case names)
def main():
# --- init ---
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
is_running = False
btn1 = Button('Hello', 200, 50, 100, 50)
btn2 = Button('World', 200, 150, 100, 50)
# --- mainloop --- (don't change it)
is_running = True
while is_running:
# --- events ---
for event in pygame.event.get():
# --- global events ---
if event.type == pygame.QUIT:
is_running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
is_running = False
# --- objects events ---
btn1.handle_event(event)
btn2.handle_event(event)
# --- updates ---
btn1.update()
btn2.update()
# --- draws ---
screen.fill(BLACK)
btn1.draw(screen)
btn2.draw(screen)
pygame.display.update()
# --- FPS ---
clock.tick(25)
# --- the end ---
pygame.quit()
#----------------------------------------------------------------------
if __name__ == '__main__':
main()
EDIT: play sound only when mouse hovers over button
if event.type == pygame.MOUSEMOTION:
previous_value = self.hovered # remeber previus value
self.hovered = self.rect.collidepoint(event.pos) # get new value
# check both values
if previous_value is False and self.hovered is True:
buttonsound1.play()
# similar play sound when mouse unhovers button
#if previous_value is True and self.hovered is False:
# unhover_sound1.play()