Skip to content

Instantly share code, notes, and snippets.

@mechamug
Created February 26, 2020 15:54
Show Gist options
  • Save mechamug/3e786a5af36f7af975cfa00d280b0231 to your computer and use it in GitHub Desktop.
Save mechamug/3e786a5af36f7af975cfa00d280b0231 to your computer and use it in GitHub Desktop.
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
import matplotlib.pyplot as plt
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
board = zeros((SIZE,SIZE),dtype=int)
plt.ion()
im = plt.imshow(board,cmap='spring')
im.set_clim(0,MAX)
plt.colorbar(label='Tiles')
plt.title('PyPlot 2048')
plt.tight_layout()
def draw():
global im
im.set_data(board)
fig = plt.gcf()
fig.canvas.draw()
fig.canvas.flush_events()
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