Pygame - 用滑鼠移動



根據滑鼠指標的移動來移動一個物件非常容易。pygame.mouse 模組定義了 get_pos() 方法。它返回一個包含滑鼠當前位置的 x 和 y 座標的兩項元組。

(mx,my) = pygame.mouse.get_pos()

捕獲了 mx 和 my 的位置後,便使用 Surface 物件上的 bilt() 函式在這些座標處渲染影像。

示例

以下程式在移動的滑鼠游標位置連續渲染給定的影像。

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()
廣告