python学习 之 pygame学习01
看了几天 pygame,捣鼓出了一个简单的小游戏(也经历了四个版本),比较简陋(哭)
#author: Cao Zhanxiang
#time: 2020/7/10
#function: V4,让弹球真正成为一个游戏
import pygame
import sys
import time
from random import randint
# 速度,x,y方向分速度
Speed = [7, 7]
# 定义RGB的黑色
BLACK = (0, 0, 0)
# 定义宽高
Width = 1000
Height = 600
# 定义初始成绩
Score = -1 # 为什么是-1,因为写0开始成绩是1(哭),也不知道为啥
# 初始化操作
pygame.init()
Screen = pygame.display.set_mode((Width, Height))
pygame.display.set_caption("BounceBall")
# Surface对象及Rect对象的创建
# pygame的Surface对象涵盖所有导入的图像
# get_rect()返回一个覆盖图像矩形(外切矩形)的Rect对象,可获得矩形位置信息
# 具体操作的时候,还是操作Rect对象(矩形)
Ball = pygame.image.load("littleball.gif")
BallRect = Ball.get_rect()
# 本来想画小星星的,但找不到合适的资源(哭)
Star = pygame.image.load("littleball.gif")
StarRect = Star.get_rect()
# 设置成绩字体
ScoreFont = pygame.font.SysFont('宋体', 30, True)
# 设置时间字体
TimeFont = pygame.font.SysFont('宋体', 30, True)
# 帧率,frames per second
FPS = 300
# Clock对象,用于操纵时间
fClock = pygame.time.Clock()
# 随机位置
RandX = randint(0, Width - StarRect.width)
RandY = randint(0, Height - StarRect.height)
# 开始时间
BeginTime = time.time()
while True:
# 退出信号
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 根据键盘输入更改速度
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Speed[0] -= 1
elif event.key == pygame.K_RIGHT:
Speed[0] += 1
elif event.key == pygame.K_UP:
Speed[1] -= 1
elif event.key == pygame.K_DOWN:
Speed[1] += 1
# 一直在运动,速度在边界处变化,实现反弹
BallRect = BallRect.move(Speed[0], Speed[1])
if BallRect.left < 0 or BallRect.right > Width:
Speed[0] = -Speed[0]
if BallRect.top < 0 or BallRect.bottom > Height:
Speed[1] = -Speed[1]
# 若球碰到星星相碰
if pygame.Rect.colliderect(BallRect, StarRect):
Score += 1
RandX = randint(0, Width - StarRect.width)
RandY = randint(0, Height - StarRect.height)
# 将星星位置移动
StarRect.top = RandY
StarRect.left = RandX
# 底色填充黑色,因为默认路径上会残留之前的图(像turtle一样)
Screen.fill(BLACK)
# 我们移动的是BallRect,但看到的却应该是Ball,所以将Ball附在BallRect上,blit:位块传送
Screen.blit(Ball, BallRect)
Screen.blit(Star, StarRect)
# 绘制游戏得分
Screen.blit(ScoreFont.render('Score: %d' % Score, True, [255, 0, 0]), [20, 20])
# 绘制剩余时间
Screen.blit(TimeFont.render('Time Left: %d s' % (60 - time.time() + BeginTime), True, [255, 0, 0]), [800, 20])
# 更新图像
pygame.display.update()
fClock.tick(FPS)
# 如果剩余时间没了,退出循环
if (60 - time.time() + BeginTime) <= 0:
break
# 绘制最终成绩
Screen.fill(BLACK)
Screen.blit(ScoreFont.render('Final Score: %d' % Score, True, [255, 0, 0]), [420, 270])
pygame.display.update()
# 等待退出程序
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
用户操作:
上下左右四个按键,改变速度,上使竖直方向分速度(正方向向下,而且注意是速度,不是速率)增加,其他同理,每碰到目标分数加一,限时60秒
效果展示:
我最好的成绩只有56分(菜的一批)。
有什么错误,欢迎批评指正(新手上路)。