pygame实现弹力球及其变速效果

yipeiwu_com5年前Python基础

本文实例为大家分享了pygame实现弹力球及其变速效果的具体代码,供大家参考,具体内容如下

期望:

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

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

具体实现:

import pygame
from pygame.locals import *
import sys, random


class Circle(object):
 # 设置Circle类属性
 def __init__(self):
  self.vel_x = 1
  self.vel_y = 1
  self.radius = 20
  self.pos_x, self.pos_y = random.randint(0, 255), random.randint(0, 255)
  self.width = 0
  self.color = 0, 0, 0

 # 球体颜色速度改变方法
 def change_circle(self, number):
  self.color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
  # 防止球体速度方向发生改变
  if self.vel_x < 0:
   self.vel_x = -number
  else:
   self.vel_x = number
  if self.vel_y < 0:
   self.vel_y = -number
  else:
   self.vel_y = number
  # self.vel_x, self.vel_y = number, number 如果仅此句,速度方向会发生改变

 def circle_run(self):
  # 防止球体超出游戏界面框体
  if self.pos_x > 580 or self.pos_x < 20:
   self.vel_x = -self.vel_x

  if self.pos_y > 480 or self.pos_y < 20:
   self.vel_y = -self.vel_y
  self.pos_x += self.vel_x
  self.pos_y += self.vel_y
  pos = self.pos_x, self.pos_y
  pygame.draw.circle(screen, self.color, pos, self.radius, self.width)

pygame.init()
screen = pygame.display.set_mode((600, 500))
# Circle实例
circle1 = Circle()

while True:
 for event in pygame.event.get():
  if event.type == QUIT:
   sys.exit()
  elif event.type == KEYUP:
   if event.key == pygame.K_1:
    circle1.change_circle(1)
   elif event.key == pygame.K_2:
    circle1.change_circle(2)
   elif event.key == pygame.K_3:
    circle1.change_circle(3)
   elif event.key == pygame.K_4:
    circle1.change_circle(4)

 screen.fill((0, 0, 100))

 circle1.circle_run()

 pygame.display.update()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pytorch自定义二值化网络层方式

任务要求: 自定义一个层主要是定义该层的实现函数,只需要重载Function的forward和backward函数即可,如下: import torch from torch.aut...

Python实现图片滑动式验证识别方法

Python实现图片滑动式验证识别方法

1 abstract 验证码作为一种自然人的机器人的判别工具,被广泛的用于各种防止程序做自动化的场景中。传统的字符型验证安全性已经名存实亡的情况下,各种新型的验证码如雨后春笋般涌现。目前...

python 中的int()函数怎么用

int(x, [base]) 功能: 函数的作用是将一个数字或base类型的字符串转换成整数。 函数原型: int(x=0) int(x, base=10),base缺省值为10,也就是...

利用python实现AR教程

利用python实现AR教程

先了解如何利用python语言实现以平面和标记物进行姿态估计 本实验只是先实现一个简单的小例子。简单来说就是先识别出图像中的参考面,再拍摄一张目标图像,将参考面顶部的3D模型投影到目标图...

python2 与 pyhton3的输入语句写法小结

什么是输入 咱们在银行ATM机器前取钱时,肯定需要输入密码,对不? 那么怎样才能让程序知道咱们刚刚输入的是什么呢?? 大家应该知道了,如果要完成ATM机取钱这件事情,需要先从键盘中输入一...