栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python--2048(控制台运行)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python--2048(控制台运行)

import random

SIZE = 4

map = [[0 for i in range(SIZE)] for i in range(SIZE)]

score = 0


# 展示矩阵
def show(M):
    print("n" + "使用W A S D控制方向", end="")
    print("n" + " " * 25 + "Score: " + "{:}".format(score), end="")
    for i in range(SIZE):
        print("n")
        for j in range(SIZE):
            print("{: >6}".format(M[i][j]), end="")
    print("n")


def add(M):
    cnt = 0
    while True:
        p = random.randint(0, SIZE * SIZE - 1)
        if M[p // SIZE][p % SIZE] == 0:
            x = random.choice([2, 2, 2, 4])
            M[p // SIZE][p % SIZE] = x
            cnt += 1
        if cnt == 2:
            break
    return M


def over(M):
    for r in range(SIZE):
        for c in range(SIZE):
            if M[r][c] == 0:
                return False
    for r in range(SIZE):
        for c in range(SIZE - 1):
            if M[r][c] == M[r][c + 1]:
                return False
    for r in range(SIZE - 1):
        for c in range(SIZE):
            if M[r][c] == M[r + 1][c]:
                return False
    return True


def caculate(M):
    global score
    changed = False
    for a in M:
        b = []
        last = 0
        for v in a:
            if v != 0:
                if v == last:
                    s = b.pop() * 2
                    b.append(s)
                    score += s
                    last = 0
                else:
                    b.append(v)
                    last = v
        b += [0] * (SIZE - len(b))  # 弥补本行剩下的元素
        for i in range(SIZE):
            if a[i] != b[i]:
                changed = True
        a[:] = b
    return M, changed


def rotate90(M):
    M = [[M[c][r] for c in range(SIZE)] for r in reversed(range(SIZE))]
    return M


def moveUp():
    global map
    map = rotate90(map)
    if caculate(map)[1]:
        map = add(map)
    map = rotate90(map)
    map = rotate90(map)
    map = rotate90(map)


def moveRight():
    global map
    map = rotate90(map)
    map = rotate90(map)
    if caculate(map)[1]:
        map = add(map)
    map = rotate90(map)
    map = rotate90(map)


def moveDown():
    global map
    map = rotate90(map)
    map = rotate90(map)
    map = rotate90(map)
    if caculate(map)[1]:
        map = add(map)
    map = rotate90(map)


def moveLeft():
    global map
    if caculate(map)[1]:
        map = add(map)


map = add(map)
show(map)
while not over(map):
    cmd = input()
    if cmd == "w":
        moveUp()
    if cmd == 's':
        moveDown()
    if cmd == 'a':
        moveLeft()
    if cmd == 'd':
        moveRight()
    show(map)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/343959.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号