|
上一节实现了小球自由移动,本节在上节基础上增加通过方向键控制小球运动,并为游戏增加了背景图片。
一、实现:
# -*- coding:utf-8 -*-import osimport sysimport pygamefrom pygame.locals import *def load_image(pic_name):'''Function:图片加载函数Input:NONEOutput: NONEauthor: socratesblog:http://blog.csdn.net/dyx1024date:2012-04-15'''#获取当前脚本文件所在目录的绝对路径current_dir = os.path.split(os.path.abspath(__file__))[0]#指定图片目录path = os.path.join(current_dir, 'image', pic_name)#加载图片return pygame.image.load(path).convert()def control_ball(event):'''Function:控制小球运动Input:NONEOutput: NONEauthor: socratesblog:http://blog.csdn.net/dyx1024date:2012-04-15''' #相对偏移坐标speed = [x, y] = [0, 0]#速度speed_offset = 1#当方向键按下时,进行位置计算if event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:speed[0] -= speed_offsetif event.key == pygame.K_RIGHT:speed[0] = speed_offsetif event.key == pygame.K_UP:speed[1] -= speed_offsetif event.key == pygame.K_DOWN:speed[1] = speed_offset#当方向键释放时,相对偏移为0,即不移动if event.type in (pygame.KEYUP, pygame.K_LEFT, pygame.K_RIGHT, pygame.K_DOWN) :speed = [0, 0]return speeddef play_ball():'''Function:主函数Input:NONEOutput: NONEauthor: socratesblog:http://blog.csdn.net/dyx1024date:2012-04-15''' pygame.init()#窗口大小window_size = Rect(0, 0, 700, 500)#设置窗口模式screen = pygame.display.set_mode(window_size.size)#设置窗口标题pygame.display.set_caption('运动的小球(2)-通过方向键控制小球移动')#加载小球图片ball_image = load_image('ball.gif')#加载窗口背景图片back_image = load_image('back_image.jpg')#获取小球图片的区域开状ball_rect = ball_image.get_rect()while True:#退出事件处理for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()#使小球移动,速度由speed变量控制cur_speed = control_ball(event)#Rect的clamp方法使用移动范围限制在窗口内ball_rect = ball_rect.move(cur_speed).clamp(window_size)#设置窗口背景screen.blit(back_image, (0, 0))#在背景Surface上绘制 小球screen.blit(ball_image, ball_rect)#更新窗口内容pygame.display.flip()if __name__ == '__main__':play_ball()
二、测试 1、开始运行,小球位于窗口(0, 0)坐标处。
2、按下向右方向键,使用小球向右移动
3、按下向下方向键,使用小球向下移动。
|
|
|