日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python新手實現(xiàn)2048小游戲

系統(tǒng) 1817 0

接觸 Python 不久,看到很多人寫2048,自己也搗鼓了一個,主要是熟悉Python語法。

程序使用Python3 寫的,代碼150行左右,基于控制臺,方向鍵使用輸入字符模擬。

演示圖片

Python新手實現(xiàn)2048小游戲_第1張圖片

2048.py

            
# -*- coding:UTF-8 -*-
#! /usr/bin/python3
 
import random
 
v = [[0, 0, 0, 0],
   [0, 0, 0, 0],
   [0, 0, 0, 0],
   [0, 0, 0, 0]]
 
def display(v, score):
    '''顯示界面
 
    '''
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[0][0], v[0][1], v[0][2], v[0][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[1][0], v[1][1], v[1][2], v[1][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[2][0], v[2][1], v[2][2], v[2][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[3][0], v[3][1], v[3][2], v[3][3]), '  Total score: ', score)
 
def init(v):
    '''隨機分布網(wǎng)格值
     
    '''
    for i in range(4):
        v[i] = [random.choice([0, 0, 0, 2, 2, 4]) for x in range(4)]
 
def align(vList, direction):
    '''對齊非零的數(shù)字
 
    direction == 'left':向左對齊,例如[8,0,0,2]左對齊后[8,2,0,0]
    direction == 'right':向右對齊,例如[8,0,0,2]右對齊后[0,0,8,2]
    '''
 
    # 移除列表中的0
    for i in range(vList.count(0)):
        vList.remove(0)
    # 被移除的0
    zeros = [0 for x in range(4 - len(vList))]
    # 在非0數(shù)字的一側(cè)補充0
    if direction == 'left':
        vList.extend(zeros)
    else:
        vList[:0] = zeros
     
def addSame(vList, direction):
    '''在列表查找相同且相鄰的數(shù)字相加, 找到符合條件的返回True,否則返回False,同時還返回增加的分數(shù)
     
    direction == 'left':從右向左查找,找到相同且相鄰的兩個數(shù)字,左側(cè)數(shù)字翻倍,右側(cè)數(shù)字置0
    direction == 'right':從左向右查找,找到相同且相鄰的兩個數(shù)字,右側(cè)數(shù)字翻倍,左側(cè)數(shù)字置0
    '''
    score = 0
    if direction == 'left':
        for i in [0, 1, 2]:
            if vList[i] == vList[i+1] != 0: 
                vList[i] *= 2
                vList[i+1] = 0
                score += vList[i]
                return {'bool':True, 'score':score}
    else:
        for i in [3, 2, 1]:
            if vList[i] == vList[i-1] != 0:
                vList[i-1] *= 2
                vList[i] = 0
                score += vList[i-1]
                return {'bool':True, 'score':score}
    return {'bool':False, 'score':score}
 
def handle(vList, direction):
    '''處理一行(列)中的數(shù)據(jù),得到最終的該行(列)的數(shù)字狀態(tài)值, 返回得分
 
    vList: 列表結(jié)構(gòu),存儲了一行(列)中的數(shù)據(jù)
    direction: 移動方向,向上和向左都使用方向'left',向右和向下都使用'right'
    '''
    totalScore = 0
    align(vList, direction)
    result = addSame(vList, direction)
    while result['bool'] == True:
        totalScore += result['score']
        align(vList, direction)
        result = addSame(vList, direction)
    return totalScore
     
 
def operation(v):
    '''根據(jù)移動方向重新計算矩陣狀態(tài)值,并記錄得分
    '''
    totalScore = 0
    gameOver = False
    direction = 'left'
    op = input('operator:')
    if op in ['a', 'A']:  # 向左移動
        direction = 'left'
        for row in range(4):
            totalScore += handle(v[row], direction)
    elif op in ['d', 'D']: # 向右移動
        direction = 'right'
        for row in range(4):
            totalScore += handle(v[row], direction)
    elif op in ['w', 'W']: # 向上移動
        direction = 'left'
        for col in range(4):
            # 將矩陣中一列復(fù)制到一個列表中然后處理
            vList = [v[row][col] for row in range(4)]
            totalScore += handle(vList, direction)
            # 從處理后的列表中的數(shù)字覆蓋原來矩陣中的值
            for row in range(4):
                v[row][col] = vList[row]
    elif op in ['s', 'S']: # 向下移動
        direction = 'right'
        for col in range(4):
            # 同上
            vList = [v[row][col] for row in range(4)]
            totalScore += handle(vList, direction)
            for row in range(4):
                v[row][col] = vList[row]
    else:
        print('Invalid input, please enter a charactor in [W, S, A, D] or the lower')
        return {'gameOver':gameOver, 'score':totalScore}
 
    # 統(tǒng)計空白區(qū)域數(shù)目 N
    N = 0
    for q in v:
      N += q.count(0)
    # 不存在剩余的空白區(qū)域時,游戲結(jié)束
    if N == 0:
        gameOver = True
        return {'gameOver':gameOver, 'score':totalScore}
 
    # 按2和4出現(xiàn)的幾率為3/1來產(chǎn)生隨機數(shù)2和4
    num = random.choice([2, 2, 2, 4]) 
    # 產(chǎn)生隨機數(shù)k,上一步產(chǎn)生的2或4將被填到第k個空白區(qū)域
    k = random.randrange(1, N+1)
    n = 0
    for i in range(4):
        for j in range(4):
            if v[i][j] == 0:
                n += 1
                if n == k:
                    v[i][j] = num
                    break
 
    return {'gameOver':gameOver, 'score':totalScore}
 
init(v)
score = 0
print('Input:W(Up) S(Down) A(Left) D(Right), press 
            
              .')
while True:
    display(v, score)
    result = operation(v)
    if result['gameOver'] == True:
        print('Game Over, You failed!')
        print('Your total score:', score)
    else:
        score += result['score']
        if score >= 2048:
            print('Game Over, You Win!!!')
            print('Your total score:', score)
            
          

以上所述就是本文給大家分享的全部代碼了,希望能夠?qū)Υ蠹覍W(xué)習(xí)Python有所幫助。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦?。。?/p>

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 兴文县| 文化| 任丘市| 运城市| 旌德县| 台山市| 从江县| 中牟县| 四会市| 来安县| 冀州市| 田东县| 霍山县| 墨玉县| 临清市| 涿州市| 灌云县| 彰化县| 临桂县| 长岭县| 大邑县| 健康| 鄂伦春自治旗| 罗城| 定陶县| 郓城县| 安仁县| 南江县| 若尔盖县| 澄江县| 沂南县| 郓城县| 武乡县| 贵阳市| 武汉市| 同江市| 马边| 青阳县| 酉阳| 连城县| 肇东市|