pygame achieves the elastic ball and its variable speed effect

  • 2020-06-07 04:50:16
  • OfStack

This article shares the specific code of pygame to realize the elastic ball and its variable speed effect for your reference. The specific content is as follows

Expectations:

1. The ball bounces when it touches the frame

2. Set the speed button and press it to change the speed and color of the sphere

Specific implementation:


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


class Circle(object):
 #  Set up the Circle Class attribute 
 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

 #  Ball color speed change method 
 def change_circle(self, number):
  self.color = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
  #  Prevent the direction of the ball's velocity from changing 
  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  If you leave it alone, the direction of the velocity will change 

 def circle_run(self):
  #  Prevent the sphere from exceeding the game interface box 
  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 The instance 
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()

Related articles: