|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
为实现点击一下显示方框,再点击显示另一个方框。下次点击前面的方框消失,新方框出现。下面的代码问题在哪?
import pygame
import sys
from pygame.locals import *
pygame.init()
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
size = width, height = 640, 640
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygame Demo")
first=True
Thisone=False
Thatpos=False
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
x = pos[0]
y = pos[1]
if first:
x1 = x
y1 = y
Thisone = True
Thatpos = False
if Thisone == True:
pygame.draw.rect(screen, RED, (x1, y1, 50, 50), 1)
first = False
else:
x2 = x
y2 = y
Thatpos = True
Thisone = False
if Thatpos == True:
pygame.draw.rect(screen, BLUE, (x2, y2, 50, 50), 1)
first = True
screen.fill((0,0,0))
#pygame.draw.rect(screen, RED, (200, 200, 50, 50), 1)
pygame.draw.circle(screen,GREEN, (300, 300), 50, 5)
pygame.display.update()
代码中存在几个问题导致矩形无法正确显示:
1. **顺序填充屏幕**:在每次事件循环中,您先绘制矩形,然后又立即调用`screen.fill((0,0,0))`来填充屏幕,这会覆盖所有已经绘制的内容。应该在此调用之后绘制矩形。
2. **获取鼠标坐标**:`pos = pygame.mouse.get_pos()`返回一个元组,应该分别获取 x 和 y 坐标。
3. **标志逻辑**:`Thisone` 和 `Thatpos` 标志在此场景中没有实际的功能,可以不需要,直接用`first`来管理切换。
修改后的代码示例如下:
import pygame
import sys
from pygame.locals import *
pygame.init()
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
size = width, height = 640, 640
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygame Demo")
first = True
rect_pos = None
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
x, y = pos
rect_pos = (x, y)
first = not first
screen.fill((0, 0, 0))
if rect_pos is not None:
color = RED if first else BLUE
pygame.draw.rect(screen, color, (rect_pos[0], rect_pos[1], 50, 50), 1)
pygame.draw.circle(screen, GREEN, (300, 300), 50, 5)
pygame.display.update()
这样修改后,每次点击时会显示一个新颜色的矩形,前一个矩形则会被覆盖消失。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
|