首页 > 解决方案 > 如何在pygame中制作一系列坐标?

问题描述

这是一个非常简单的问题,但我想编写一些代码,以便当你在某个范围内时,你点击某个东西,它会改变背景。到目前为止一切正常,但我只知道如何对其进行编码,以便当您处于确切的 X 和 Y 坐标时,您就可以点击。如果你在 100-300 X(例如)和 500 - 600 Y 范围内,我该如何做到这一点,而不是 100 X 和 600 Y 的精确坐标?

(顺便说一下,这是我正在使用的代码片段,如果你愿意,我可以提供完整的代码。)

if 120+75 > mouse[0] > 120 and 50 + 125 > mouse[1] > 125 and x == 110 and y == 60:
    print('Click to change')

标签: pygame

解决方案


您必须定义矩形区域的左上角 ( x, y) 和区域的大小 ( width, height):

x = 120
y = 125
width = 75
height = 50

评估鼠标是否在该区域:

if x < mouse[0] x + width and y < mouse[1] y + height:
    print('Click to change')

我建议使用pygame.Rect.collidepoint()通过(x, y, width, height)定义一个矩形对象并评估鼠标位置是否在矩形区域内:

rect = pygame.Rect(120, 125, 75, 50)
if rect.collidepoint(mouse):
    print('Click to change')

推荐阅读