📜  pygame mouse pos - Python (1)

📅  最后修改于: 2023-12-03 15:18:45             🧑  作者: Mango

Pygame Mouse Pos - Python

该程序主要是在Pygame中获取鼠标的位置,并且显示在屏幕上。这对于游戏开发和交互式应用程序开发非常有用。

安装Pygame

在使用Pygame之前,需要先安装Pygame。我们可以在终端或命令行中使用以下命令来安装Pygame:

pip install pygame
获取鼠标位置

我们可以使用pygame.mouse.get_pos()函数来获取鼠标位置。鼠标位置是一个元组,元组的第一个值是鼠标的x轴坐标,第二个值是鼠标的y轴坐标。

import pygame

# Initialize Pygame
pygame.init()

# Set the width and height of the screen (just like before)
size = (700, 500)
screen = pygame.display.set_mode(size)

# Set the window title
pygame.display.set_caption("Pygame Mouse Pos")

# Loop until the user clicks the close button
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Main program loop
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # User clicked the close button
            done = True
    
    # --- Game logic should go here

    # --- Drawing code should go here
    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill((255, 255, 255))

    # Get the mouse position
    mouse_pos = pygame.mouse.get_pos()

    # Print the mouse position
    font = pygame.font.Font(None, 36)
    text = font.render("Mouse position: {0}".format(mouse_pos), True, (0, 0, 0))
    screen.blit(text, (10, 10))

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(60)

# Close the window and quit.
pygame.quit()
解释代码

在上述代码中,我们首先导入了pygame模块,然后进行了初始化。然后,我们定义了屏幕的大小并创建了一个名为screen的屏幕对象。接下来,我们设置了窗口的标题。

然后,我们进入程序的循环,使用pygame.mouse.get_pos()函数获取鼠标的位置,并使用pygame.font.Font()函数创建字体对象,更新屏幕并将鼠标位置显示出来。

最后,我们使用pygame.quit()来结束程序。