看看效果吧!代码
看看效果吧! 代码# 安装以下几个库
# pip install pygame
# pip install pgzero
# pip install keyboard
import pgzrun # 导入游戏库
import keyboard
WIDTH = 640 # 设置窗口宽度
HEIGHT = 480 # 设置窗口高度
TITLE = '弹跳的小球' # 窗口标题
r = 20 # 设置小球的半径
c_x = 180 # 设置小球的起始坐标x
c_y = 100 # 设置小球的起始坐标y
r_x = 0 #滑块的移动
speed_x = 3 # 设置小球x轴方向
speed_y = 5 #设置小球y轴方向
r_speed = 5 #设置滑块的移动速度
flag = 1 # 设置一个标志,来判断游戏失败
# 绘制函数
def draw():
rect = Rect((260 + r_x, 330), (120, 20)) #矩形的坐标,大小
if flag:
screen.fill('yellow') # 修改背景颜色
# screen.draw.circle((400,300),100,'white')# 画一个空心圆
screen.draw.filled_circle((c_x,c_y),r,'red') # 画一个实心圆
# screen.draw.rect(rect,'red') # 画一个空心矩形
screen.draw.filled_rect(rect,"red") # 画一个实心矩形
else:
screen.clear() # 清屏
screen.draw.text('Game Over!',(130,150),fontsize=100,color='red') #画文本
screen.draw.text('游戏失败',(130,250),fontsize=100,fontname="simhei",color='yellow')
# 更新函数,当程序运行后,每帧都会执行一次该函数
def update():
global c_x,c_y,speed_x,speed_y,r,r_x,flag # 表示全局变量
c_x += speed_x # 小球移动
c_y += speed_y
if c_x >= WIDTH -r or c_x <= r: # 如果小球撞到窗口就改变方向
speed_x = -speed_x
if c_y > HEIGHT - r or c_y <= r:
speed_y = -speed_y
if keyboard.is_pressed('a') and r_x >= -260: # 当按下a键,滑块左移,并当碰到窗口左壁时停止左移
r_x -= r_speed
if keyboard.is_pressed('d') and r_x <= 260: # 当按下d键,滑块右移,并当碰到窗口右壁时停止右移
r_x += r_speed
if c_x >= 260 + r_x and c_x <= 380 + r_x and c_y >= 325 and c_y <= 330: #如果小球碰到滑块就反弹
speed_x = -speed_x
speed_y = -speed_y
if c_y == HEIGHT - r: # 如果小球碰到窗口底端,标志位置零,游戏结束
flag = 0
pgzrun.go() # 开始执行游戏



