python-拼图游戏代码

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

#-*-coding:utf-8-*-importsimpleguitkassimpleguiimportrandom#载入外部图像baymax=simplegui.load_image()#定义常量#画布的尺寸WIDTH=600HEIGHT=WIDTH+100#图像块的边长IMAGE_SIZE=WIDTH/3#图像块坐标列表all_coordinates=[[IMAGE_SIZE*0.5,IMAGE_SIZE*0.5],[IMAGE_SIZE*1.5,IMAGE_SIZE*0.5],[IMAGE_SIZE*2.5,IMAGE_SIZE*0.5],[IMAGE_SIZE*0.5,IMAGE_SIZE*1.5],[IMAGE_SIZE*1.5,IMAGE_SIZE*1.5],[IMAGE_SIZE*2.5,IMAGE_SIZE*1.5],[IMAGE_SIZE*0.5,IMAGE_SIZE*2.5],[IMAGE_SIZE*1.5,IMAGE_SIZE*2.5],None]#棋盘行列数ROWS=3COLS=3#移动步数steps=0#保存所有图像块的列表board=[[None,None,None],[None,None,None],[None,None,None]]#图像块类classSquare:def__init__(self,coordinate):self.center=coordinatedefdraw(self,canvas,board_pos):canvas.draw_image(baymax,self.center,[IMAGE_SIZE,IMAGE_SIZE],[(board_pos[1]+0.5)*IMAGE_SIZE,(board_pos[0]+0.5)*IMAGE_SIZE],[IMAGE_SIZE,IMAGE_SIZE])#初始化拼图板definit_board():#打乱图像块坐标random.shuffle(all_coordinates)#填充拼图板foriinrange(ROWS):forjinrange(COLS):idx=i*ROWS+jsquare_center=all_coordinates[idx]ifsquare_centerisNone:board[i][j]=Noneelse:board[i][j]=Square(square_center)#重置游戏defplay_game():globalstepssteps=0init_board()#绘制游戏界面各元素defdraw(canvas):#画黑框canvas.draw_polygon([[0,0],[WIDTH,0],[WIDTH,WIDTH],[0,WIDTH]],1,'Black')#画目标图像canvas.draw_image(baymax,[WIDTH/2,WIDTH/2],[WIDTH,WIDTH],[50,WIDTH+50],[98,98])#画步数canvas.draw_text(步数:+str(steps),[400,680],22,White)#画图像块#代码写在这里foriinrange(ROWS):forjinrange(COLS):ifboard[i][j]isnotNone:board[i][j].draw(canvas,[i,j])defmouseclick(pos):globalsteps#将点击位置换算成拼图板上的坐标r=int(pos[1]//IMAGE_SIZE)c=int(pos[0]//IMAGE_SIZE)ifr3andc3:#点击位置在拼图板内才移动图片ifboard[r][c]isNone:#点到空位置上什么也不移动returnelse:#依次检查当前图像块的上,下,左,右是否有空位置,如果有就移动当前图像块#代码写在这里current_square=board[r][c]ifr-1=0andboard[r-1][c]isNone:#判断上面board[r][c]=Noneboard[r-1][c]=current_squaresteps+=1elifc+1=2andboard[r][c+1]isNone:#判断右面board[r][c]=Noneboard[r][c+1]=current_squaresteps+=1elifr+1=2andboard[r+1][c]isNone:#判断下面board[r][c]=Noneboard[r+1][c]=current_squaresteps+=1elifc-1=0andboard[r][c-1]isNone:#判断左面board[r][c]=Noneboard[r][c-1]=current_squaresteps+=1#创建框架frame=simplegui.create_frame(拼图,WIDTH,HEIGHT)frame.set_canvas_background(Black)frame.set_draw_handler(draw)frame.add_button(重新开始,play_game,60)#注册鼠标事件frame.set_mouseclick_handler(mouseclick)#初始化游戏play_game()#启动框架frame.start()

1 / 3
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功