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


本文摘自php中文网,作者零下一度,侵删。

期望:

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

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

具体实现:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

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 弹力球的实现实例的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python的注释有哪几种

anaconda安装后找不到怎么办

Python对文件操作采用的统一步骤是什么

Python怎么判断列表为空

Python语言语句块的标记是什么?

Python文件扩展名是什么

Python怎么求最大值最小值

Python3怎么安装库

零基础能学Python

Python输出结果怎么换行

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...