c17.py

Created by aquaebm

Created on June 16, 2024

1.5 KB

Did you know C17 is 2048 in base 13? Definitely not a Dragon Ball character…

Use the arrow keys to slide and merge similar tiles to aim for 2048 (or higher ;))


from util import *
from random import choice
def sr(n):
  s=-(n<0)
  return range(s,n+s,s or 1)
class Grid:
  def __init__(s,l):
    s.s=l
    s.grid=[[0]*l for _ in range(l)]
  def __getitem__(s,x):return s.grid[x]
  def draw(s):
    l=222//s.s
    hl=l>>1
    for j,row in enumerate(s.grid):
      for i,v in enumerate(row):
        x,y=49+l*j,l*i
        col=(21*(11-v),42*(5-v),63*(3-v))
        fill_rect(x,y,l,l,col)
        if v:
          draw_str_centered(str(2**v),x+hl,y+hl,comp_col(col),col)
  def coords(s,i,dx,dy):
    n=s.s
    l=(i for _ in range(n))
    return zip(sr(dx*n) or l,sr(dy*n) or l)
  def slide(s,i,dx,dy):
    n=0
    for cx,cy in s.coords(i,dx,dy):
      px,py=cx-dx*n,cy-dy*n
      i=s[cx][cy]
      s[px][py],s[cx][cy]=i,s[px][py]
      n+=i==0
  def merge(s,i,dx,dy):
    for(px,py),(cx,cy)in windows(s.coords(i,dx,dy),2):
      same=s[px][py]!=0 and s[px][py]==s[cx][cy]
      s[px][py]+=same
      s[cx][cy]*=not same
  def try_spawn_tile(s):
    d=range(s.s)
    empty=[(i,j) for j in d for i in d if not s[i][j]]
    if empty:
      x,y=choice(empty)
      s[x][y]=choice((1,1,1,2))
  def play_move(s,dx,dy):
    for i in range(s.s):
      s.slide(i,dx,dy)
      s.merge(i,dx,dy)
      s.slide(i,dx,dy)
  def start_game(s):
    k=KeyPressHandler((0,1,2,3))
    s.try_spawn_tile()
    while True:
      s.try_spawn_tile()
      s.draw()
      dx,dy=0,0
      while(dx,dy)==(0,0):dx,dy=k[0]-k[3],k[1]-k[2]
      s.play_move(dx,dy)
def run(n):Grid(n).start_game()
ARGS={"n":4}
run(**ARGS)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.