From 64c44e7b756fece019c8fa1b4a534508cce51ee7 Mon Sep 17 00:00:00 2001 From: Albert Tan Date: Thu, 13 Apr 2023 20:45:42 +0800 Subject: yes --- 2048.py | 150 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 2048.py diff --git a/2048.py b/2048.py new file mode 100644 index 0000000..3de8fe2 --- /dev/null +++ b/2048.py @@ -0,0 +1,150 @@ +import random +import time +import sys + +arr = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] + + +def show(): + out = "\n" + for i in arr: + for j in i: + out += str(j) + out += "\t" + out += "\n\n" + out += "----------------------------\n" + print(out) + + +def generate(): + empty = [] + flag = 0 + for i in range(4): + for j in range(4): + if arr[i][j] == 0: + empty.append([i, j]) + elif arr[i][j] == 2048: + flag = 1 + if flag: + return 2 + elif len(empty) == 0: + return 1 + else: + pos = random.choice(empty) + arr[pos[0]][pos[1]] = random.choice([2, 2, 4]) + return 0 + + +def moveleft(): + for i in range(4): + i2 = [0] + arr[i] + tmp = [] + lastitem = 0 + for j in range(1, 5): + if i2[j] != 0: + if i2[j] != lastitem: + tmp.append(i2[j]) + lastitem = i2[j] + else: + tmp[-1] *= 2 + lastitem = 0 + for k in range(4 - len(tmp)): + tmp.append(0) + arr[i] = tmp + + +def moveright(): + for i in range(4): + i2 = arr[i] + [0] + tmp = [] + lastitem = 0 + for j in range(3, -1, -1): + if i2[j] != 0: + if i2[j] != lastitem: + tmp = [i2[j]] + tmp + lastitem = i2[j] + else: + tmp[0] *= 2 + lastitem = 0 + for k in range(4 - len(tmp)): + tmp = [0] + tmp + arr[i] = tmp + +def moveup(): + for i in range(4): + i2 = [] + tmp = [] + lastitem = 0 + for j in arr: + i2.append(j[i]) + i2 = [0] + i2 + for j in range(1, 5): + if i2[j] != 0: + if i2[j] != lastitem: + tmp.append(i2[j]) + lastitem = i2[j] + else: + tmp[-1] *= 2 + lastitem = 0 + for k in range(4 - len(tmp)): + tmp.append(0) + for j in range(4): + arr[j][i] = tmp[j] + +def movedown(): + for i in range(4): + i2 = [] + tmp = [] + lastitem = 0 + for j in arr: + i2.append(j[i]) + i2 = i2 + [0] + for j in range(3, -1, -1): + if i2[j] != 0: + if i2[j] != lastitem: + tmp = [i2[j]] + tmp + lastitem = i2[j] + else: + tmp[0] *= 2 + lastitem = 0 + for k in range(4 - len(tmp)): + tmp = [0] + tmp + for j in range(4): + arr[j][i] = tmp[j] + +def move(): + action = input("Action (W, A, S, D): ").lower() + if action == "w": + moveup() + elif action == "a": + moveleft() + elif action == "s": + movedown() + elif action == "d": + moveright() + else: + print("Invalid Input") + move() + + +generate() +show() +sys.setrecursionlimit(1) + +while True: + try: + move() + except RecursionError: + print("Too much wrong attempts! You lost\n") + break + x = generate() + if x == 2: + show() + print("You Won\n") + break + elif x: + show() + print("You lost\n") + break + else: + show() -- cgit v1.2.3