Advertisement
Guest User

Untitled

a guest
Mar 25th, 2014
630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. R=range
  2. G=lambda:[[0]*4for _ in R(4)]
  3. B=G()
  4.  
  5. def print_board(B):
  6.  print "\n".join(" ".join(("%4d"%c) if c else '   .' for c in row) for row in B)
  7.  
  8. #return (is_move,is_combination,new_src,new_dest)
  9. def combine(s,d):
  10.  if s<1or d<1:return (0,0,s or d)
  11.  if s==d:return (1,0,s+d)
  12.  return(0,s,d)
  13.  
  14.  
  15. #0=up, 1=right, 2=down, 3=left
  16. #direction -> (dx, dy, startx, xdirection, starty, ydirection)
  17. #Ds=[(-1,0,0,1,0,0),(0,-1,0,0,0,1),(1,0,2,-1,0,0),(0,1,0,0,2,-1)]
  18. #direction -> (dx, dy)
  19. Ds=[(0,-1),(1,0),(0,1),(-1,0)]
  20. #delta -> (iter_start, iter_end, iter_direction, source_direction)
  21. Js=[(0,4,1,0),(2,-1,-1,-1),(1,4,1,1)]
  22. Ss=[0,-1,1]
  23. def move(P,d):
  24.  C=G()
  25.  dx,dy=Ds[d]
  26.  sx,ex,ix,Sx=Js[dx]
  27.  sy,ey,iy,Sy=Js[dy]
  28.  while 1:
  29.   N=[r[:]for r in P]
  30.   for x in R(sx,ex,ix):
  31.    for y in R(sy,ey,iy):
  32.     src=N[y][x]
  33.     q,w=(y-Sy,x-Sx)
  34.     dest=N[q][w]
  35.     is_comb,next_src,next_dst=combine(src, dest)
  36.     if is_comb and(C[y][x]or C[q][w]):continue
  37.     #print "N[%d][%d]=%s,N[%d][%d]=%s --> %s, %s, comb=%s" % (
  38.     #    y, x, src, q, w, dest, next_src, next_dst, is_comb)
  39.     N[y][x]=next_src
  40.     N[q][w]=next_dst
  41.     C[q][w]+=is_comb
  42.   if N==P:break
  43.   P=N
  44.  return N
  45. def fill(N):
  46.  for x in R(4):
  47.   for y in R(4):
  48.    if N[y][x]==0:N[y][x]=2;return N
  49. moves=lambda P:[d for d in R(4)if move(P,d)!=P]
  50. ev=lambda P:sum((256,c)[c>0] for v in P for c in v)+P[3][3]*10+P[3][2]*9
  51. def move_ev(P,d):
  52.  return ev(move(P,d))
  53. def best(P,i):
  54.  if i==0:return(ev(P),-1)
  55.  M=moves(P)
  56.  return max((best(fill(move(P,d)),i-1)[0],d)for d in M)if M else (-9999,-1)
  57.  
  58. B[0][0]=2
  59. i=0
  60. res = '';go=0
  61. while B:
  62.  if i%1==0:print_board(B)
  63.  if not go and B[3][3]==2048:
  64.      print "Path to 2048:", res
  65.      if not go and raw_input("Continue (y/n)? ")[0]!='y':break
  66.      go=1
  67.  EV,MOVE=best(B,4)
  68.  if i%1==0:print "Best move: %s, with EV=%s" % ("awds"[MOVE], EV)
  69.  B=fill(move(B,MOVE))
  70.  res += `MOVE`
  71.  i+=1
  72.  
  73. print "Final position:"
  74. print_board(B)
  75. print "Path to final position:", res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement