파이 게임으로 틱택 토를 만들려고 해요. 사각형 중 하나를 클릭하면 x가 표시됩니다. 문제는 x를 표시하는 데 많은 클릭이 필요하다는 것입니다. 다음은 코드입니다.
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.quit()
sys.exit()
mouse_pos = pygame.mouse.get_pos()
event = pygame.event.wait()
screen.fill(bg_color)
if event.type == pygame.MOUSEBUTTONDOWN and 250 < mouse_pos[0] < 300 and 250 > mouse_pos[1] > 199:
mouse_clicked1 = True
if event.type == pygame.MOUSEBUTTONDOWN and 301 < mouse_pos[0] < 351 and 249 > mouse_pos[1] > 201:
mouse_clicked2 = True
if mouse_clicked1:
screen.blit(x, object_top_left)
if mouse_clicked2:
screen.blit(x, object_top)
pygame.event.wait()
큐에서 단일 이벤트를 기다립니다. 에서 얻은 이벤트를 사용하여 함수를 제거하십시오 pygame.event.get()
.
이벤트 유형이 MOUSEBUTTONDOWN
(또는 MOUSEBUTTONUP
)이면 마우스 위치가 객체 의 pos
속성에 저장됩니다 pygame.event.Event()
.
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN and 250 < event.pos[0] < 300 and 250 > event.pos[1] > 199:
mouse_clicked1 = True
if event.type == pygame.MOUSEBUTTONDOWN and 301 < event.pos[0] < 351 and 249 > event.pos[1] > 201:
mouse_clicked2 = True
screen.fill(bg_color)
if mouse_clicked1:
screen.blit(x, object_top_left)
if mouse_clicked2:
screen.blit(x, object_top)
참고 pygame.event.get()
얻고 큐 삭제합니다 모든 이벤트. 따라서 pygame.event.wait()
루프에서를 호출 하면 이벤트가 거의 반환되지 않습니다.
또한 pygame.Rect
객체 를 사용하는 것이 좋습니다 collidepoint()
.
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
rect1 = pygameRect(250, 200, 50, 50)
if rect1.collidepoint(event.pos):
mouse_clicked1 = True
rect2 = pygameRect(300, 200, 50, 50)
if rect2.collidepoint(event.pos):
mouse_clicked2 = True
screen.fill(bg_color)
if mouse_clicked1:
screen.blit(x, object_top_left)
if mouse_clicked2:
screen.blit(x, object_top)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다