Skip to content

Instantly share code, notes, and snippets.

@mechamug
Created February 26, 2020 15:50
Show Gist options
  • Save mechamug/0e47561e9d5017e85323673ee285a314 to your computer and use it in GitHub Desktop.
Save mechamug/0e47561e9d5017e85323673ee285a314 to your computer and use it in GitHub Desktop.
Python 2048
from numpy import any, all, where, zeros
from random import choice, randint
from itertools import product
from readchar import readchar
from colorama import Fore as cf
SIZE, MAX = 5, 10
def add_tile(a):
a[choice([*zip(*where(a==0))])] = randint(1,2)
def can_combine(v):
return any([v[x]==v[x+1] for x in range(len(v) - 1)])
def can_move(a):
return any(a==0) or any([can_combine(v) for v in [*a]+[*a.T]])
def try_combine(v,x,y):
if x < SIZE and y < SIZE and v[x] == v[y]:
v[x],v[y] = v[x]+1,0
if v[x] == MAX:
print("You're a winner, Harry.")
quit()
return True
return False
def compact(v):
f,m = 0,False
for r in range(len(v)):
if v[r] == 0: continue
m = try_combine(v,r,r+1) or m
while f in range(len(v)) and v[f] != 0: f += 1
if f < r:
v[r],v[f] = 0,v[r]
try_combine(v,f-1,f)
m = True
return m
def move(a,dir):
m = False
for x in range(SIZE):
if dir in 'kw': m = compact(a[:,x]) or m
if dir in 'js': m = compact(a[::-1,x]) or m
if dir in 'ha': m = compact(a[x,:]) or m
if dir in 'ld': m = compact(a[x,::-1]) or m
return m
def draw():
colors = [*vars(cf).values()]
tiles = '*123456789X'
print(chr(27) + "[2J")
for r in range(SIZE):
for c in range(SIZE):
print(colors[board[r,c]+1] + tiles[board[r,c]], end=' ')
print(cf.RESET)
board = zeros((SIZE,SIZE),dtype=int)
for _ in range(2): add_tile(board)
while True:
draw()
if not can_move(board):
print("You lost.")
quit()
key = readchar()
m = move(board,key)
if m: add_tile(board)
if key == 'q':
quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment