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
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()
This question already has answers here:
Pygame mouse clicking detection
(4 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
So I'm working on a snake game and I ran into some problems with the button class. I would like to implement two buttons at the end of the game. One in order to restart the game, the other one to close the game. I tested the buttons and they should be working. I just don't know where to draw them, because when I draw them at the end, I cannot press the button, because the game freezes due to the game.sleep() command. The game closes on itself, that's why I added a delay. I drew the buttons al the way at the end.
I edited the code, so only the button code is shown below with the gameloop.
clicked = False
font = pygame.font.SysFont('Constantia', 30)
class button():
# colours for button and text
button_col = (255, 0, 0)
hover_col = (75, 225, 255)
click_col = (50, 150, 255)
text_col = BLACK
width = 180
height = 70
def __init__(self, x, y, text):
self.x = x
self.y = y
self.text = text
def draw_button(self):
global clicked
action = False
# get mouse position
pos = pygame.mouse.get_pos()
# create pygame Rect object for the button
button_rect = Rect(self.x, self.y, self.width, self.height)
# check mouseover and clicked conditions
if button_rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1:
clicked = True
pygame.draw.rect(SCREEN, self.click_col, button_rect)
elif pygame.mouse.get_pressed()[0] == 0 and clicked == True:
clicked = False
action = True
else:
pygame.draw.rect(SCREEN, self.hover_col, button_rect)
else:
pygame.draw.rect(SCREEN, self.button_col, button_rect)
# add shading to button
pygame.draw.line(SCREEN, WHITE, (self.x, self.y),
(self.x + self.width, self.y), 2)
pygame.draw.line(SCREEN, WHITE, (self.x, self.y),
(self.x, self.y + self.height), 2)
pygame.draw.line(SCREEN, BLACK, (self.x, self.y + self.height),
(self.x + self.width, self.y + self.height), 2)
pygame.draw.line(SCREEN, BLACK, (self.x + self.width, self.y),
(self.x + self.width, self.y + self.height), 2)
# add text to button
text_img = font.render(self.text, True, self.text_col)
text_len = text_img.get_width()
SCREEN.blit(text_img, (self.x + int(self.width / 2) -
int(text_len / 2), self.y + 25))
return action
again = button(75, 200, 'Play Again?')
quit = button(325, 200, 'Quit?')
def main():
RUN = True
SNAKE_POS_X = BLOCKSIZE
SNAKE_POS_Y = BLOCKSIZE
SNAKE_POS_X_CHANGE = 0
SNAKE_POS_Y_CHANGE = 0
LENGTH_OF_SNAKE = 1
global FOOD_POS_X, FOOD_POS_Y
FOOD_POS_X = round(random.randrange(
0, WIDTH - BLOCKSIZE) / BLOCKSIZE) * BLOCKSIZE
FOOD_POS_Y = round(random.randrange(
0, HEIGHT - BLOCKSIZE) / BLOCKSIZE) * BLOCKSIZE
while RUN:
for event in pygame.event.get():
if event.type == pygame.QUIT:
RUN = False
# snake_movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
SNAKE_POS_X_CHANGE = 0
SNAKE_POS_Y_CHANGE = -BLOCKSIZE
elif event.key == pygame.K_DOWN:
SNAKE_POS_X_CHANGE = 0
SNAKE_POS_Y_CHANGE = BLOCKSIZE
elif event.key == pygame.K_RIGHT:
SNAKE_POS_X_CHANGE = BLOCKSIZE
SNAKE_POS_Y_CHANGE = 0
elif event.key == pygame.K_LEFT:
SNAKE_POS_X_CHANGE = -BLOCKSIZE
SNAKE_POS_Y_CHANGE = 0
if SNAKE_POS_X >= WIDTH or SNAKE_POS_X < 0 or SNAKE_POS_Y >= HEIGHT or SNAKE_POS_Y < 0:
RUN = False
SNAKE_POS_X += SNAKE_POS_X_CHANGE
SNAKE_POS_Y += SNAKE_POS_Y_CHANGE
SCREEN.fill(BISQUE2)
checkerboard()
food()
SNAKE_HEAD = []
SNAKE_HEAD.append(SNAKE_POS_X)
SNAKE_HEAD.append(SNAKE_POS_Y)
SNAKE_LIST.append(SNAKE_HEAD)
if len(SNAKE_LIST) > LENGTH_OF_SNAKE:
del SNAKE_LIST[0]
for x in SNAKE_LIST[:-1]:
if x == SNAKE_HEAD:
RUN = False
snake(BLOCKSIZE, SNAKE_LIST)
score(LENGTH_OF_SNAKE - 1)
# draw_grid()
CLOCK.tick(FPS)
pygame.display.update()
if SNAKE_POS_X == FOOD_POS_X and SNAKE_POS_Y == FOOD_POS_Y:
FOOD_POS_X = round(random.randrange(
0, WIDTH - BLOCKSIZE) / BLOCKSIZE) * BLOCKSIZE
FOOD_POS_Y = round(random.randrange(
0, HEIGHT - BLOCKSIZE) / BLOCKSIZE) * BLOCKSIZE
LENGTH_OF_SNAKE += 1
CRUNCH.play()
game_over_message("Game Over!", BLACK)
GAME_OVER_SOUND.play()
# pygame.display.update()
if again.draw_button():
main()
if quit.draw_button():
pygame.quit()
pygame.display.update()
time.sleep(2)
pygame.quit()
main()
Is it because you do not have FOOD_POS_X, FOOD_POS_Y defined as this I got errors from these when I tried to run your code
I'm making a class that allows users to make text boxes for pygame games. I'm able to reach the mousebuttondown command but it doesn't reach that keyboard input statement. Given below is my whole code along with that part that is giving me an issue. I also need a way to take the input for every letter.
not printing reached
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
if event.type == pygame.K_a:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
whole code - ignore update
import pygame
pygame.font.init()
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
self.surface = surface
self.id = id
self.color = color
self.width = width
self.height = height
self.x = x
self.y = y
self.antialias = antialias
self.maxtextlen = maxtextlen
self.text_list = []
self.text_list_keys = []
self.currentId = 0
self.click_check = False
self.font = pygame.font.SysFont('comicsans', 20)
self.dict_all = {}
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
# for i in self.text_list_keys:
# if self.id not in i:
# self.text_list_keys.append(self.id)
# self.text_list.append(tuple(self.id))
# else:
# self.nothing()
self.dict_all[self.id] = tuple((self.x, self.y, self.width, self.height))
self.dict_text = {}
def update(self, events, mousepos):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN and ((self.x + self.width) > mousepos[0] > self.x) \
and ((self.y + self.height) > mousepos[1] > self.y):
print("reached: " + mousepos)
self.click_check = True
else:
self.click_check = False
if self.click_check:
print("1")
if event.type == pygame.KEYDOWN:
print("#")
if event.key == pygame.K_a:
print("reached")
new_t = ""
for j in range(len(self.text_list)):
t = (self.text_list[j][0]).index(self.getId(self.currentId))
new_t = t
self.text_list[new_t].append("a")
self.surface.blit(self.font.render(f'{self.text_list[new_t]}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("this")
else:
pass
def rect(self, text_id, mousepos):
x, y, width, height = self.dict_all[text_id]
if ((x + width) > mousepos[0] > x) and ((y + height) > mousepos[1] > y):
print("yes")
return True
else:
return False
def getId(self, text_id):
self.currentId = text_id
def nothing(self):
return False
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
if event.type == pygame.K_a:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
test.py
import pygame
from pygame_textbox import textBox
pygame.init()
win_width = 500
win_height = 500
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("test")
run = True
while run:
mouse = pygame.mouse.get_pressed()
screen.fill((0, 0, 0))
events = pygame.event.get()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
# a.getId(1)
a.rect(1, mouse)
mouse_pos = pygame.mouse.get_pos()
a.main(events, mouse_pos, 1)
pygame.display.update()
edited main
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
if event.type == pygame.KEYDOWN:
# keys = pygame.key.get_pressed()
# if keys[pygame.K_a]:
if event.type == pygame.K_a:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
Updated files
import pygame
pygame.font.init()
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
self.surface = surface
self.id = id
self.color = color
self.width = width
self.height = height
self.x = x
self.y = y
self.antialias = antialias
self.maxtextlen = maxtextlen
self.text_list = []
self.text_list_keys = []
self.currentId = 0
self.click_check = False
self.font = pygame.font.SysFont('comicsans', 20)
self.dict_all = {}
self.pressed = False
self.dict_text = {}
self.dict_text[id] = []
# pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
# for i in self.text_list_keys:
# if self.id not in i:
# self.text_list_keys.append(self.id)
# self.text_list.append(tuple(self.id))
# else:
# self.nothing()
self.dict_all[self.id] = tuple((self.x, self.y, self.width, self.height))
self.dict_text = {}
def draw(self):
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
# def update(self, events, mousepos):
# for event in events:
# if event.type == pygame.QUIT:
# exit()
# if event.type == pygame.MOUSEBUTTONDOWN and ((self.x + self.width) > mousepos[0] > self.x) \
# and ((self.y + self.height) > mousepos[1] > self.y):
# print("reached: ", mousepos)
# self.click_check = True
# else:
# self.click_check = False
#
# if self.click_check:
# print("1")
# if event.type == pygame.KEYDOWN:
# print("#")
# if event.key == pygame.K_a:
# print("reached")
# new_t = ""
# for j in range(len(self.text_list)):
# t = (self.text_list[j][0]).index(self.getId(self.currentId))
# new_t = t
# self.text_list[new_t].append("a")
# self.surface.blit(self.font.render(f'{self.text_list[new_t]}', self.antialias, (0, 0, 0)),
# (self.x, self.y))
#
# else:
# print("this")
#
# else:
# pass
def rect(self, text_id, mousepos):
x, y, width, height = self.dict_all[text_id]
if ((x + width) > mousepos[0] > x) and ((y + height) > mousepos[1] > y):
print("yes")
return True
else:
return False
def getId(self, text_id):
self.currentId = text_id
def nothing(self):
return False
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
self.pressed = False
if self.rect(id, mousepos):
self.pressed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
if self.pressed:
print("reached")
self.dict_text[id].append("a")
self.surface.blit(
self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
else:
pass
test.py
import pygame
from pygame_textbox import textBox
pygame.init()
win_width = 500
win_height = 500
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("test")
run = True
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
while run:
mouse = pygame.mouse.get_pressed()
screen.fill((0, 0, 0))
events = pygame.event.get()
a.draw()
a.getId(1)
a.rect(1, mouse)
mouse_pos = pygame.mouse.get_pos()
a.main(events, mouse_pos, 1)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
pygame.display.update()
The button is stored in the key attribute of the event, rather than the type attribute:
(see pygame.event)
if event.type == pygame.K_a:
if event.key == pygame.K_a:
Any way, that won't solve your issue, because the MOUSEBUTTONDOWN event doesn't evaluate and key state and even has no key attribute. Only the KEYDOWN and KEYUP events provide a key.
You have to use pygame.key.get_pressed() to evaluate if an additional key is hold down when the mouse button is pressed:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect(id, mousepos):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
print("reached")
# [...]
If you want to detect when the mouse is on the button and a is pressed, then you've to use the KEYDOWN event:
if event.type == pygame.KEYDOWN:
if self.rect(id, mousepos):
if event.key == pygame.K_a:
print("reached")
# [...]
If you want to detect if the button was pressed by the mouse and later you want to detect if a is pressed, then you have to store the state if the button is pressed:
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
# [...]
self.pressed = False
def draw(self):
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
for id in self.dict_text:
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)), (self.x, self.y))
# [...]
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
self.pressed = False
if self.rect(id, mousepos):
self.pressed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
if self.pressed:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("didn't")
Of course you've to instance the button (a) before the main application loop:
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
run = True
while run:
# [...]
a.draw()
a.rect(1, mouse)
# [...]
Complete code:
import pygame
pygame.font.init()
class textBox:
def __init__(self, surface, id, color, width, height, x, y, antialias, maxtextlen):
self.surface = surface
self.id = id
self.color = color
self.width = width
self.height = height
self.x = x
self.y = y
self.antialias = antialias
self.maxtextlen = maxtextlen
self.text_list = []
self.text_list_keys = []
self.currentId = 0
self.click_check = False
self.font = pygame.font.SysFont('comicsans', 20)
self.dict_all = {}
# for i in self.text_list_keys:
# if self.id not in i:
# self.text_list_keys.append(self.id)
# self.text_list.append(tuple(self.id))
# else:
# self.nothing()
self.dict_all[self.id] = tuple((self.x, self.y, self.width, self.height))
self.dict_text = {}
self.pressed = False
def draw(self):
pygame.draw.rect(self.surface, (self.color), (self.x, self.y, self.width, self.height))
for id in self.dict_text:
self.surface.blit(self.font.render(f'{str(self.dict_text[id])}', self.antialias, (0, 0, 0)), (self.x, self.y))
def update(self, events, mousepos):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN and ((self.x + self.width) > mousepos[0] > self.x) \
and ((self.y + self.height) > mousepos[1] > self.y):
print("reached: " + mousepos)
self.click_check = True
else:
self.click_check = False
if self.click_check:
print("1")
if event.type == pygame.KEYDOWN:
print("#")
if event.key == pygame.K_a:
print("reached")
new_t = ""
for j in range(len(self.text_list)):
t = (self.text_list[j][0]).index(self.getId(self.currentId))
new_t = t
self.text_list[new_t].append("a")
self.surface.blit(self.font.render(f'{self.text_list[new_t]}', self.antialias, (0, 0, 0)),
(self.x, self.y))
else:
print("this")
else:
pass
def rect(self, text_id, mousepos):
x, y, width, height = self.dict_all[text_id]
if ((x + width) > mousepos[0] > x) and ((y + height) > mousepos[1] > y):
print("yes")
return True
else:
return False
def getId(self, text_id):
self.currentId = text_id
def nothing(self):
return False
def main(self, events, mousepos, id):
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
self.pressed = False
if self.rect(id, mousepos):
self.pressed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
if self.pressed:
print("reached")
self.dict_text[id] = []
self.dict_text[id].append("a")
else:
print("didn't")
pygame.init()
win_width = 500
win_height = 500
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("test")
a = textBox(screen, 1, (255, 255, 255), 100, 30, 100, 100, True, 20)
run = True
while run:
mouse = pygame.mouse.get_pressed()
screen.fill((0, 0, 0))
events = pygame.event.get()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
# a.getId(1)
a.draw()
a.rect(1, mouse)
mouse_pos = pygame.mouse.get_pos()
a.main(events, mouse_pos, 1)
pygame.display.update()
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:
I am writing a code for a game (school project).
I have a Class with different images for objects.
What I want is to create a condition for collision. For example, if the image if fire collides the image of earth then get a new image.
How can I do it ?
Thank you!
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((900,800))
pygame.display.set_caption("Tiny Alchemist")
clock = pygame.time.Clock()
FPS = 90
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
ALTWHITE = (240, 240, 240)
clear = False # Flag that shows if the user wants to clear the screen
class Element(pygame.Surface):
def __init__(self, image, xpos, ypos):
self.image = image
self.xpos = xpos
self.ypos = ypos
self.width = image.get_width()
self.height = image.get_height()
self.selected = False
self.visible = False
self.rect = pygame.Rect(xpos, ypos, image.get_width(), image.get_height())
def move(self, move):
self.xpos += move[0]
self.ypos += move[1]
self.rect = pygame.Rect(self.xpos, self.ypos, self.width, self.height)
class Recycle(pygame.Surface):
def __init__(self, xpos, ypos):
self.image = pygame.image.load("ElementIcon/recycle.png").convert_alpha()
self.image = pygame.transform.scale(self.image, (75, 75))
self.image.set_colorkey(BLACK)
self.xpos = xpos
self.ypos = ypos
self.rect = pygame.Rect(xpos, ypos, self.image.get_width(), self.image.get_height())
class PanelElements(pygame.Surface):
def __init__ (self, image, xpos, ypos):
self.image = image
self.xpos = xpos
self.ypos = ypos
self.rect = pygame.Rect(xpos, ypos, image.get_width(), image.get_height())
self.clicked = False
def init():
global ImageList
global Panel
global recycle
fire = pygame.image.load("ElementIcon/fire.png").convert_alpha()
fire = pygame.transform.scale(fire, (50, 69))
fire.set_colorkey(BLACK)
fire_mini = pygame.transform.scale(fire, (40,50))
fire_mini.set_colorkey(ALTWHITE)
earth = pygame.image.load("ElementIcon/earth.png").convert_alpha()
earth = pygame.transform.scale(earth, (50, 69))
earth.set_colorkey(BLACK)
earth_mini = pygame.transform.scale(earth, (40, 50))
earth_mini.set_colorkey(ALTWHITE)
water = pygame.image.load("ElementIcon/water.png").convert_alpha()
water = pygame.transform.scale(water, (50, 69))
water.set_colorkey(BLACK)
water_mini = pygame.transform.scale(water, (40, 50))
water_mini.set_colorkey(ALTWHITE)
wind = pygame.image.load("ElementIcon/wind.png").convert_alpha()
wind = pygame.transform.scale(wind, (50, 69))
wind.set_colorkey(BLACK)
wind_mini = pygame.transform.scale(wind, (40, 50))
wind_mini.set_colorkey(ALTWHITE)
energy = pygame.image.load("ElementIcon/energy.png").convert_alpha()
energy = pygame.transform.scale(energy, (50, 69))
energy.set_colorkey(BLACK)
energy_mini = pygame.transform.scale(energy, (40, 50))
energy_mini.set_colorkey(ALTWHITE)
recycle = Recycle(650, 718)
fire_mini_obj = PanelElements(fire_mini, 750, 10)
earth_mini_obj = PanelElements(earth_mini, 750, 60)
water_mini_obj = PanelElements(water_mini, 750, 110)
wind_mini_obj = PanelElements(wind_mini, 750, 160)
fire_obj = Element(fire, 362, 460)
fire_obj.visible = True
earth_obj = Element(earth, 300, 410)
earth_obj.visible = True
water_obj = Element(water, 365, 350)
water_obj.visible = True
wind_obj = Element(wind, 420, 409)
wind_obj.visible = True
Panel = [] #adding elements to the list
Panel.append(fire_mini_obj)
Panel.append(earth_mini_obj)
Panel.append(water_mini_obj)
Panel.append(wind_mini_obj)
ImageList =[] #adding elements to the list
ImageList.append(fire_obj)
ImageList.append(earth_obj)
ImageList.append(water_obj)
ImageList.append(wind_obj)
def run():
global done
done = False
while done == False:
check_events()
update()
clock.tick(60)
def check_events():
global done
global ImageList
global Panel
global recycle
global clear
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
print("User quits the game :(")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
print("Game stopped early by user :( ")
if event.type == pygame.MOUSEBUTTONDOWN:
for im in ImageList:
if im.rect.collidepoint(mouse_pos) and (im.visible == True):
im.selected = True
if recycle.rect.collidepoint(mouse_pos):
clear = True
for mini in Panel:
if mini.rect.collidepoint(mouse_pos):
mini.clicked = True
if event.type == pygame.MOUSEBUTTONUP:
for im in ImageList:
if im.rect.collidepoint(mouse_pos) and im.visible == True:
im.selected = False
if event.type == pygame.MOUSEMOTION:
for im in ImageList:
if im.rect.collidepoint(mouse_pos) and im.selected and (im.visible == True):
xmv = event.rel[0]
ymv = event.rel[1]
if event.buttons[0]:
if xmv < 0:
if im.xpos > 0:
im.move((xmv,0))
elif event.rel[0] > 0:
if im.xpos < screen.get_width():
im.move((xmv,0))
elif ymv < 0:
if im.ypos > 0:
im.move((0,ymv))
elif event.rel[1] > 0:
if im.ypos < screen.get_height():
im.move((0,ymv))
#pygame.display.update()
def update():
global ImageList
global Panel
global recycle
global clear
screen.fill(WHITE)
#Update the screen with drawings
for im in ImageList:
if im.visible == True:
screen.blit(im.image, (im.xpos, im.ypos))
pygame.draw.rect(screen, ALTWHITE, (740, 0, 160, 800), 0)
for mini in Panel:
screen.blit(mini.image, (mini.xpos, mini.ypos))
screen.blit(recycle.image, (recycle.xpos, recycle.ypos))
if (clear == True):
for im in ImageList:
im.visible = False
clear = False
for i in range(0,len(Panel)):
if Panel[i].clicked == True:
Panel[i].clicked = False
pygame.display.update()
if __name__=="__main__":
init()
run()
pygame.quit()
perhaps something like this:
earth = pygame.image.load("earth.png").convert()
earthRect = earth.get_rect()
fire = pygame.image.load("fire.png").convert()
fireRect = fire.get_rect()
if earth.colliderect(fire):
earth = pygame.image.load("thirdimage.png")
with the first four lines defining our images and the rect objects used to detect collision, the last two line detecting the collision and changing the image file