Pygame游戏(1) 之 会反弹的闪光方块
首先从简单开始,让我们先知道怎么绘制一个方块
这里我们调用一个pygame的一个函数
pygame.draw.rect(Surface,Color,Rect,width)
说明:
Surface 矩形的绘制屏幕(你想绘制到哪个窗口上)
Color 矩形的绘制颜色
Rect 矩形的绘制区域(pos_x,pos_y,width,height)
pos_x:矩形左上角的x坐标
pos_y; 矩形左上角的y坐标
width: 矩形的宽
height: 矩形的高
width 绘制边缘的宽度,默认为0,即完全填充
第二步,暂时先绘制一个不会变色的方块(注释在代码行的后面)
import pygame,sys #导入函数库
from pygame.locals import *
pygame.init() #初始化各个模块
screen = pygame.display.set_mode((600,500)) #创建窗口
pygame.display.set_caption("方块") #设置标题
backcolor = (255,255,255) #背景颜色的RGB值
while True: #将事件置于循环之中无限执行
for event in pygame.event.get(): #获取事件
if event.type == QUIT: #按下窗口左上角的关闭按钮
sys.exit() #退出程序
elif event.type == KEYDOWN: #按下键盘事件
if event.key == pygame.K_ESCAPE: #按下ESC键
sys.exit() #退出程序
screen.fill(backcolor) #填充背景
color = (120,120,120) #方块的颜色
pos = (100,100,50,50) #矩形的大小和初始的左上角坐标
pygame.draw.rect(screen,color,pos,0) #绘制方块
pygame.display.update() #更新屏幕
这一步应该很顺利吧
有了这一步的基础,接下去我们就让方块接触到窗口边界后反弹并且一直在变颜色
第三步:加入随机函数让方块变色和设置方块反弹的代码(注释在代码行的后面)
import pygame,sys,random
from pygame.locals import *
pygame.init() #初始化游戏
screen = pygame.display.set_mode((600,500)) #创建窗口
pygame.display.set_caption("会移动的闪光方块") #设置标题
backcolor = (255,255,255) #背景颜色RGB
pos_x = 300 #起始坐标x像素位置
pos_y = 250
vel_x = 0.5 #设置x轴方向单位速度
vel_y = 0.5
while True: #将事件置于循环之中无限执行
for event in pygame.event.get(): #获取事件
if event.type == QUIT: #按下窗口左上角的关闭按钮
sys.exit() #退出程序
elif event.type == KEYDOWN: #按下键盘事件
if event.key == pygame.K_ESCAPE: #按下空格键
sys.exit() #退出程序
screen.fill(backcolor) #填充背景
pos_x += vel_x #x轴方向每次移动单位距离
pos_y += vel_y
if pos_x > 500 or pos_x < 0: #到达左右边界后 速度反向
vel_x = -vel_x
if pos_y > 400 or pos_y < 0: #胆大上下边界后 速度反向
vel_y = -vel_y
r = random.randint(0,255) #随机函数生成数字
g = random.randint(0,255)
b = random.randint(0,250)
color = (r,g,b)
pos = (pos_x,pos_y,100,100) #左上角坐标,长度,宽度
pygame.draw.rect(screen,color,pos,0) #绘制完全填充的矩形
pygame.display.update() #更新屏幕
好了,是不是觉得很有意思呢