Python:pygame游戏编程之旅二(自由移动的小球)
2012-04-15 17:09
871 查看
本节实现一个在窗口中自由运动的小球程序,做了详细注释,不多做解释了。
代码:
测试:
动画程序,抓几张不同时刻的图片。
1、
2、
3、
PS:
有朋友说球速度还是太快了,此时可以加个定时器控制一下,如下:
代码:
# -*- coding:utf-8 -*- import sys import pygame from pygame.locals import * def play_ball(): pygame.init() #窗口大小 window_size = (width, height) =(700, 500) #小球运行偏移量[水平,垂直],值越大,移动越快 speed = [1, 1] #窗口背景色RGB值 color_black = (0, 0, 139) #设置窗口模式 screen = pygame.display.set_mode(window_size) #设置窗口标题 pygame.display.set_caption('运动的小球') #加载小球图片 ball_image = pygame.image.load('ball.gif') #获取小球图片的区域开状 ball_rect = ball_image.get_rect() while True: #退出事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() #使小球移动,速度由speed变量控制 ball_rect = ball_rect.move(speed) #当小球运动出窗口时,重新设置偏移量 if (ball_rect.left < 0) or (ball_rect.right > width): speed[0] =- speed[0] if (ball_rect.top < 0) or (ball_rect.bottom > height): speed[1] =- speed[1] #填充窗口背景 screen.fill(color_black) #在背景Surface上绘制 小球 screen.blit(ball_image, ball_rect) #更新窗口内容 pygame.display.update() if __name__ == '__main__': play_ball()
测试:
动画程序,抓几张不同时刻的图片。
1、
2、
3、
PS:
有朋友说球速度还是太快了,此时可以加个定时器控制一下,如下:
# -*- coding:utf-8 -*- import sys import pygame from pygame.locals import * def play_ball(): pygame.init() #窗口大小 window_size = (width, height) =(700, 500) #小球运行偏移量[水平,垂直],值越大,移动越快 speed = [1, 1] #窗口背景色RGB值 color_black = (0, 0, 139) #设置窗口模式 screen = pygame.display.set_mode(window_size) #设置窗口标题 pygame.display.set_caption('运动的小球') #加载小球图片 ball_image = pygame.image.load('ball.gif') #获取小球图片的区域开状 ball_rect = ball_image.get_rect() frames_per_sec = 10 fps_clock = pygame.time.Clock() while True: #退出事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() #使小球移动,速度由speed变量控制 ball_rect = ball_rect.move(speed) #当小球运动出窗口时,重新设置偏移量 if (ball_rect.left < 0) or (ball_rect.right > width): speed[0] =- speed[0] if (ball_rect.top < 0) or (ball_rect.bottom > height): speed[1] =- speed[1] #填充窗口背景 screen.fill(color_black) #在背景Surface上绘制 小球 screen.blit(ball_image, ball_rect) #更新窗口内容 pygame.display.update() fps_clock.tick(frames_per_sec) if __name__ == '__main__': play_ball()
相关文章推荐
- Python:pygame游戏编程之旅二(自由移动的小球)
- Python:pygame游戏编程之旅二(自由移动的小球)
- Python:pygame游戏编程之旅三(玩家控制的小球)
- Python:pygame游戏编程之旅三(玩家控制的小球)
- Python:pygame游戏编程之旅三(玩家控制的小球)
- 用Python和Pygame写游戏-从入门到精通(10)方向移动
- 【python游戏编程之旅】第四篇---pygame中加载位图与常用的数学函数。
- 【python游戏编程之旅】第七篇---pygame中的冲突检测技术
- 【python游戏编程之旅】第一篇---初识pygame
- Python:pygame游戏编程之旅六(游戏中的声音处理)
- 【python游戏编程之旅】第六篇---pygame中的Sprite(精灵)模块和加载动画
- 【python游戏编程之旅】第三篇---pygame事件与设备轮询
- Python:pygame游戏编程之旅六(游戏中的声音处理)
- Python:pygame游戏编程之旅一(Hello World)
- 【python游戏编程之旅】第八篇---pygame游戏开发常用数据结构
- Python:pygame游戏编程之旅七(pygame基础知识讲解1)
- 【python游戏编程之旅】第二篇--pygame中的IO、数据
- Python:pygame游戏编程之旅四(游戏界面文字处理)
- Python:pygame游戏编程之旅七(pygame基础知识讲解1)
- Python:pygame游戏编程之旅五(游戏界面文字处理详解)