pygame中的鼠标点击检测

时间:2019-03-16 03:19:33

标签: python-3.x pygame

我有一个任务,我有一个3X3正方形,每单击一次小正方形,该正方形就会涂成红色。这是我的代码了。我认为在我的第一个while循环中做错了什么,但我不确定。请帮助我。

import pygame

pygame.init()

#create a screen
screen = pygame.display.set_mode((400, 400))

#colors
white = [255, 255, 255]
red = [255, 0, 0]

x = 0
y = 0

#create my square
for j in range(3):

    for i in range(3):

        pygame.draw.rect(screen, white, (x, y, 30, 30), 1)
        x += 30

        if x == 90:
            x = 0
            y += 30

pygame.display.flip()
running = 1

while running:

    event = pygame.event.poll()

#found in what position my mouse is
    if event.type == pygame.QUIT:
        running = 0
    elif event.type == pygame.MOUSEMOTION:
        print("mouse at (%d, %d)" % event.pos)

    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

#mouse click
    if click[0] == 1 and x in range(30) and y in range (30):
        pygame.draw.rect(screen, red, (30, 30 , 29 ,29))

while pygame.event.wait().type != pygame.QUIT:
    pygame.display.change()

1 个答案:

答案 0 :(得分:1)

每次在屏幕上绘画或执行某些操作时,您都必须update屏幕。因此,将此行放在您的第一个while循环下。

pygame.display.flip()

在您的情况下,您正在检查x和y,它们不是鼠标位置。

if click[0] == 1 and x in range(30) and y in range (30):

请检查鼠标在range(90)中的位置,因为您有三个矩形,它们分别为30x30

if click[0] == 1 and mouse[0] in range(90) and mouse[1] in range (90):

然后,设置矩形的起始位置以填充鼠标点。

rect_x = 30*(mouse[0]//30) # set start x position of rectangular  
rect_y = 30*(mouse[1]//30) # set start y position of rectangular 

您可以以此来编辑代码。

while running:

    pygame.display.flip()
    event = pygame.event.poll()

    #found in what position my mouse is
    if event.type == pygame.QUIT:
        running = 0
    elif event.type == pygame.MOUSEMOTION:
        print("mouse at (%d, %d)" % event.pos)


    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    #mouse click
    if click[0] == 1 and mouse[0] in range(90) and mouse[1] in range (90):

        '''
        rect_x = 30*(0//30) = 0
        rect_y = 30*(70//30) = 60
        '''

        rect_x = 30*(mouse[0]//30) # set start x position of rectangular  
        rect_y = 30*(mouse[1]//30) # set start y position of rectangular 

        pygame.draw.rect(screen, red, (rect_x, rect_y , 30 , 30)) # rectangular (height, width), (30, 30)

enter image description here