鼠标坐标不变-python



我正试图构建一个简单的游戏,但我的鼠标遇到了问题,因为它没有显示它的坐标正在改变。

这是我的代码:

import pygame
pygame.init()
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
# Game Screen Dimensions
game_layout_length = 500
game_layout_width = 500
# Mouse Positions
pos = pygame.mouse.get_pos()
# Character Attributes
character_length = 10
character_width = 10
game_screen = pygame.display.set_mode((game_layout_width, game_layout_length))
game_close = False
game_lost = False
while not game_close:
while not game_lost:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_close = True
game_lost = True
if event.type == pygame.MOUSEBUTTONDOWN:
print(pos)
game_screen.fill(black)
pygame.display.update()
pygame.quit()
quit()

这是点击屏幕多个不同部分后的结果:

pygame 2.1.2 (SDL 2.0.18, Python 3.8.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
(0, 0)
(0, 0)
(0, 0)
(0, 0)
(0, 0)
Process finished with exit code 0

还有,有没有办法让一个矩形跟随我的鼠标?我试着做pygame.mouse.rect(game_screen, blue, [pos, character_length, character_width]),但那只是破坏了我的程序。

因此,问题是您没有刷新鼠标位置,因为它不在循环中。您所需要做的就是将pos变量放入循环中。

以下是你应该怎么做:

if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
print(pos)
game_screen.fill(black)
pygame.display.update()

这是第二个问题的答案:

所以,问题是,在你画出矩形后,你用黑色填充屏幕,所以,所有的矩形都被黑色覆盖了。

你所需要做的就是删除game_screen.fill(black),它就会起作用。

谢谢,我成功地将一个变量设置为我的x和y坐标,但当我试图使一些东西(如矩形(跟随我的鼠标时,它不起作用,甚至不显示。该程序只是执行一个纯黑色屏幕。

这是我的代码:

import pygame
pygame.init()
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
# Game Screen Dimensions
game_layout_length = 500
game_layout_width = 500
# Character Attributes
character_length = 10
character_width = 10
game_screen = pygame.display.set_mode((game_layout_width, game_layout_length))
game_close = False
game_lost = False
while not game_close:
while not game_lost:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_close = True
game_lost = True
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
character_x = pos[0]
character_y = pos[1]
pygame.draw.rect(game_screen, blue, [character_x, character_y, character_length, character_width])
game_screen.fill(black)
pygame.display.update()
pygame.quit()
quit()

我用了一条调试线来查看变量是否有问题,但这些似乎都很好,所以我不确定问题在哪里。

最新更新