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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

鱼丸粗面丶   2021-03-24 我要评论
想了解pygame实现弹力球及其变速效果的相关内容吗,鱼丸粗面丶在本文为您仔细讲解pygame实现弹力球及其变速效果的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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()

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们