Python實(shí)現(xiàn)簡單2048小游戲
簡單的2048小游戲
不多說,直接上圖,這里并未實(shí)現(xiàn)GUI之類的,需要的話,可自行實(shí)現(xiàn):

接下來就是代碼模塊,其中的2048游戲原來網(wǎng)絡(luò)上有很多,我就不詳細(xì)寫上去了,都寫在注釋里面了。唯一要注意的就是需要先去了解一下矩陣的轉(zhuǎn)置,這里會用到
import random
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
# 打印游戲界面
def display(board, score):
print('{0:4} {1:4} {2:4} {3:4}'.format(board[0][0], board[0][1], board[0][2], board[0][3]))
print('{0:4} {1:4} {2:4} {3:4}'.format(board[1][0], board[1][1], board[1][2], board[1][3]))
print('{0:4} {1:4} {2:4} {3:4}'.format(board[2][0], board[2][1], board[2][2], board[2][3]))
print('{0:4} {1:4} {2:4} {3:4}'.format(board[3][0], board[3][1], board[3][2], board[3][3]), ' 分?jǐn)?shù):', score)
# 初始化游戲,在4*4里面隨機(jī)生成兩個2
def init(board):
# 游戲先都重置為0
for i in range(4):
for j in range(4):
board[i][j] = 0
# 隨機(jī)生成兩個2保存的位置
randomposition = random.sample(range(0, 15), 2)
board[int(randomposition[0] / 4)][randomposition[0] % 4] = 2
board[int(randomposition[1] / 4)][randomposition[1] % 4] = 2
def addSameNumber(boardList, direction):
'''需要在列表中查找相鄰相同的數(shù)字相加,返回增加的分?jǐn)?shù)
:param boardList: 經(jīng)過對齊非零的數(shù)字處理過后的二維數(shù)組
:param direction: direction == 'left'從右向左查找,找到相同且相鄰的兩個數(shù)字,左側(cè)數(shù)字翻倍,右側(cè)數(shù)字置0
direction == 'right'從左向右查找,找到相同且相鄰的兩個數(shù)字,右側(cè)數(shù)字翻倍,左側(cè)數(shù)字置0
:return:
'''
addNumber = 0
# 向左以及向上的操作
if direction == 'left':
for i in [0, 1, 2]:
if boardList[i] == boardList[i+1] != 0:
boardList[i] *= 2
boardList[i + 1] = 0
addNumber += boardList[i]
return {'continueRun': True, 'addNumber': addNumber}
return {'continueRun': False, 'addNumber': addNumber}
# 向右以及向下的操作
else:
for i in [3, 2, 1]:
if boardList[i] == boardList[i-1] != 0:
boardList[i] *= 2
boardList[i - 1] = 0
addNumber += boardList[i]
return {'continueRun': True, 'addNumber': addNumber}
return {'continueRun': False, 'addNumber': addNumber}
def align(boardList, direction):
'''對齊非零的數(shù)字
direction == 'left':向左對齊,例如[8,0,0,2]左對齊后[8,2,0,0]
direction == 'right':向右對齊,例如[8,0,0,2]右對齊后[0,0,8,2]
'''
# 先移除列表里面的0,如[8,0,0,2]->[8,2],1.先找0的個數(shù),然后依照個數(shù)進(jìn)行清理
# boardList.remove(0):移除列表中的某個值的第一個匹配項(xiàng),所以[8,0,0,2]會移除兩次0
for x in range(boardList.count(0)):
boardList.remove(0)
# 移除的0重新補(bǔ)充回去,[8,2]->[8,2,0,0]
if direction == 'left':
boardList.extend([0 for x in range(4 - len(boardList))])
else:
boardList[:0] = [0 for x in range(4 - len(boardList))]
def handle(boardList, direction):
'''
處理一行(列)中的數(shù)據(jù),得到最終的該行(列)的數(shù)字狀態(tài)值, 返回得分
:param boardList: 列表結(jié)構(gòu),存儲了一行(列)中的數(shù)據(jù)
:param direction: 移動方向,向上和向左都使用方向'left',向右和向下都使用'right'
:return: 返回一行(列)處理后加的分?jǐn)?shù)
'''
addscore = 0
# 先處理數(shù)據(jù),把數(shù)據(jù)都往指定方向進(jìn)行運(yùn)動
align(boardList, direction)
result = addSameNumber(boardList, direction)
# 當(dāng)result['continueRun'] 為True,代表需要再次執(zhí)行
while result['continueRun']:
# 重新對其,然后重新執(zhí)行合并,直到再也無法合并為止
addscore += result['addNumber']
align(boardList, direction)
result = addSameNumber(boardList, direction)
# 直到執(zhí)行完畢,及一行的數(shù)據(jù)都不存在相同的
return {'addscore': addscore}
# 游戲操作函數(shù),根據(jù)移動方向重新計算矩陣狀態(tài)值,并記錄得分
def operator(board):
# 每一次的操作所加的分?jǐn)?shù),以及操作后游戲是否觸發(fā)結(jié)束狀態(tài)(即數(shù)據(jù)占滿位置)
addScore = 0
gameOver = False
# 默認(rèn)向左
direction = 'left'
op = input("請輸入您的操作:")
if op in ['a', 'A']:
# 方向向左
direction = 'left'
# 一行一行進(jìn)行處理
for row in range(4):
addScore += handle(board[row], direction)['addscore']
elif op in ['d', 'D']:
direction = 'right'
for row in range(4):
addScore += handle(board[row], direction)['addscore']
elif op in ['w', 'W']:
# 向上相當(dāng)于向左的轉(zhuǎn)置處理
direction = 'left'
board = list(map(list, zip(*board)))
# 一行一行進(jìn)行處理
for row in range(4):
addScore += handle(board[row], direction)['addscore']
board = list(map(list, zip(*board)))
elif op in ['s', 'S']:
# 向下相當(dāng)于向右的轉(zhuǎn)置處理
direction = 'right'
board = list(map(list, zip(*board)))
# 一行一行進(jìn)行處理
for row in range(4):
addScore += handle(board[row], direction)['addscore']
board = list(map(list, zip(*board)))
else:
print("錯誤輸入!請輸入[W, S, A, D]或者對應(yīng)小寫")
return {'gameOver': gameOver, 'addScore': addScore, 'board': board}
# 每一次操作后都需要判斷0的數(shù)量,如果滿了,則游戲結(jié)束
number_0 = 0
for q in board:
# count(0)是指0出現(xiàn)的個數(shù),是掃描每一行的
number_0 += q.count(0)
# 如果number_0為0,說明滿了
if number_0 == 0:
gameOver = True
return {'gameOver': gameOver, 'addScore': addScore, 'board': board}
# 說明還沒有滿,則在空的位置上加上一個2或者4,概率為3:1
else:
addnum = random.choice([2,2,2,4])
position_0_list = []
# 找出0的位置,并保存起來
for i in range(4):
for j in range(4):
if board[i][j] == 0:
position_0_list.append(i*4 + j)
# 在剛才記錄的0的位置里面隨便找一個,然后替換成生成的2或者4
randomposition = random.sample(position_0_list, 1)
board[int(randomposition[0] / 4)][randomposition[0] % 4] = addnum
return {'gameOver': gameOver, 'addScore': addScore, 'board': board}
if __name__ == '__main__':
print('輸入:W(上) S(下) A(左) D(右).')
# 初始化游戲界面,游戲分?jǐn)?shù)
gameOver = False
init(board)
score = 0
# 游戲未結(jié)束,則一直運(yùn)行
while gameOver != True:
display(board, score)
operator_result = operator(board)
board = operator_result['board']
if operator_result['gameOver'] == True:
print("游戲結(jié)束,你輸了!")
print("你的最終得分:", score)
gameOver = operator_result['gameOver']
break
else:
# 加上這一步的分
score += operator_result['addScore']
if score >= 2048:
print("牛啊牛啊,你吊竟然贏了!")
print("你的最終得分:", score)
# 結(jié)束游戲
gameOver = True
break
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
手把手教你YOLOv5如何進(jìn)行區(qū)域目標(biāo)檢測
YOLOV5和YOLOV4有很多相同的地方,最大的改變還是基礎(chǔ)架構(gòu)的變化,下面這篇文章主要給大家介紹了關(guān)于YOLOv5如何進(jìn)行區(qū)域目標(biāo)檢測的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12
Python變量名詳細(xì)規(guī)則詳細(xì)變量值介紹
這篇文章主要介紹了Python變量名詳細(xì)規(guī)則詳細(xì)變量值,Python需要使用標(biāo)識符給變量命名,其實(shí)標(biāo)識符就是用于給程序中變量、類、方法命名的符號(簡單來說,標(biāo)識符就是合法的名稱,下面葛小編一起進(jìn)入文章里哦阿姐更多詳細(xì)內(nèi)容吧2022-01-01
NumPy實(shí)現(xiàn)從已有的數(shù)組創(chuàng)建數(shù)組
本文介紹了NumPy中如何從已有的數(shù)組創(chuàng)建數(shù)組,包括使用numpy.asarray,numpy.frombuffer和numpy.fromiter方法,具有一定的參考價值,感興趣的可以了解一下2024-10-10
conda配置python虛擬環(huán)境的實(shí)現(xiàn)步驟
本文主要介紹了conda配置python虛擬環(huán)境的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Python3.6實(shí)現(xiàn)帶有簡單界面的有道翻譯小程序
本文通過實(shí)例代碼給大家介紹了基于Python3.6實(shí)現(xiàn)帶有簡單界面的有道翻譯小程序,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2019-04-04
python使用tkinter實(shí)現(xiàn)簡單計算器
這篇文章主要為大家詳細(xì)介紹了python使用tkinter實(shí)現(xiàn)簡單計算器,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
python+django+mysql開發(fā)實(shí)戰(zhàn)(附demo)
本文主要介紹了python+django+mysql開發(fā)實(shí)戰(zhàn)(附demo),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
Python wxPython庫Core組件BoxSizer用法示例
這篇文章主要介紹了Python wxPython庫Core組件BoxSizer用法,結(jié)合實(shí)例形式分析了wxPython BoxSizer布局管理相關(guān)使用方法及操作注意事項(xiàng),需要的朋友可以參考下2018-09-09

