Pygame 简明教程
Pygame - Moving with Mouse
根据鼠标指针的移动来移动对象很容易。pygame.mouse 模块定义了 get_pos() 方法。它返回一个包含两个元素的元组,对应于鼠标当前位置的 x 和 y 坐标。
Moving an object according to movement of mouse pointer is easy. The pygame.mouse module defines get_pos() method. It returns a two-item tuple corresponding to x and y coordinates of current position of mouse.
(mx,my) = pygame.mouse.get_pos()
捕获 mx 和 my 的位置后,借助 Surface 对象上的 bilt() 函数以这些坐标渲染图像。
After capturing mx and my positions, the image is rendered with the help of bilt() function on the Surface object at these coordinates.
Example
以下程序在鼠标光标移动位置持续渲染给定图像。
Following program continuously renders the given image at moving mouse cursor position.
filename = 'pygame.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("Moving with mouse")
img = pygame.image.load(filename)
x = 0
y= 150
while True:
mx,my=pygame.mouse.get_pos()
screen.fill((255,255,255))
screen.blit(img, (mx, my))
for event in pygame.event.get():
if event.type == QUIT:
exit()
pygame.display.update()