
用户可通过键盘输入来操控游戏中角色的运动,取得键盘事件的方法有以下两种 :
常用的按键与键盘常数对应表 :
按下右箭头键,蓝色小球会 向 右移动:按住右箭头键不放 , 球体会快速 向 右移
动, 若到达边界则停止移动:按左箭头键,蓝色小球会 向 左移动 ,到达边界则 停止。
import pygame pygame.init()
screen = pygame.display.set_mode((640, 70))
pygame.display.set_caption("键盘事件") background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255)) ball = pygame.Surface((30,30)) #建立球的矩形背景区
ball.fill((255,255,255)) #矩形区域背景为白色
pygame.draw.circle(ball, (0,0,255), (15,15), 15, 0) #画蓝色球 rect1 = ball.get_rect() #取得球的矩形背景区域
rect1.center = (320,35) #球的初始位置
x, y = rect1.topleft #球左上角坐标
dx = 5 #球移动距离 clock = pygame.time.Clock() running = True
while running:
clock.tick(30) #每秒执行30次
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed() #检查按键是按下
if keys[pygame.K_RIGHT] and rect1.right < screen.get_width(): #按向右键且未达右边界
rect1.centerx += dx #向右移动
elif keys[pygame.K_LEFT] and rect1.left > 0: #按向左键且未达左边界
rect1.centerx -= dx #向左移动 screen.blit(background, (0,0)) #清除绘图窗口
screen.blit(ball, rect1.topleft)
pygame.display.update()
pygame.quit()
鼠标事件
游戏中的角色除了可用键盘来操作外,还可以用鼠标来操作。鼠标事件包括鼠
标按键事件及鼠标移动事件两大类。
开始时蓝色球不会移动,单击或按下鼠标左键后,移动 鼠 标则球会跟着 鼠标移
动;按鼠标右键后 , 球不会跟着鼠标移动 。
import pygame pygame.init()
screen = pygame.display.set_mode((640, 300))
pygame.display.set_caption("鼠标移动事件") background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255)) ball = pygame.Surface((30,30)) #建立球的矩形背景绘图区
ball.fill((255,255,255)) #矩形区域背景为白色
pygame.draw.circle(ball, (0,0,255), (15,15), 15, 0) #画蓝色实心圆作为球体 rect1 = ball.get_rect() #取得球的矩形背景区域
rect1.center = (320,150) #设置球的起始位置
x, y = rect1.topleft #球左上角坐标 clock = pygame.time.Clock() running = True
playing = False #开始时球不能移动
while running:
clock.tick(30) #每秒执行30次
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
buttons = pygame.mouse.get_pressed()
if buttons[0]: #按下左键后拖动鼠标球可移动
playing = True
elif buttons[2]: #按下右键后拖动鼠标球不能移动
playing = False
if playing == True: #球可移动状态
mouses = pygame.mouse.get_pos() #取得鼠标坐标
rect1.centerx = mouses[0] #把鼠标的x坐标作为球中心的X坐标
rect1.centery = mouses[1] #把鼠标的y坐标作为球中心的y坐标
screen.blit(background, (0,0)) #清除绘图窗口
screen.blit(ball, rect1.topleft) #重新绘制
pygame.display.update() #显示
pygame.quit()