如何自制游戏:

1、先写一个游戏初始界面:

'''显示游戏开始界面'''defShowStartInterface(screen,width,height):

screen.fill(cfg.BACKGROUNDCOLOR)

tfont=pygame.font.Font(cfg.FONTPATH,width//4)

cfont=pygame.font.Font(cfg.FONTPATH,width//20)

title=tfont.render('拼图游戏',True,cfg.RED)

content1=cfont.render('按H或M或L键开始游戏',True,cfg.BLUE)

content2=cfont.render('H为5*5模式,M为4*4模式,L为3*3模式',True,cfg.BLUE)

trect=title.get_rect()

trect.midtop=(width/2,height/10)

crect1=content1.get_rect()

crect1.midtop=(width/2,height/2.2)

crect2=content2.get_rect()

crect2.midtop=(width/2,height/1.8)

screen.blit(title,trect)

screen.blit(content1,crect1)

screen.blit(content2,crect2) whileTrue: foreventinpygame.event.get(): if(event.type==pygame.QUIT)or(event.type==pygame.KEYDOWNandevent.key==pygame.K_ESCAPE):

pygame.quit()

sys.exit() elifevent.type==pygame.KEYDOWN: ifevent.key==ord('l'):return3

elifevent.key==ord('m'):return4

elifevent.key==ord('h'):return5

pygame.display.update()

2、定义移动操作的目的是为了移动拼图,具体实现起来十分简单:

'''将空白Cell左边的Cell右移到空白Cell位置'''defmoveR(board,blank_cell_idx,num_cols):

ifblank_cell_idx%num_cols==0:returnblank_cell_idx

board[blank_cell_idx-1],board[blank_cell_idx]=board[blank_cell_idx],board[blank_cell_idx-1] returnblank_cell_idx-1'''将空白Cell右边的Cell左移到空白Cell位置'''defmoveL(board,blank_cell_idx,num_cols):

if(blank_cell_idx+1)%num_cols==0:returnblank_cell_idx

board[blank_cell_idx+1],board[blank_cell_idx]=board[blank_cell_idx],board[blank_cell_idx+1] returnblank_cell_idx+1'''将空白Cell上边的Cell下移到空白Cell位置'''defmoveD(board,blank_cell_idx,num_cols):

ifblank_cell_idx

board[blank_cell_idx-num_cols],board[blank_cell_idx]=board[blank_cell_idx],board[blank_cell_idx-num_cols] returnblank_cell_idx-num_cols'''将空白Cell下边的Cell上移到空白Cell位置'''defmoveU(board,blank_cell_idx,num_rows,num_cols):

ifblank_cell_idx>=(num_rows-1)*num_cols:returnblank_cell_idx

board[blank_cell_idx+num_cols],board[blank_cell_idx]=board[blank_cell_idx],board[blank_cell_idx+num_cols] returnblank_cell_idx+num_cols

3、我们需要打乱拼图, 但是随机打乱很可能导致拼图无解,因此我们通过随机移动拼图来实现打乱拼图的效果 ,这也是我们先定义拼图的移动操作的主要原因:

'''获得打乱的拼图'''defCreateBoard(num_rows,num_cols,num_cells):

board=[] foriinrange(num_cells):board.append(i) #去掉右下角那块

blank_cell_idx=num_cells-1

board[blank_cell_idx]=-1

foriinrange(cfg.NUMRANDOM): #0:left,1:right,2:up,3:down

direction=random.randint(0,3) ifdirection==0:blank_cell

推荐内容