用户:
QinJerry查看:0 回复:0 评论:0 创建时间:2019-08-06T18:11:18
【作品展示】
【作品介绍】
开始点击空格开始游戏,←、→或a、d操控绿方块,躲避黑方块
【作品源代码】
#coding:utf-8
#导入模块
import pygame,sys,random
#初始化pygame
pygame.init()
#建立一个384x554像素的窗口,用canvas变量接收
canvas = pygame.display.set_mode([384,554])
#给窗口取名为“控制绿方块”
pygame.display.set_caption('控制绿方块')
#关键变量赋值
y,y2,y3,y4,u,x,ks,score = -96,-338,-580,-822,1,0,1,0
#定义hit函数,用于检测碰撞
def hit(a,y,y2,y3,y4):
return a>-96 and a<96 and 458>y-96 and 458<y+96 or a>0 and a<192 and 458>y2-96 and 458<y2+96 or\
a>96 and a<288 and 458>y3-96 and 458<y3+96 or a>192 and a<384 and 458>y4-96 and 458<y4+96
#给屏幕覆盖白色
canvas.fi喵])
#传输文字
tqlf = pygame.font.SysFont('simhei',40)
canvas.blit(tqlf.render('控制绿方块',1,[0,0,0]),[90,191])
canvas.blit(tqlf.render('按空格开始游戏',1,[255,0,0]),[53,265])
pygame.display.update()
#游戏副循环,检测玩家是否按下空格
while ks:
#检测状态
for e in pygame.event.get():
#如果状态为12号(也就是点击屏幕又上角的×),结束程序
if e.type == 12:
sys.exit()
#如果状态为2号,说明键盘按下了,继续检测是不是空格键
if e.type == 2 and e.key == 32:
#如果是空格键,退出循环
ks = 0
#添加字体
qwqa = pygame.font.Font(None,30)
#游戏主循环
while True:
#用白色覆盖屏幕
canvas.fi喵])
#传输敌方方块
pygame.draw.rect(canvas,[0,0,0],[0,y,96,96])
pygame.draw.rect(canvas,[0,0,0],[96,y2,96,96])
pygame.draw.rect(canvas,[0,0,0],[192,y3,96,96])
pygame.draw.rect(canvas,[0,0,0],[288,y4,96,96])
#传输分数
canvas.blit(qwqa.render('score:'+str(score),1,[157,9,157]),[0,0])
#如果变量u不为0,控制敌方方块移动和加分数
if u:
y,y2,y3,y4 = y+1,y2+1,y3+1,y4+1
if y==650:
y=-96
score+=1
elif y2==650:
y2=-96
score+=1
elif y3==650:
score+=1
y3=-96
elif y4==650:
score+=1
y4=-96
#调用hit函数检测碰撞,如果碰撞u赋值为0
if hit(x,y,y2,y3,y4):
u = 0
#画我方方块
pygame.draw.rect(canvas,[0,255,0],[x,458,96,96])
#检测状态
for e in pygame.event.get():
#如果为12号退出状态,结束程序
if e.type == 12:
sys.exit()
#如果u不为0,执行if下语句
if u:
#如果键盘按下
if e.type==2:
#如果按下的是←或a,我方方块向左移动96像素
if e.key == pygame.K_LEFT and x>0 or e.key == pygame.K_a and x>0:
x-=96
#如果按下的是→或d,我方方块向右移动96像素
if e.key == pygame.K_RIGHT and x < 288 or e.key == pygame.K_d and x != 288:
x+=96
#如果u为0并且键盘按下并且按下的是空格
if not u and e.type == 2 and e.key == pygame.K_SPACE:
y,y2,y3,y4,u,x,ks,score = -96,-338,-580,-822,1,0,1,0
#传输三条红线
pygame.draw.rect(canvas,[255,0,0],[96,0,1,650])
pygame.draw.rect(canvas,[255,0,0],[192,0,1,650])
pygame.draw.rect(canvas,[255,0,0],[288,0,1,650])
#如果u为0,传输文字“按空格重新开始”
if not u:
canvas.blit(tqlf.render('按空格重新开始',1,[0,0,255]),[53,233])
#停顿2毫米继续运行,不写程序会特别快
pygame.time.delay(2)
#刷新屏幕类容,不写窗口永远是黑色的
pygame.display.update()
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端: