分享一个pygame 弹力球的实现实例

零下一度
发布: 2017-07-03 09:38:35
原创
2596人浏览过

期望:

1.球体接触到框体后反弹

2.设置速度按键,按下后改变球体速度、颜色状态

具体实现:

 1 import pygame 2 
 from pygame.locals import * 3 
 import sys, random 4  5  6 class Circle(object): 7     
 #   设置Circle类属性 8     def __init__(self): 9         
 self.vel_x = 110         self.vel_y = 111         
 self.radius = 2012         
 self.pos_x, self.pos_y = random.randint(0, 255), random.randint(0, 255)13         
 self.width = 014         self.color = 0, 0, 015 16     
 #   球体颜色速度改变方法17     def change_circle(self, number):18         
 self.color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)19         
 #   防止球体速度方向发生改变20         if self.vel_x < 0:21             
 self.vel_x = -number22         else:23             self.vel_x = number24         
 if self.vel_y < 0:25             self.vel_y = -number26         else:27             
 self.vel_y = number28         
 #   self.vel_x, self.vel_y = number, number  如果仅此句,速度方向会发生改变   
 def circle_run(self):31         #   防止球体超出游戏界面框体32         
 if self.pos_x > 580 or self.pos_x < 20:33             self.vel_x = -self.vel_x    
 if self.pos_y > 480 or self.pos_y < 20:36             self.vel_y = -self.vel_y37         
 self.pos_x += self.vel_x38         self.pos_y += self.vel_y39         
 pos = self.pos_x, self.pos_y40         
 ygame.draw.circle(screen, self.color, pos, self.radius, self.width)41 42 pygame.init()43 
 screen = pygame.display.set_mode((600, 500))44 
 #   Circle实例45 circle1 = Circle()46 47 while True:48     
 for event in pygame.event.get():49         if event.type == QUIT:50             
 sys.exit()51         elif event.type == KEYUP:52             
 if event.key == pygame.K_1:53                 
 circle1.change_circle(1)54             
 elif event.key == pygame.K_2:55                 
 circle1.change_circle(2)56             
 elif event.key == pygame.K_3:57                 
 circle1.change_circle(3)58             
 elif event.key == pygame.K_4:59                 
 circle1.change_circle(4)60 61     
 screen.fill((0, 0, 100))62 63     
 circle1.circle_run()64 65     
 pygame.display.update()
登录后复制

 

以上就是分享一个pygame 弹力球的实现实例的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号