人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動態(tài)

Python實現(xiàn)簡單2048小游戲

發(fā)布日期:2022-03-30 18:35 | 文章來源:源碼中國

簡單的2048小游戲

不多說,直接上圖,這里并未實現(xiàn)GUI之類的,需要的話,可自行實現(xiàn):

接下來就是代碼模塊,其中的2048游戲原來網(wǎng)絡上有很多,我就不詳細寫上去了,都寫在注釋里面了。唯一要注意的就是需要先去了解一下矩陣的轉(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]), '分數(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ù)字相加,返回增加的分數(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ù)進行清理
 # 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: 返回一行(列)處理后加的分數(shù)
 '''
 addscore = 0
 # 先處理數(shù)據(jù),把數(shù)據(jù)都往指定方向進行運動
 align(boardList, direction)
 result = addSameNumber(boardList, direction)
 # 當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):
 # 每一次的操作所加的分數(shù),以及操作后游戲是否觸發(fā)結(jié)束狀態(tài)(即數(shù)據(jù)占滿位置)
 addScore = 0
 gameOver = False
 # 默認向左
 direction = 'left'
 op = input("請輸入您的操作:")
 if op in ['a', 'A']:
  # 方向向左
  direction = 'left'
  # 一行一行進行處理
  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']:
  # 向上相當于向左的轉(zhuǎn)置處理
  direction = 'left'
  board = list(map(list, zip(*board)))
  # 一行一行進行處理
  for row in range(4):
addScore += handle(board[row], direction)['addscore']
  board = list(map(list, zip(*board)))
 elif op in ['s', 'S']:
  # 向下相當于向右的轉(zhuǎn)置處理
  direction = 'right'
  board = list(map(list, zip(*board)))
  # 一行一行進行處理
  for row in range(4):
addScore += handle(board[row], direction)['addscore']
  board = list(map(list, zip(*board)))
 else:
  print("錯誤輸入!請輸入[W, S, A, D]或者對應小寫")
  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(右).')
 # 初始化游戲界面,游戲分數(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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持本站。

美國穩(wěn)定服務器

版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實時開通

自選配置、實時開通

免備案

全球線路精選!

全天候客戶服務

7x24全年不間斷在線

專屬顧問服務

1對1客戶咨詢顧問

在線
客服

在線客服:7*24小時在線

客服
熱線

400-630-3752
7*24小時客服服務熱線

關(guān)注
微信

關(guān)注官方微信
頂部