1、功能介绍:
空格键:起跳
键盘:方向键左右可以移动
在线安装命令是:
pip install *****
pip更新命令如下:
python.exe -m pip install --upgrade pip
源码如下,可以直接复制,使用,需要有第三方库pygame、sys。
import pygame
import sys
# 初始化
pygame.init()
# 屏幕设置
screen_width = 400
screen_height = 300
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Jumping Ball Game")
# 颜色设置
black = (0, 0, 0)
ball_color = (0, 128, 255)
class Ball:
def __init__(self, x, y, radius, gravity):
self.x = x
self.y = y
self.radius = radius
self.dx = 0
self.dy = 0
self.gravity = gravity
def jump(self):
if self.y == screen_height - self.radius:
self.dy = -15
def move_left(self):
self.dx = -5
def move_right(self):
self.dx = 5
def stop(self):
self.dx = 0
def update(self):
self.dy += self.gravity
self.y += self.dy
self.x += self.dx
if self.y >= screen_height - self.radius:
self.y = screen_height - self.radius
self.dy = 0
if self.x <= 0:
self.x = 0
elif self.x >= screen_width:
self.x = screen_width
def draw(self):
pygame.draw.circle(screen, ball_color, (int(self.x), int(self.y)), self.radius)
# 创建小球
ball = Ball(screen_width // 2, screen_height - 20, 20, 1)
# 游戏循环
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
ball.jump()
if event.key == pygame.K_LEFT:
ball.move_left()
if event.key == pygame.K_RIGHT:
ball.move_right()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
ball.stop()
# 更新和绘制
ball.update()
screen.fill(black)
ball.draw()
pygame.display.flip()
clock.tick(30)
# 退出游戏
pygame.quit()
sys.exit()