接下來就是代碼模塊,其中的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里面隨機生成兩個2
def init(board):
# 游戲先都重置為0
for i in range(4):
for j in range(4):
board[i][j] = 0
# 隨機生成兩個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):移除列表中的某個值的第一個匹配項,所以[8,0,0,2]會移除兩次0
for x in range(boardList.count(0)):
boardList.remove(0)
# 移除的0重新補充回去,[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)行運動
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é)束,則一直運行
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