python写个小游戏之跳跳球

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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值