pygame使用ios键盘怎么拉长事件移动方块但是方块只是拉长

用Python和Pygame写游戏-从入门到精通(2)
本文转载自:http://eyehere.net/2011/python-pygame-novice-professional-2/
上次我们试着写了一个最简单的Pygame程序并且解释了一个大概的框架,这次就Pygame中也是游戏中最关键(……好吧,也许并不是最关键,但绝对是至关重要的一项)的事件来展开。
此图为一个用Pygame开发的游戏,或许有些简陋,但是只要你有爱,什么都能出来!
事件是什么,其实从名称来看我们就能想到些什么,而且你所想到的基本就是事件的真正意思了。我们上一个程序,会一直运行下去,直到你关闭窗口而产生了一个QUIT事件,Pygame会接受用户的各种操作(比如按键盘,移动鼠标等)产生事件。事件随时可能发生,而且量也可能会很大,Pygame的做法是把一系列的事件存放一个队列里,逐个的处理。
上个程序中,使用了pygame.event.get()来处理所有的事件,这好像打开大门让所有的人进入。如果我们使用pygame.event.wait(),Pygame就会等到发生一个事件才继续下去,就好像你在门的猫眼上盯着外面一样,来一个放一个……一般游戏中不太实用,因为游戏往往是需要动态运作的;而另外一个方法pygame.event.poll()就好一些,一旦调用,它会根据现在的情形返回一个真实的事件,或者一个“什么都没有”。下表是一个常用事件集:
用户按下关闭按钮
ATIVEEVENT
Pygame被激活或者隐藏
gain, state
键盘被按下
unicode, key, mod
键盘被放开
MOUSEMOTION
pos, rel, buttons
MOUSEBUTTONDOWN
pos, button
MOUSEBUTTONUP
pos, button
JOYAXISMOTION
游戏手柄(Joystick or pad)移动
joy, axis, value
JOYBALLMOTION
游戏球(Joy ball)?移动
joy, axis, value
JOYHATMOTION
游戏手柄(Joystick)?移动
joy, axis, value
JOYBUTTONDOWN
游戏手柄按下
joy, button
JOYBUTTONUP
游戏手柄放开
joy, button
VIDEORESIZE
Pygame窗口缩放
size, w, h
VIDEOEXPOSE
Pygame窗口部分公开(expose)?
触发了一个用户事件
如果你想把这个表现在就背下来,当然我不会阻止你,但实在不是个好主意,在实际的使用中,自然而然的就会记住。我们先来写一个可以把所有方法输出的程序,它的结果是这样的。
我们这里使用了wait(),因为这个程序在有事件发生的时候动弹就可以了。还用了font模块来显示文字(后面会讲的),下面是源代码:
12345678910111213141516171819202122232425262728293031323334import pygamefrom pygame.locals import *from sys import exit&pygame.init()SCREEN_SIZE = (640, 480)screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)&font = pygame.font.SysFont(&arial&, 16);font_height = font.get_linesize()event_text = []&while True:&&&&&event = pygame.event.wait()&&&&event_text.append(str(event))&&&&#获得时间的名称&&&&event_text = event_text[-SCREEN_SIZE[1]/font_height:]&&&&#这个切片操作保证了event_text里面只保留一个屏幕的文字&&&&&if event.type == QUIT:&&&&&&&&exit()&&&&&screen.fill((255, 255, 255))&&&&&y = SCREEN_SIZE[1]-font_height&&&&#找一个合适的起笔位置,最下面开始但是要留一行的空&&&&for text in reversed(event_text):&&&&&&&&screen.blit( font.render(text, True, (0, 0, 0)), (0, y) )&&&&&&&&#以后会讲&&&&&&&&y-=font_height&&&&&&&&#把笔提一行&&&&&pygame.display.update()小贴士:&书上说,如果你把填充色的(0, 0, 0)改为(0, 255, 0),效果会想黑客帝国的字幕雨一样,我得说,实际试一下并不太像……不过以后你完全可以写一个以假乱真甚至更酷的!这个程序在你移动鼠标的时候产生了海量的信息,让我们知道了Pygame是多么的繁忙……我们第一个程序那样是调用pygame.mouse.get_pos()来得到当前鼠标的位置,而现在利用事件可以直接获得!处理鼠标事件MOUSEMOTION事件会在鼠标动作的时候发生,它有三个参数:和MOUSEMOTION类似的,我们还有MOUSEBUTTONDOWN和MOUSEBUTTONUP两个事件,看名字就明白是什么意思了。很多时候,你只需要知道鼠标点下就可以了,那就可以不用上面那个比较强大(也比较复杂)的事件了。它们的参数为:处理键盘事件键盘和游戏手柄的事件比较类似,为KEYDOWN和KEYUP,下面有一个例子来演示使用方向键移动一些东西。Python
background_image_filename
'sushiplate.jpg'
pygame.locals
pygame.init()
pygame.display.set_mode((640,
background
pygame.image.load(background_image_filename).convert()
pygame.event.get():
&&&&&&&&if
event.type
&&&&&&&&&&
&&&&&&&&if
event.type
&&&&&&&&&&&&#键盘有按下?
&&&&&&&&&&&&if
&&&&&&&&&&&&&&&&#按下的是左方向键的话,把x坐标减一
&&&&&&&&&&&&&&&&move_x
&&&&&&&&&&&&elif
&&&&&&&&&&&&&&&&#右方向键则加一
&&&&&&&&&&&&&&&&move_x
&&&&&&&&&&&&elif
&&&&&&&&&&&&&&&&#类似了
&&&&&&&&&&&&&&&&move_y
&&&&&&&&&&&&elif
&&&&&&&&&&&&&&&&move_y
&&&&&&&&elif
event.type
&&&&&&&&&&&&#如果用户放开了键盘,图就不要动了
&&&&&&&&&&&&move_x
&&&&&&&&&&&&move_y
&&&&&&&&#计算出新的坐标
&&&&&&&&x+=
&&&&&&&&y+=
&&&&&&&&screen.fill((0,0,0))
&&&&&&&&screen.blit(background,
&&&&&&&&#在新的位置上画图
&&&&&&&&pygame.display.update()
当我们运行这个程序的时候,按下方向键就可以把背景图移动,但是等等!为什么我只能按一下动一下啊……太不好试了吧?!用脚掌考虑下就应该按着就一直动下去才是啊!?Pygame这么垃圾么……
哦,真是抱歉上面的代码有点小bug,但是真的很小,你都不需要更改代码本身,只要改一下缩进就可以了,你可以发现么?Python本身是缩进编排来表现层次,有些时候可能会出现一点小麻烦,要我们自己注意才可以。
KEYDOWN和KEYUP的参数描述如下:
并不是所有的事件都需要处理的,就好像不是所有登门造访的人都是我们欢迎的一样。比如,俄罗斯方块就无视你的鼠标,而在游戏场景切换的时候,你按什么都是徒劳的。我们应该有一个方法来过滤掉一些我们不感兴趣的事件(当然我们可以不处理这些没兴趣的事件,但最好的方法还是让它们根本不进入我们的事件队列,就好像在门上贴着“XXX免进”一样),我们使用pygame.event.set_blocked(事件名)来完成。如果有好多事件需要过滤,可以传递一个列表,比如pygame.event.set_blocked([KEYDOWN,
KEYUP]),如果你设置参数None,那么所有的事件有被打开了。与之相对的,我们使用pygame.event.set_allowed()来设定允许的事件。
通常玩家做什么,Pygame就产生对应的事件就可以了,不过有的时候我们需要模拟出一些事件来,比如录像回放的时候,我们就要把用户的操作再现一遍。
为了产生事件,必须先造一个出来,然后再传递它:
1234my_event = pygame.event.Event(KEYDOWN, key=K_SPACE, mod=0, unicode=u' ')#你也可以像下面这样写,看起来比较清晰(但字变多了……)my_event = pygame.event.Event(KEYDOWN, {&key&:K_SPACE, &mod&:0, &unicode&:u' '})pygame.event.post(my_event)你甚至可以产生一个完全自定义的全新事件,有些高级的话题,暂时不详细说,仅用代码演示一下:Python
CATONKEYBOARD
USEREVENT+1
pygame.event.Event(CATONKEYBOARD,
message=&Bad
pgame.event.post(my_event)
#然后获得它
pygame.event.get():
event.type
CATONKEYBOARD:
&&&&&&&&print
event.message
这次的内容很多,又很重要,一遍看下来云里雾里或者看的时候明白看完了全忘了什么的估计很多,慢慢学习吧~~多看看动手写写,其实都很简单。
下次讲解显示的部分。
看过本文的人也看了:
我要留言技术领域:
取消收藏确定要取消收藏吗?
删除图谱提示你保存在该图谱下的知识内容也会被删除,建议你先将内容移到其他图谱中。你确定要删除知识图谱及其内容吗?
删除节点提示无法删除该知识节点,因该节点下仍保存有相关知识内容!
删除节点提示你确定要删除该知识节点吗?少儿编程分享:手把手教你用Python编写俄罗斯方块(七)_百度文库
您的浏览器Javascript被禁用,需开启后体验完整功能,
享专业文档下载特权
&赠共享文档下载特权
&10W篇文档免费专享
&每天抽奖多种福利
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
少儿编程分享:手把手教你用Python编写俄罗斯方块(七)
码趣学院致力于为国内青少儿提供一套专业、...|
总评分0.0|
&&参数的调试是游戏关键的部分,直接决定了游戏的可玩性噢!
阅读已结束,下载本文需要
定制HR最喜欢的简历
下载文档到电脑,同时保存到云知识,更方便管理
加入VIP
还剩2页未读,
定制HR最喜欢的简历
你可能喜欢转载请注明:@小五义 &http://www.cnblogs.com/xiaowuyi
&& & & &学了这么长时间的Pygame,一直想写个游戏实战一下。看起来很简单的游戏,写其来怎么这么难。最初想写个俄罗斯方块,想了很长时间如何实现,想来想去,也没写出来,于是干脆下载别人的代码来读。后来,要想写一个帮助记忆的挖宝箱的游戏,结果也没完成。唯一完成了就是下面这个小人接金币的游戏,超级简单,通过左右键控制小人移动去接空中下来的金币,接住金币得5分,接不住游戏结束,金币速度会随着level的关数而越来越快。完成这段代码后,我依然觉得这段代码写得很差,确实也是自己对pygame只是掌握了皮毛,对surface、sprite这些理解的还不透彻。这里把代码写出来,有时间的大牛们可以帮助指点一下,让我也有所提高。
# -*- coding: cp936 -*-
@小五义 http://www.cnblogs.com/xiaowuyi
一个超级简单的游戏
左右键控制小人移动去接空中下来的金币,接住金币得5分,接不住游戏结束,金币速度会随着level的关数
而越来越快
import pygame,sys,os,random
pygame.init()
class rect():#画出小人
def __init__(self,filename,initial_position):
self.image=pygame.image.load(filename)
self.rect=self.image.get_rect()
self.rect.topleft=initial_position
class goldrect(pygame.sprite.Sprite):#绘出金币
def __init__(self,gold_position,speed):
pygame.sprite.Sprite.__init__(self)
self.image=pygame.image.load('image\\gold.png')
self.rect=self.image.get_rect()
self.rect.topleft=gold_position
self.speed=speed
def move(self):
self.rect=self.rect.move(self.speed)
def drawback(): #绘出背景图片
my_back=pygame.image.load('image\\qi3.jpg')
bakscreen.blit(my_back,[0,0])
def loadtext(levelnum,score,highscore):#绘出成绩、level、最高分等
my_font=pygame.font.SysFont(None,24)
levelstr='Level:'+str(levelnum)
text_screen=my_font.render(levelstr, True, (255, 0, 0))
bakscreen.blit(text_screen, (650,50))
highscorestr='Higescore:'+str(highscore)
text_screen=my_font.render(highscorestr, True, (255, 0, 0))
bakscreen.blit(text_screen, (650,80))
scorestr='Score:'+str(score)
text_screen=my_font.render(scorestr, True, (255, 0, 0))
bakscreen.blit(text_screen, (650,110))
def loadgameover(scorenum,highscore):#绘出GAME OVER
my_font=pygame.font.SysFont(None,50)
levelstr='GAME OVER'
over_screen=my_font.render(levelstr, True, (255, 0, 0))
bakscreen.blit(over_screen, (300,240))
highscorestr='YOUR SCORE IS '+str(scorenum)
over_screen=my_font.render(highscorestr, True, (255, 0, 0))
bakscreen.blit(over_screen, (280,290))
if scorenum&int(highscore):#写入最高分
highscorestr='YOUR HAVE GOT THE HIGHEST SCORE!'
text_screen=my_font.render(highscorestr, True, (255, 0, 0))
bakscreen.blit(text_screen, (100,340))
highfile=open('highscore','w')
highfile.writelines(str(scorenum))
highfile.close()
def gethighscore(): #读取最高分
if os.path.isfile('highscore'):
highfile=open('highscore','r')
highscore=highfile.readline()
highfile.close()
highscore=0
return highscore
bakscreen=pygame.display.set_mode([800,600])
bakscreen.fill([0,160,233])
pygame.display.set_caption('Dig!Dig!')
drawback()
levelnum=1 #level
scorenum=0 #得分
highscore=gethighscore()#最高分
#记录向左移动步数,用来控制图片
iright=10 #记录向右移动步数,用来控制图片
filename='image\\1.png'
backimg_ren=rect(filename,[x,y])
bakscreen.blit(backimg_ren.image,backimg_ren.rect)
loadtext(levelnum,scorenum,highscore)
goldx=random.randint(50,580)
speed=[0,levelnum]
mygold=goldrect([goldx,100],speed)
pygame.display.update()
while True:
if scorenum&0 and scorenum/50.0==int(scorenum/50.0):#当得分是50的倍数时修改level
levelnum=scorenum/50+1
speed=[0,levelnum]
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
#make gold
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_LEFT]:#按下左键
drawback()
loadtext(levelnum,scorenum,highscore)
if iright & 14 :iright=10
iright=iright+1
filename='image\\'+str(iright)+'.png'
backimg_surface=rect(filename,[x,y])
bakscreen.blit(backimg_surface.image,backimg_surface.rect)
if pressed_keys[pygame.K_RIGHT]:#按下右键
drawback()
loadtext(levelnum,scorenum,highscore)
if ileft & 4 :ileft=0
ileft=ileft+1
filename='image\\'+str(ileft)+'.png'
backimg_surface=rect(filename,[x,y])
bakscreen.blit(backimg_surface.image,backimg_surface.rect)
drawback()
loadtext(levelnum,scorenum,highscore)
mygold.move()
bakscreen.blit(mygold.image,mygold.rect)
backimg_surface=rect(filename,[x,y])
bakscreen.blit(backimg_surface.image,backimg_surface.rect)
if mygold.rect.top&600:#判断金币是否着地,一但着地,游戏结束
loadgameover(scorenum,highscore)
if mygold.rect.colliderect(backimg_surface.rect):#判断金币是否与小人碰撞,如果碰撞表示小人接到金币
scorenum+=5
loadtext(levelnum,scorenum,highscore)
goldx=random.randint(50,580)
mygold=goldrect([goldx,100],speed)
pygame.display.update()
程序中用到的资源可从这里下载:文件名:gold.7z, 访问地址:http://pan.baidu.com/s/1i4s7b1r
阅读(...) 评论()pygame tetromino 俄罗斯方块 - 开源中国社区
当前访客身份:游客 [
当前位置:
发布于 日 20时,
&无详细内容&
代码片段(1)
tetromino1.py&~&12KB&&&&
import pygame,sys,time,random
from pygame.locals import*
winx = 640
winy = 480
boxsize = 20
boardwidth = 10
boardheight = 20
xmargin = int(winx-boardwidth*boxsize)/2
topmargin = int(winy-boardheight*boxsize-5)
templatenum = 5
movedownfreq = 0.1
movesidefreq = 0.15
white = (255,255,255)
black = (0,0,0)
blue = (0,0,255)
yellow = (255,255,0)
green = (0,255,0)
purple = (255,0,255)
red = (255,0,0)
blank = '.'
colors = (yellow,green,purple,red)
stemplate = [['.....',
ztemplate = [['.....',
itemplate = [['..0..',
otemplate = [['.....',
ltemplate = [['.....',
jtemplate = [['.....',
ttemplate = [['.....',
pieces = {'s':stemplate,
'z':ztemplate,
'i':itemplate,
'o':otemplate,
'l':ltemplate,
'j':jtemplate,
't':ttemplate}
def main():
global fpsclock,disp,basicfont,bigfont
pygame.init()
fpsclock = pygame.time.Clock()
disp = pygame.display.set_mode((winx,winy))
pygame.display.set_caption('tetromino')
bigfont = pygame.font.Font('freesansbold.ttf',100)
basicfont = pygame.font.Font('freesansbold.ttf',20)
showtextscreen('Tetromino')
while True:
if random.randint(0,1) == 0:
pygame.mixer.music.load('tetrisb.mid')
pygame.mixer.music.load('tetrisc.mid')
pygame.mixer.music.play(-1,0.0)
pygame.mixer.music.stop()
showtextscreen('Game Over')
def rungame():
board = getblankboard()
lastmovedowntime = time.time()
lastmovesidetime = time.time()
lastfalltime = time.time()
movedown = False
moveleft = False
moveright = False
level, fallfreq = calculate(score)
fallpiece = getnewpiece()
nextpiece = getnewpiece()
while True:
if fallpiece == None:
fallpiece = nextpiece
nextpiece = getnewpiece()
lastfalltime = time.time()
if not validposition(board,fallpiece):
checkforquit()
for event in pygame.event.get():
if event.type == KEYUP:
if (event.key == K_p):
disp.fill(black)
pygame.mixer.music.stop()
showtextscreen('Paused')
pygame.mixer.music.play(-1,0.0)
lastfalltime = time.time()
lastmovedowntime = time.time()
lastmovesidetime = time.time()
elif (event.key == K_LEFT or event.key == K_a):
moveleft = False
elif (event.key == K_RIGHT or event.key == K_d):
moveright = False
elif (event.key == K_DOWN or event.key == K_s):
movedown = False
elif event.type == KEYDOWN:
if (event.key == K_LEFT or event.key == K_a) and validposition(board,fallpiece,ax = -1):
fallpiece['x']-=1
moveleft = True
moveright = False
lastmovesidetime = time.time()
elif (event.key == K_RIGHT or event.key == K_d) and validposition(board,fallpiece,ax = 1):
fallpiece['x']+=1
moveright = True
moveleft = False
lastmovesidetime = time.time()
elif (event.key == K_UP or event.key ==K_w):
fallpiece['rotation'] =
(fallpiece['rotation'] + 1) % len(pieces[fallpiece['shape']])
if not validposition(board,fallpiece):
fallpiece['rotation'] = (fallpiece['rotation'] - 1) % len(pieces[fallpiece['shape']])
elif (event.key == K_DOWN or event.key ==K_s):
movedown = True
if validposition(board,fallpiece, ay = 1):
fallpiece['y']+=1
lastmovedowntime = time.time()
if event.key == K_SPACE:
movedown = False
moveleft = False
moveright = False
for i in range(1,boardheight):
if not validposition(board,fallpiece,ay = i):
fallpiece['y'] += i-1
if (moveleft or moveright) and time.time()-lastmovesidetime & movesidefreq:
if moveleft and validposition(board,fallpiece,ax = -1):
fallpiece['x']-=1
if moveright and validposition(board,fallpiece,ax = 1):
fallpiece['x']+=1
lastmovesidetime = time.time()
if movedown and time.time()-lastmovedowntime&movedownfreq and validposition(board,fallpiece,ay=1):
fallpiece['y']+=1
lastmovedowntime = time.time()
if time.time()-lastfalltime&fallfreq:
if not validposition(board,fallpiece,ay = 1):
addtoboard(board,fallpiece)
score +=removecompleteline(board)
level,fallfreq = calculate(score)
fallpiece = None
fallpiece['y'] +=1
lastfalltime = time.time()
disp.fill(black)
drawboard(board)
drawstatus(score,level)
drawnextpiece(nextpiece)
if fallpiece !=None:
drawpiece(fallpiece)
pygame.display.update()
fpsclock.tick(FPS)
def calculate(score):
level = int(score/10)+1
fallfreq = 0.27-(level*0.02)
return level,fallfreq
def terminal():
pygame.quit()
sys.exit()
def checkforquit():
for event in pygame.event.get(QUIT):
terminal()
for event in pygame.event.get(KEYUP):
if event.key == K_ESCAPE:
pygame.event.post(event)
def checkforpress():
checkforquit()
for event in pygame.event.get([KEYDOWN,KEYUP]):
if event.type == KEYDOWN:
return event.key
return None
def maketext(text,font,color):
surf = font.render(text,1,color)
return surf,surf.get_rect()
def showtextscreen(text):
tilesurf,tilerect = maketext(text,bigfont,white)
tilerect.center = (int(winx/2),int(winy/2))
disp.blit(tilesurf,tilerect)
presssurf,pressrect = maketext('press a key to play',basicfont,white)
pressrect.center = (int(winx/2),int(winy/2)+100)
disp.blit(presssurf,pressrect)
while checkforpress() == None:
pygame.display.update()
fpsclock.tick()
def getnewpiece():
shape = random.choice(list(pieces.keys()))
newpiece = {'shape':shape,
'rotation': random.randint(0,len(pieces[shape])-1),
'x': int(boardwidth)/2-int(templatenum/2),
'color': random.randint(0,len(colors)-1)}
return newpiece
def getblankboard():
board = []
for x in range(boardwidth):
board.append([blank]*boardheight)
return board
def addtoboard(board,piece):
for x in range(templatenum):
for y in range(templatenum):
if pieces[piece['shape']][piece['rotation']][y][x]!=blank:
board[x + piece['x']][y + piece['y']] = piece['color']
def onboard(x,y):
return x &=0 and x&boardwidth and y&boardheight
def validposition(board,piece,ax = 0,ay = 0):
for x in range(templatenum):
for y in range(templatenum):
aboveboard = y +piece['y'] +ay & 0
if aboveboard or pieces[piece['shape']][piece['rotation']][y][x]== blank:
if not onboard(x + piece['x']+ax,y+piece['y']+ay):
return False
if board[x+piece['x']+ax][y+piece['y']+ay]!=blank:
return False
return True
def completeline(board,y):
for x in range(boardwidth):
if board[x][y]==blank:
return False
return True
def removecompleteline(board):
numremove = 0
y = boardheight-1
while y &=0:
if completeline(board,y):
for pulldowny in range(y,0,-1):
for x in range (boardwidth):
board[x][pulldowny] = board[x][pulldowny-1]
for x in range(boardwidth):
board[x][0] = blank
numremove+=1
return numremove
def convertsize(boxx,boxy):
return (boxx*boxsize+xmargin,boxy*boxsize+topmargin)
def drawbox(boxx,boxy,color,pixelx = None,pixely= None):
if color == blank:
if pixelx == None and pixely == None:
pixelx,pixely = convertsize(boxx,boxy)
pygame.draw.rect(disp,colors[color],(pixelx+1 , pixely+1,boxsize-1,boxsize-1))
def drawboard(board):
pygame.draw.rect(disp,blue,(xmargin-3,topmargin-7,boardwidth*boxsize+8,boardheight*boxsize+8),5)
for x in range(boardwidth):
for y in range(boardheight):
drawbox(x,y,board[x][y])
def drawstatus(score,level):
scoresurf = basicfont.render('Score: %s'%score,True,white)
scorerect = scoresurf.get_rect()
scorerect.topleft = (winx-150,20)
disp.blit(scoresurf,scorerect)
levelsurf = basicfont.render('level: %s'%level,True, white)
levelrect = levelsurf.get_rect()
levelrect.topleft = (winx-150,50)
disp.blit(levelsurf,levelrect)
def drawpiece(piece,pixelx = None,pixely = None):
shapedraw = pieces[piece['shape']][piece['rotation']]
if pixelx == None and pixely == None:
pixelx,pixely = convertsize(piece['x'],piece['y'])
for x in range(templatenum):
for y in range(templatenum):
if shapedraw[y][x]!=blank:
drawbox(None,None,piece['color'],pixelx+(x*boxsize),pixely + y*boxsize)
def drawnextpiece(piece):
nextsurf = basicfont.render('Next:',True,white)
nextrect =nextsurf.get_rect()
nextrect.topleft = (winx-120,80)
disp.blit(nextsurf,nextrect)
drawpiece(piece,pixelx = winx-120,pixely = 100)
if __name__ == '__main__':
开源中国-程序员在线工具:
相关的代码(1173)
1回/14709阅
0回/2035阅
0回/2792阅
0回/4662阅
0回/1292阅
2回/1161阅
开源从代码分享开始
pljd139的其它代码pygame实现俄罗斯方块
import random, time, pygame, sys
from pygame.locals import *
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
BOXSIZE = 20
BOARDWIDTH = 10
BOARDHEIGHT = 20
BLANK = '.'
MOVESIDEWAYSFREQ = 0.15
MOVEDOWNFREQ = 0.1
XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * BOXSIZE) / 2)
TOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) - 5
= (255, 255, 255)
= (185, 185, 185)
= (155, 155,
BORDERCOLOR = BLUE
BGCOLOR = BLACK
TEXTCOLOR = WHITE
= (BLUE,GREEN,RED,YELLOW)
TEMPLATEWIDTH = 5
TEMPLATEHEIGHT = 5
S_SHAPE_TEMPLATE = [['.....',
Z_SHAPE_TEMPLATE = [['.....',
I_SHAPE_TEMPLATE = [['..O..',
O_SHAPE_TEMPLATE = [['.....',
J_SHAPE_TEMPLATE = [['.....',
L_SHAPE_TEMPLATE = [['.....',
T_SHAPE_TEMPLATE = [['.....',
PIECES = {'S': S_SHAPE_TEMPLATE,
'Z': Z_SHAPE_TEMPLATE,
'J': J_SHAPE_TEMPLATE,
'L': L_SHAPE_TEMPLATE,
'I': I_SHAPE_TEMPLATE,
'O': O_SHAPE_TEMPLATE,
'T': T_SHAPE_TEMPLATE}
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
BIGFONT = pygame.font.Font('freesansbold.ttf', 100)
pygame.display.set_caption('Tetromino')
showTextScreen('Tetromino')
while True:
pygame.mixer.music.load('tetrisc.mp3')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.stop()
showTextScreen('Game Over')
def runGame():
board = getBlankBoard()
lastMoveDownTime = time.time()
lastMoveSidewaysTime = time.time()
lastFallTime = time.time()
movingDown = False
movingLeft = False
movingRight = False
level, fallFreq = calculateLevelAndFallFreq(score)
fallingPiece = getNewPiece()
nextPiece = getNewPiece()
while True:
if fallingPiece == None:
fallingPiece = nextPiece
nextPiece = getNewPiece()
lastFallTime = time.time()
if not isValidPosition(board, fallingPiece):
for event in pygame.event.get():
if event.type == KEYUP:
if (event.key == K_LEFT):
movingLeft = False
elif (event.key == K_RIGHT):
movingRight = False
elif (event.key == K_DOWN):
movingDown = False
elif event.type == KEYDOWN:
if (event.key == K_LEFT) and isValidPosition(board, fallingPiece, adjX=-1):
fallingPiece['x'] = fallingPiece['x'] -1
movingLeft = True
movingRight = False
lastMoveSidewaysTime = time.time()
elif (event.key == K_RIGHT ) and isValidPosition(board, fallingPiece, adjX=1):
fallingPiece['x'] =fallingPiece['x'] + 1
movingRight = True
movingLeft = False
lastMoveSidewaysTime = time.time()
elif event.key == K_UP :
fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])
if not isValidPosition(board, fallingPiece):
fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
elif (event.key == K_DOWN ):
movingDown = True
if isValidPosition(board, fallingPiece, adjY=1):
fallingPiece['y'] =
fallingPiece['y'] +1
lastMoveDownTime = time.time()
if (movingLeft or movingRight) and time.time() - lastMoveSidewaysTime & MOVESIDEWAYSFREQ:
if movingLeft and isValidPosition(board, fallingPiece, adjX=-1):
fallingPiece['x'] =fallingPiece['x'] - 1
elif movingRight and isValidPosition(board, fallingPiece, adjX=1):
fallingPiece['x'] =fallingPiece['x'] + 1
lastMoveSidewaysTime = time.time()
if movingDown and time.time() - lastMoveDownTime & MOVEDOWNFREQ and isValidPosition(board, fallingPiece, adjY=1):
fallingPiece['y'] = fallingPiece['y'] + 1
lastMoveDownTime = time.time()
if time.time() - lastFallTime & fallFreq:
if not isValidPosition(board, fallingPiece, adjY=1):
addToBoard(board, fallingPiece)
score=score + removeCompleteLines(board)
level, fallFreq = calculateLevelAndFallFreq(score)
fallingPiece = None
fallingPiece['y'] = fallingPiece['y'] +1
lastFallTime = time.time()
DISPLAYSURF.fill(BGCOLOR)
drawBoard(board)
drawStatus(score, level)
drawNextPiece(nextPiece)
if fallingPiece != None:
drawPiece(fallingPiece)
pygame.display.update()
FPSCLOCK.tick(FPS)
def makeTextObjs(text, font, color):
surf = font.render(text, True, color)
return surf, surf.get_rect()
def checkForKeyPress():
for event in pygame.event.get([KEYDOWN, KEYUP]):
if event.type == KEYDOWN:
return event.key
return None
def calculateLevelAndFallFreq(score):
level = int(score / 10) + 1
fallFreq = 0.27 - (level * 0.02)
return level, fallFreq
def getNewPiece():
shape = random.choice(list(PIECES.keys()))
newPiece = {'shape': shape,
'rotation': random.randint(0, len(PIECES[shape]) - 1),
'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2),
'color': random.randint(0, len(COLORS) - 1)
return newPiece
def addToBoard(board, piece):
for x in range(TEMPLATEWIDTH):
for y in range(TEMPLATEHEIGHT):
if PIECES[piece['shape']][piece['rotation']][y][x] != BLANK:
board[x + piece['x']][y + piece['y']] = piece['color']
def getBlankBoard():
board = []
for i in range(BOARDWIDTH):
board.append([BLANK] * BOARDHEIGHT)
return board
def isOnBoard(x, y):
return x &= 0 and x & BOARDWIDTH and y & BOARDHEIGHT
def isValidPosition(board, piece, adjX=0, adjY=0):
for x in range(TEMPLATEWIDTH):
for y in range(TEMPLATEHEIGHT):
isAboveBoard = y + piece['y'] + adjY
if isAboveBoard or PIECES[piece['shape']][piece['rotation']][y][x] == BLANK:
if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY):
return False
if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != BLANK:
return False
return True
def isCompleteLine(board, y):
for x in range(BOARDWIDTH):
if board[x][y] == BLANK:
return False
return True
def removeCompleteLines(board):
numLinesRemoved = 0
y = BOARDHEIGHT - 1
while y &= 0:
if isCompleteLine(board, y):
for pullDownY in range(y, 0, -1):
for x in range(BOARDWIDTH):
board[x][pullDownY] = board[x][pullDownY-1]
for x in range(BOARDWIDTH):
board[x][0]=BLANK
numLinesRemoved=numLinesRemoved+1
return numLinesRemoved
def convertToPixelCoords(boxx, boxy):
return (XMARGIN + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))
def drawBoard(board):
pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN - 3, TOPMARGIN - 7, (BOARDWIDTH * BOXSIZE) + 8, (BOARDHEIGHT * BOXSIZE) + 8), 5)
pygame.draw.rect(DISPLAYSURF, BGCOLOR, (XMARGIN, TOPMARGIN, BOXSIZE * BOARDWIDTH, BOXSIZE * BOARDHEIGHT))
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
drawBox(x, y, board[x][y])
def drawBox(boxx, boxy, color, pixelx=None, pixely=None):
if color == BLANK:
if pixelx == None and pixely == None:
pixelx, pixely = convertToPixelCoords(boxx, boxy)
pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx + 1, pixely + 1, BOXSIZE - 1, BOXSIZE - 1))
def drawPiece(piece, pixelx=None, pixely=None):
shapeToDraw = PIECES[piece['shape']][piece['rotation']]
if pixelx == None and pixely == None:
pixelx, pixely = convertToPixelCoords(piece['x'], piece['y'])
for x in range(TEMPLATEWIDTH):
for y in range(TEMPLATEHEIGHT):
if shapeToDraw[y][x] != BLANK:
drawBox(None, None, piece['color'], pixelx+(x * BOXSIZE), pixely + (y * BOXSIZE))
def drawNextPiece(piece):
nextSurf = BASICFONT.render('Next:', True, TEXTCOLOR)
nextRect = nextSurf.get_rect()
nextRect.topleft = (WINDOWWIDTH - 120, 80)
DISPLAYSURF.blit(nextSurf, nextRect)
drawPiece(piece, pixelx=WINDOWWIDTH-120, pixely=100)
def drawStatus(score, level):
scoreSurf = BASICFONT.render('Score: %s' % score, True, TEXTCOLOR)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (WINDOWWIDTH - 150, 20)
DISPLAYSURF.blit(scoreSurf, scoreRect)
levelSurf = BASICFONT.render('Level: %s' % level, True, TEXTCOLOR)
levelRect = levelSurf.get_rect()
levelRect.topleft = (WINDOWWIDTH - 150, 50)
DISPLAYSURF.blit(levelSurf, levelRect)
def showTextScreen(text):
titleSurf, titleRect = makeTextObjs(text, BIGFONT, TEXTCOLOR)
titleRect.center = (int(WINDOWWIDTH / 2) - 3, int(WINDOWHEIGHT / 2) - 3)
DISPLAYSURF.blit(titleSurf, titleRect)
pressKeySurf, pressKeyRect = makeTextObjs('Press a key to play.', BASICFONT, TEXTCOLOR)
pressKeyRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2) + 100)
DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
while checkForKeyPress() == None:
pygame.display.update()
FPSCLOCK.tick()
if __name__ == '__main__':
pygame游戏小例子
基于Pierre Dellacherie算法实现俄罗斯方块的人工智能(python实现)《一》
Python 俄罗斯方块
Python写的俄罗斯方块
python练手--自制俄罗斯方块(文末附源码)
俄罗斯方块pygame
没有更多推荐了,}

我要回帖

更多关于 pygame键盘 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信