是否可以用鼠标点击Pygame中的不同矩形按钮,获取x-y位置并将if语句作为变量。
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
.
.
.
if button_cliked_one and button_cliked_two:
print ('buttons clicked')
else:
print('something is wrong')
答案 0 :(得分:1)
很难理解你想要什么,但也许你想存储以前的鼠标点击位置以绘制矩形?
您所要做的就是将其存储在另一个变量中。如果您一次只需要两个点击位置,则只需使用它。或者,您可以使用Python列表存储任意数量点击的位置。
import pygame, sys
SIZE = 640, 480
screen = pygame.display.set_mode(SIZE)
# empty list
all_clicks = []
drawn = True
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
# store mouse click position in the list:
all_clicks.append(event.pos)
# event.pos already has the info you'd get by calling pygame.mouse.get_pos()
drawn = False
print(all_clicks)
# at every second click:
if not len(all_clicks) % 2 and not drawn:
# draw a rectangle having the click positions as coordinates:
# pick the minimal x coordinate of both clicks as left position for rect:
x = min(all_clicks[-1][0], all_clicks[-2][0])
# ditto for top positionn
y = min(all_clicks[-1][1], all_clicks[-2][1])
# and calculate width and height in the same way
w = max(all_clicks[-1][0], all_clicks[-2][0]) - x
h = max(all_clicks[-1][1], all_clicks[-2][1]) - y
pygame.draw.rect(screen, (255, 255, 255), (x, y, w, h))
drawn = True
# update screen:
pygame.display.flip()
# pause a while (30ms) least our game use 100% cpu for nothing:
pygame.time.wait(30)
答案 1 :(得分:0)
您可以使用变量previous_button
和current_button
来记住最后两个按钮。然后你可以检查它们是否正确。
它类似于@jsbueno解决方案,但我使用两个变量,而不是列表。 如果您想要检查更长的组合,那么您可以使用列表。
import pygame
# --- functions ---
def check_which_button_was_click(buttons, pos):
for name, (rect, color) in buttons.items():
if rect.collidepoint(pos):
return name
# --- main ---
# - init -
screen = pygame.display.set_mode((350, 150))
# - objects -
buttons = {
'RED': (pygame.Rect(50, 50, 50, 50), (255, 0, 0)),
'GREEN': (pygame.Rect(150, 50, 50, 50), (0, 255, 0)),
'BLUE': (pygame.Rect(250, 50, 50, 50), (0, 0, 255)),
}
previous_button = None
current_button = None
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - event -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
clicked_button = check_which_button_was_click(buttons, event.pos)
if clicked_button is not None:
previous_button = current_button
current_button = clicked_button
print(previous_button, current_button)
# - updates -
if previous_button == 'RED' and current_button == 'BLUE':
print('correct buttons clicked: RED & BLUE')
previous_button = None
current_button = None
# - draws -
screen.fill((0,0,0))
for rect, color in buttons.values():
pygame.draw.rect(screen, color, rect)
pygame.display.flip()
# - FPS -
clock.tick(5)
# - end -
pygame.quit()