Pygame 简明教程
Pygame - Moving an Image
对象的移动是任何计算机游戏的关键方面。计算机游戏通过绘制和擦除一个对象在增量位置创建运动的错觉。下面的代码通过在事件循环中递增 x 坐标位置来绘制图像并用背景色擦除它。
Movement of an object is an important aspect of any computer game. A computer game creates illusion of movement by drawing and erasing an object at incremental position. Following code draws an image by incrementing x coordinate position in an event loop and erasing it with the background color.
Example
image_filename = 'pygame.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((400,300), 0, 32)
pygame.display.set_caption("Moving Image")
img = pygame.image.load(image_filename)
x = 0
while True:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(img, (x, 100))
x= x+0.5
if x > 400:
x = x-400
pygame.display.update()
Output
Pygame 徽标图像开始显示在左边界,并重复向右移。如果到达右边界,则其位置将重置为左侧。
The Pygame logo image starts displaying at left border and repeatedly shifts towards right. If it reaches right border, its position is reset to left.

在以下程序中,图像最初显示在 (0,150) 位置。当用户按下箭头键(左、右、上、下)时,图像以 5 个像素改变其位置。如果发生 KEYDOWN 事件,程序检查键值是否为 K_LEFT、K_RIGHT、K_UP 或 K_DOWN。如果是 K_LEFT 或 K_RIGHT,则 x 坐标改变 +5 或 -5。如果是 K_UP 或 K_DOWN,则 y 坐标的值改变 -5 或 +5。
In the following program, the image is displayed at (0,150) position to begin with. When user presses arrow keys (left, right, up, down), the image changes its location by 5 pixels. If a KEYDOWN event occurs, the program checks if the key value is K_LEFT, K_RIGHT, K_UP or K_DOWN. The x coordinate changes by +5 or -5 if it is K_LEFT or K_RIGHT. Value of y coordinate changes by -5 or +5 if key value is K_UP or K_DOWN.
image_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 arrows")
img = pygame.image.load(image_filename)
x = 0
y= 150
while True:
screen.fill((255,255,255))
screen.blit(img, (x, y))
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_RIGHT:
x= x+5
if event.key == K_LEFT:
x=x-5
if event.key == K_UP:
y=y-5
if event.key == K_DOWN:
y=y+5
pygame.display.update()