|
|
发表于 2024-8-28 19:22:49
|
显示全部楼层
你好,鱼油。你提出的代码逻辑问题主要是在于按钮状态的检测以及 `button1.count` 和 `button2.count` 的值更新方式。这导致在点击按钮后没有正确记录状态。以下是修改建议和解释:
1. **使用 `pygame.mouse.get_pressed()` 检测鼠标按压状态:** 这样可以确保检测到按下和释放的事件。
2. **避免使用多余的计数器**:可以用布尔变量来检测按钮是否被按下。
3. **在主循环中检测鼠标点击**:这样可以持续更新按钮状态。
修改后的代码如下:
- # coding: utf-8
- import pygame
- import sys
- from pygame.locals import *
- pygame.init()
- win = pygame.display.set_mode((360, 450))
- GREEN = (0, 255, 0)
- RED = (255, 0, 0)
- WHITE = (255, 255, 255)
- DIM = (40, 40, 40)
- class Circle:
- def __init__(self, color, x, y, r, width):
- self.color = color
- self.x = x
- self.y = y
- self.r = r
- self.width = width
- def draw(self, win):
- pygame.draw.circle(win, self.color, (self.x, self.y), self.r, 0)
- # 创建按钮类
- class Button:
- def __init__(self, color, x, y, l, w, initial_state=False):
- self.color = color
- self.x = x
- self.y = y
- self.l = l
- self.w = w
- self.pressed = initial_state
- def draw(self, win):
- color = GREEN if self.pressed else RED
- pygame.draw.rect(win, color, (self.x, self.y, self.l, self.w), 0)
- def check_click(self, mouse_pos, mouse_pressed):
- if (self.x < mouse_pos[0] < self.x + self.l and
- self.y < mouse_pos[1] < self.y + self.w):
- if mouse_pressed[0]: # 检测左键
- self.pressed = True
- else:
- self.pressed = False
- button1 = Button(RED, 50, 150, 60, 40)
- button2 = Button(RED, 250, 150, 60, 40)
- bulb = Circle(DIM, 180, 300, 60, 0)
- while True:
- win.fill((0, 0, 0))
- events = pygame.event.get()
- pos = pygame.mouse.get_pos()
- mouse_pressed = pygame.mouse.get_pressed()
-
- for event in events:
- if event.type == QUIT:
- pygame.quit()
- sys.exit()
- button1.check_click(pos, mouse_pressed)
- button2.check_click(pos, mouse_pressed)
- if button1.pressed and button2.pressed:
- bulb.color = WHITE
- else:
- bulb.color = DIM
- button1.draw(win)
- button2.draw(win)
- bulb.draw(win)
- pygame.display.update()
复制代码
主要修改点:
1. 在 `Button` 类中新加入 `pressed` 布尔变量,用来记录按钮是否被按下。
2. 定义 `check_click` 方法来检测鼠标点击并更新 `pressed` 状态。
3. 在主循环中调用 `check_click` 方法来检测鼠标点击事件并判断按钮状态。
这样修改之后,只有在两个按钮都被按下时,灯才亮。希望这能解决你的问题!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|