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设计】。

相关文章

python数组复制拷贝的实现方法

本文实例讲述了python数组复制拷贝的实现方法。分享给大家供大家参考。具体分析如下: python中直接通过等号赋值实际上只是引用地址的传递 如: a = [1,2,3,4,5]...

Python 计算任意两向量之间的夹角方法

Python 计算任意两向量之间的夹角方法

如图所示,我们要计算任意两个向量之间的夹角。 (图中的坐标数字是估计值,随手给定) python代码如下 import math AB = [1,-3,5,-1] CD = [...

Python 基础知识之字符串处理

Python字符串处理 字符串输入: my_string = raw_input("please input a word:") 字符串判断: (1) 判断是不是纯字母 my_...

解析Python3中的Import

Python import的搜索路径 import的搜索路径为: 搜索「内置模块」(built-in module) 搜索 sys.path 中的路径 而sys.path在...

python随机取list中的元素方法

python随机取list中的元素方法

随机取 list 中的元素 random.sample import random a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = random.sample...