鼠标坐标不变 - python

Mouse coordinates not changing - 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()

谢谢,我成功地为我的 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()

我使用了调试线来查看是否是变量的问题,但这些变量似乎工作正常,所以我不确定问题出在哪里。

这是你第二个问题的答案:

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

您只需删除 game_screen.fill(black) 即可。