您好,登錄后才能下訂單哦!
創(chuàng)建游戲文件 2048.py
首先導(dǎo)入需要的包:
import curses from random import randrange, choice from collections import defaultdict
主邏輯
用戶行為
所有的有效輸入都可以轉(zhuǎn)換為"上,下,左,右,游戲重置,退出"這六種行為,用 actions 表示
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
有效輸入鍵是最常見的 W(上),A(左),S(下),D(右),R(重置),Q(退出),這里要考慮到大寫鍵開啟的情況,獲得有效鍵值列表:
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
將輸入與行為進(jìn)行關(guān)聯(lián):
actionsdict = dict(zip(lettercodes, actions * 2))
狀態(tài)機(jī)
處理游戲主邏輯的時(shí)候我們會(huì)用到一種十分常用的技術(shù):狀態(tài)機(jī),或者更準(zhǔn)確的說是有限狀態(tài)機(jī)(FSM)
你會(huì)發(fā)現(xiàn) 2048 游戲很容易就能分解成幾種狀態(tài)的轉(zhuǎn)換。
state 存儲(chǔ)當(dāng)前狀態(tài), state_actions 這個(gè)詞典變量作為狀態(tài)轉(zhuǎn)換的規(guī)則,它的 key 是狀態(tài),value 是返回下一個(gè)狀態(tài)的函數(shù):
Init: init() Game: game() Win: lambda: not_game('Win') Gameover: lambda: not_game('Gameover')
Exit: 退出循環(huán)
狀態(tài)機(jī)會(huì)不斷循環(huán),直到達(dá)到 Exit 終結(jié)狀態(tài)結(jié)束程序。
下面是經(jīng)過提取的主邏輯的代碼,會(huì)在后面進(jìn)行補(bǔ)全:
def main(stdscr): def init(): #重置游戲棋盤 return 'Game' def not_game(state): #畫出 GameOver 或者 Win 的界面 #讀取用戶輸入得到action,判斷是重啟游戲還是結(jié)束游戲 responses = defaultdict(lambda: state) #默認(rèn)是當(dāng)前狀態(tài),沒有行為就會(huì)一直在當(dāng)前界面循環(huán) responses['Restart'], responses['Exit'] = 'Init', 'Exit' #對(duì)應(yīng)不同的行為轉(zhuǎn)換到不同的狀態(tài) return responses[action] def game(): #畫出當(dāng)前棋盤狀態(tài) #讀取用戶輸入得到action if action == 'Restart': return 'Init' if action == 'Exit': return 'Exit' #if 成功移動(dòng)了一步: if 游戲勝利了: return 'Win' if 游戲失敗了: return 'Gameover' return 'Game' state_actions = { 'Init': init, 'Win': lambda: not_game('Win'), 'Gameover': lambda: not_game('Gameover'), 'Game': game } state = 'Init' #狀態(tài)機(jī)開始循環(huán) while state != 'Exit': state = state_actions[state]()
用戶輸入處理
阻塞+循環(huán),直到獲得用戶有效輸入才返回對(duì)應(yīng)行為:
def get_user_action(keyboard): char = "N" while char not in actions_dict: char = keyboard.getch() return actions_dict[char]
矩陣轉(zhuǎn)置與矩陣逆轉(zhuǎn)
加入這兩個(gè)操作可以大大節(jié)省我們的代碼量,減少重復(fù)勞動(dòng),看到后面就知道了。
矩陣轉(zhuǎn)置:
def transpose(field): return [list(row) for row in zip(*field)]
矩陣逆轉(zhuǎn)(不是逆矩陣):
def invert(field): return [row[::-1] for row in field]
創(chuàng)建棋盤
初始化棋盤的參數(shù),可以指定棋盤的高和寬以及游戲勝利條件,默認(rèn)是最經(jīng)典的 4×4~2048。
class GameField(object): def __init__(self, height=4, width=4, win=2048): self.height = height #高 self.width = width #寬 self.win_value = 2048 #過關(guān)分?jǐn)?shù) self.score = 0 #當(dāng)前分?jǐn)?shù) self.highscore = 0 #最高分 self.reset() #棋盤重置
棋盤操作
隨機(jī)生成一個(gè) 2 或者 4
def spawn(self): new_element = 4 if randrange(100) > 89 else 2 (i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0]) self.field[i][j] = new_element #### 重置棋盤 def reset(self): if self.score > self.highscore: self.highscore = self.score self.score = 0 self.field = [[0 for i in range(self.width)] for j in range(self.height)] self.spawn() self.spawn() #### 一行向左合并 (注:這一操作是在 move 內(nèi)定義的,拆出來是為了方便閱讀) def move_row_left(row): def tighten(row): # 把零散的非零單元擠到一塊 new_row = [i for i in row if i != 0] new_row += [0 for i in range(len(row) - len(new_row))] return new_row def merge(row): # 對(duì)鄰近元素進(jìn)行合并 pair = False new_row = [] for i in range(len(row)): if pair: new_row.append(2 * row[i]) self.score += 2 * row[i] pair = False else: if i + 1 < len(row) and row[i] == row[i + 1]: pair = True new_row.append(0) else: new_row.append(row[i]) assert len(new_row) == len(row) return new_row #先擠到一塊再合并再擠到一塊 return tighten(merge(tighten(row)))
棋盤走一步
通過對(duì)矩陣進(jìn)行轉(zhuǎn)置與逆轉(zhuǎn),可以直接從左移得到其余三個(gè)方向的移動(dòng)操作
def move(self, direction): def move_row_left(row): #一行向左合并 moves = {} moves['Left'] = lambda field: [move_row_left(row) for row in field] moves['Right'] = lambda field: invert(moves['Left'](invert(field))) moves['Up'] = lambda field: transpose(moves['Left'](transpose(field))) moves['Down'] = lambda field: transpose(moves['Right'](transpose(field))) if direction in moves: if self.move_is_possible(direction): self.field = moves[direction](self.field) self.spawn() return True else: return False
判斷輸贏
def is_win(self): return any(any(i >= self.win_value for i in row) for row in self.field) def is_gameover(self): return not any(self.move_is_possible(move) for move in actions) #### 判斷能否移動(dòng) def move_is_possible(self, direction): defrow_is_left_movable(row): def change(i): if row[i] == 0 and row[i + 1] != 0: # 可以移動(dòng) return True if row[i] != 0 and row[i + 1] == row[i]: # 可以合并 return True return False return any(change(i) for i in range(len(row) - 1)) check = {} check['Left'] = lambda field: any(row_is_left_movable(row) for row in field) check['Right'] = lambda field: check['Left'](invert(field)) check['Up'] = lambda field: check['Left'](transpose(field)) check['Down'] = lambda field: check['Right'](transpose(field)) if direction in check: return check[direction](self.field) else: return False
繪制游戲界面
def draw(self, screen): help_string1 = '(W)Up (S)Down (A)Left (D)Right' help_string2 = ' (R)Restart (Q)Exit' gameover_string = ' GAME OVER' win_string = ' YOU WIN!' def cast(string): screen.addstr(string + 'n') #繪制水平分割線 def draw_hor_separator(): line = '+' + ('+------' * self.width + '+')[1:] separator = defaultdict(lambda: line) if not hasattr(draw_hor_separator, "counter"): draw_hor_separator.counter = 0 cast(separator[draw_hor_separator.counter]) draw_hor_separator.counter += 1 def draw_row(row): cast(''.join('|{: ^5} '.format(num) if num > 0 else '| ' for num in row) + '|') screen.clear() cast('SCORE: ' + str(self.score)) if 0 != self.highscore: cast('HGHSCORE: ' + str(self.highscore)) for row in self.field: draw_hor_separator() draw_row(row) draw_hor_separator() if self.is_win(): cast(win_string) else: if self.is_gameover(): cast(gameover_string) else: cast(help_string1) cast(help_string2)
完成主邏輯
完成以上工作后,我們就可以補(bǔ)完主邏輯了!
def main(stdscr): def init(): #重置游戲棋盤 game_field.reset() return 'Game' def not_game(state): #畫出 GameOver 或者 Win 的界面 game_field.draw(stdscr) #讀取用戶輸入得到action,判斷是重啟游戲還是結(jié)束游戲 action = get_user_action(stdscr) responses = defaultdict(lambda: state) #默認(rèn)是當(dāng)前狀態(tài),沒有行為就會(huì)一直在當(dāng)前界面循環(huán) responses['Restart'], responses['Exit'] = 'Init', 'Exit' #對(duì)應(yīng)不同的行為轉(zhuǎn)換到不同的狀態(tài) return responses[action] def game(): #畫出當(dāng)前棋盤狀態(tài) game_field.draw(stdscr) #讀取用戶輸入得到action action = get_user_action(stdscr) if action == 'Restart': return 'Init' if action == 'Exit': return 'Exit' if game_field.move(action): # move successful if game_field.is_win(): return 'Win' if game_field.is_gameover(): return 'Gameover' return 'Game' state_actions = { 'Init': init, 'Win': lambda: not_game('Win'), 'Gameover': lambda: not_game('Gameover'), 'Game': game } curses.use_default_colors() game_field = GameField(win=32) state = 'Init' #狀態(tài)機(jī)開始循環(huán) while state != 'Exit': state = state_actions[state]()
運(yùn)行
填上最后一行代碼:
curses.wrapper(main)
完整版代碼地址:https://github.com/JLUNeverMore/easy_2048-in-200-lines
總結(jié)
以上所述是小編給大家介紹的200 行python 代碼實(shí)現(xiàn) 2048 游戲,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。