您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)如何通過Python把照片做成拼圖游戲的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
我用隔壁詩(shī)詩(shī)學(xué)姐的照片,給她做了一個(gè)拼圖游戲
結(jié)果,我自己的拼不出來了
安裝pygame模塊
#pip install pygame PS C:\Users\lex> pip install pygame Looking in indexes: http://mirrors.aliyun.com/pypi/simple Requirement already satisfied: pygame in f:\develop\python36\lib\site-packages (2.0.1) PS C:\Users\lex>
cfg.py
配置需要讀取的學(xué)姐的照片路徑、引入游戲引用到的字體及顏色。
'''配置文件''' import os '''屏幕大小''' SCREENSIZE = (640, 640) '''讀取學(xué)姐照片''' PICTURE_ROOT_DIR = os.path.join(os.getcwd(), 'resources/pictures') '''字體路徑''' FONTPATH = os.path.join(os.getcwd(), 'resources/font/FZSTK.TTF') '''定義一些顏色''' BACKGROUNDCOLOR = (255, 255, 255) RED = (255, 0, 0) BLUE = (0, 0, 255) BLACK = (0, 0, 0) '''FPS''' FPS = 40 '''隨機(jī)打亂拼圖次數(shù)''' NUMRANDOM = 100
將詩(shī)詩(shī)學(xué)姐的照片,添加到resources/pictures路徑下,
游戲啟動(dòng)時(shí),根據(jù)我們?cè)赾fg.py中的配置,會(huì)自動(dòng)將該路徑的照片
加載成為我們拼圖的原材料。
pintu.py
代碼結(jié)構(gòu)搞的簡(jiǎn)單一點(diǎn)。一個(gè)配置文件cfg,一個(gè)資源路徑resources,存放字體和圖片。
主函數(shù)代碼放在這里:
1、定義四個(gè)可移動(dòng)函數(shù),在存在空格的情況下,允許向空格的方向移動(dòng)。
2、createboard:隨機(jī)將圖片拆分,并且打亂。
3、開始時(shí),隨機(jī)從圖片文件夾獲取一張圖片:如果想給整個(gè)宿舍的學(xué)姐做游戲,
就把所有人的照片放進(jìn)去,這樣每次打開,會(huì)隨機(jī)生成一個(gè)學(xué)姐的照片作為游戲背景。
''' Function: 拼圖小游戲 作者: LexSaints ''' import os import sys import cfg import random import pygame '''判斷游戲是否結(jié)束''' def isGameOver(board, size): assert isinstance(size, int) num_cells = size * size for i in range(num_cells-1): if board[i] != i: return False return True '''將空白Cell左邊的Cell右移到空白Cell位置''' def moveR(board, blank_cell_idx, num_cols): if blank_cell_idx % num_cols == 0: return blank_cell_idx board[blank_cell_idx-1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx-1] return blank_cell_idx - 1 '''將空白Cell右邊的Cell左移到空白Cell位置''' def moveL(board, blank_cell_idx, num_cols): if (blank_cell_idx+1) % num_cols == 0: return blank_cell_idx board[blank_cell_idx+1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx+1] return blank_cell_idx + 1 '''將空白Cell上邊的Cell下移到空白Cell位置''' def moveD(board, blank_cell_idx, num_cols): if blank_cell_idx < num_cols: return blank_cell_idx board[blank_cell_idx-num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx-num_cols] return blank_cell_idx - num_cols '''將空白Cell下邊的Cell上移到空白Cell位置''' def moveU(board, blank_cell_idx, num_rows, num_cols): if blank_cell_idx >= (num_rows-1) * num_cols: return blank_cell_idx board[blank_cell_idx+num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx+num_cols] return blank_cell_idx + num_cols '''獲得打亂的拼圖''' def CreateBoard(num_rows, num_cols, num_cells): board = [] for i in range(num_cells): board.append(i) # 去掉右下角那塊 blank_cell_idx = num_cells - 1 board[blank_cell_idx] = -1 for i in range(cfg.NUMRANDOM): # 0: left, 1: right, 2: up, 3: down direction = random.randint(0, 3) if direction == 0: blank_cell_idx = moveL(board, blank_cell_idx, num_cols) elif direction == 1: blank_cell_idx = moveR(board, blank_cell_idx, num_cols) elif direction == 2: blank_cell_idx = moveU(board, blank_cell_idx, num_rows, num_cols) elif direction == 3: blank_cell_idx = moveD(board, blank_cell_idx, num_cols) return board, blank_cell_idx '''隨機(jī)選取一張圖片''' def GetImagePath(rootdir): imagenames = os.listdir(rootdir) assert len(imagenames) > 0 return os.path.join(rootdir, random.choice(imagenames)) '''顯示游戲結(jié)束界面''' def ShowEndInterface(screen, width, height): screen.fill(cfg.BACKGROUNDCOLOR) font = pygame.font.Font(cfg.FONTPATH, width//15) title = font.render('恭喜! 你成功完成了拼圖!', True, (233, 150, 122)) rect = title.get_rect() rect.midtop = (width/2, height/2.5) screen.blit(title, rect) pygame.display.update() while True: for event in pygame.event.get(): if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() pygame.display.update() '''顯示游戲開始界面''' def ShowStartInterface(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) while True: for event in pygame.event.get(): if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == ord('l'): return 3 elif event.key == ord('m'): return 4 elif event.key == ord('h'): return 5 pygame.display.update() '''主函數(shù)''' def main(): # 初始化 pygame.init() clock = pygame.time.Clock() # 加載圖片 game_img_used = pygame.image.load(GetImagePath(cfg.PICTURE_ROOT_DIR)) game_img_used = pygame.transform.scale(game_img_used, cfg.SCREENSIZE) game_img_used_rect = game_img_used.get_rect() # 設(shè)置窗口 screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('拼圖游戲 —— Linux黑客小課堂') # 游戲開始界面 size = ShowStartInterface(screen, game_img_used_rect.width, game_img_used_rect.height) assert isinstance(size, int) num_rows, num_cols = size, size num_cells = size * size # 計(jì)算Cell大小 cell_width = game_img_used_rect.width // num_cols cell_height = game_img_used_rect.height // num_rows # 避免初始化為原圖 while True: game_board, blank_cell_idx = CreateBoard(num_rows, num_cols, num_cells) if not isGameOver(game_board, size): break # 游戲主循環(huán) is_running = True while is_running: # --事件捕獲 for event in pygame.event.get(): # ----退出游戲 if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() # ----鍵盤操作 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT or event.key == ord('a'): blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols) elif event.key == pygame.K_RIGHT or event.key == ord('d'): blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols) elif event.key == pygame.K_UP or event.key == ord('w'): blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols) elif event.key == pygame.K_DOWN or event.key == ord('s'): blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols) # ----鼠標(biāo)操作 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: x, y = pygame.mouse.get_pos() x_pos = x // cell_width y_pos = y // cell_height idx = x_pos + y_pos * num_cols if idx == blank_cell_idx-1: blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols) elif idx == blank_cell_idx+1: blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols) elif idx == blank_cell_idx+num_cols: blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols) elif idx == blank_cell_idx-num_cols: blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols) # --判斷游戲是否結(jié)束 if isGameOver(game_board, size): game_board[blank_cell_idx] = num_cells - 1 is_running = False # --更新屏幕 screen.fill(cfg.BACKGROUNDCOLOR) for i in range(num_cells): if game_board[i] == -1: continue x_pos = i // num_cols y_pos = i % num_cols rect = pygame.Rect(y_pos*cell_width, x_pos*cell_height, cell_width, cell_height) img_area = pygame.Rect((game_board[i]%num_cols)*cell_width, (game_board[i]//num_cols)*cell_height, cell_width, cell_height) screen.blit(game_img_used, rect, img_area) for i in range(num_cols+1): pygame.draw.line(screen, cfg.BLACK, (i*cell_width, 0), (i*cell_width, game_img_used_rect.height)) for i in range(num_rows+1): pygame.draw.line(screen, cfg.BLACK, (0, i*cell_height), (game_img_used_rect.width, i*cell_height)) pygame.display.update() clock.tick(cfg.FPS) # 游戲結(jié)束界面 ShowEndInterface(screen, game_img_used_rect.width, game_img_used_rect.height) '''run''' if __name__ == '__main__': main()
1、開發(fā)工具啟動(dòng)
如果你有python開發(fā)環(huán)境VScode、sublimeText、notepad+、pycharm等等這些環(huán)境,可以直接在工具中,運(yùn)行游戲。
2、命令行運(yùn)行游戲
如下圖:
感謝各位的閱讀!關(guān)于“如何通過Python把照片做成拼圖游戲”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。