Python Pygame实现弹力球及按键变速变色功能

叶初
叶初
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍使用Python和Pygame库实现弹力球运动及交互效果。通过定义Circle类管理球体位置、速度与颜色,代码实现了球体在指定边界内的反弹逻辑。同时,利用键盘按键(1-4)实时改变球体的运动速度和随机颜色,为初学者提供完整的Pygame交互示例。

本文分享了一个使用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()

以上就是本文的全部内容,希望这段代码能对您的Pygame学习有所帮助,欢迎继续支持本站获取更多技术资源。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表