Advertisement
Guest User

2048

a guest
Jun 20th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.43 KB | None | 0 0
  1. import math
  2. import random
  3. import time
  4. import turtle as t
  5.  
  6. grid=[['']*4,['']*4,['']*4,['']*4]
  7.  
  8. max_digits = 5
  9.  
  10. # displays the board via command line for debugging
  11. def gridify(grid):
  12.     rtn_str = "-"*(len(grid[0])*(max_digits + 2) + 5) + "\n"
  13.     for row in grid:
  14.         rtn_str += "|"
  15.         for num in row:
  16.             digits = len(str(num))
  17.             rtn_str += " " * int((max_digits-len(str(num)))/2 + 1) + str(num) + " " * math.ceil((max_digits-len(str(num)))/2 + 1) + "|"
  18.         rtn_str += "\n" + "-"*(len(grid[0])*(max_digits + 2) + 5) + "\n"
  19.     return rtn_str
  20.  
  21. # insert a new tile at random location
  22. def newtile(grid):
  23.     # FILL IN HERE
  24.  
  25.     # create empty list named empty_spots
  26.     empty_spots =[]
  27.     # loop through up to 4
  28.     for i in range(4):
  29.         # loop through up to 4
  30.         for j in range(4):
  31.             # check if grid at spot is empty
  32.             if grid[i][j] == "":
  33.                 # append position to empty_spots
  34.                 empty_spots.append((i, j))
  35.     # create variable named spot and choose randomly from empty_spots
  36.     spot = random.choice(empty_spots)
  37.     # replace grid with a random number from [2,2,2,2,4]
  38.     grid[spot[0]][spot[1]] = random.choice([2,2,2,2,4])
  39.  
  40.     pass
  41.  
  42. score = 0
  43.  
  44. # moves all tiles left and increments score as necessary
  45. def left(grid):
  46.     score=0
  47.     for i in range(4):
  48.         # placements are finalized left to right, tracks which spots have combined to prevent double combinations
  49.         combined=[False]*4
  50.         for j in range(4):
  51.             # skip blanks
  52.             if grid[i][j]=="":
  53.                 continue
  54.             # pick up number encountered
  55.             moving=grid[i][j]
  56.             grid[i][j]=""
  57.             # move number to the left until an end case is hit
  58.             for spot in range(j,-2,-1):
  59.                 # case 1: ran off edge of row - place number in first spot
  60.                 if spot==-1:
  61.                     grid[i][0]=moving
  62.                     break
  63.                 # skip blanks
  64.                 if grid[i][spot]=="":
  65.                     continue
  66.                 # case 2: found same number to combine with
  67.                 if grid[i][spot]==moving and not combined[spot]:
  68.                     grid[i][spot]*=2
  69.                     score+=moving*2
  70.                     combined [spot]=True
  71.                     break
  72.                 # case 3: found different number or number is already combined
  73.                 grid[i][spot+1]=moving
  74.                 break
  75.     return score
  76.  
  77. def right(grid):
  78.     pass
  79.     # score=0
  80.     # for i in range(4):
  81.     #   combined=[False]*4
  82.     #   for j in range(3,-1,-1):
  83.             # FILL IN HERE
  84.  
  85.             # skip blank
  86.  
  87.             # pick up number encountered
  88.  
  89.             # move number right until 4th spot
  90.            
  91.                 # case 1: ran off edge of row - place number in last spot
  92.                
  93.                 # skip blanks
  94.                
  95.                 # case 2: found same number to combine with
  96.            
  97.                 # case 3: found different number or number is already combined
  98.                
  99.     # return score
  100.  
  101. def up(grid):
  102.     score=0
  103.     for j in range(4):
  104.         combined=[False]*4
  105.         for i in range(4):
  106.             if grid[i][j]=="":
  107.                 continue
  108.             moving=grid[i][j]
  109.             grid[i][j]=""
  110.             for spot in range(i,-2,-1):
  111.                 if spot==-1:
  112.                     grid[0][j]=moving
  113.                     break
  114.                 if grid[spot][j]=="":
  115.                     continue
  116.                 if grid[spot][j]==moving and not combined[spot]:
  117.                     grid[spot][j]*=2
  118.                     score+=moving*2
  119.                     combined [spot]=True
  120.                     break
  121.                 grid[spot+1][j]=moving
  122.                 break
  123.     return score
  124.  
  125. def down(grid):
  126.     # FILL IN HERE
  127.     pass
  128.  
  129.  
  130. # Check whether a particular move is valid (changes the board state)
  131. def valid_move(grid,move):
  132.     grid2=[row.copy() for row in grid]
  133.     move(grid2)
  134.     if grid2 !=grid:
  135.         return True
  136.  
  137. # Command line user input (for debugging or before graphics implementation)
  138. def user_input(grid):
  139.     while True:
  140.         response=input("Move using W,A,S,D\n").lower()
  141.         if response=="w":
  142.             if valid_move(grid, up):
  143.                 return up(grid)
  144.         elif response=="a":
  145.             if valid_move(grid, left):
  146.                 return left(grid)
  147.         elif response=="s":
  148.             if valid_move(grid, down):
  149.                 return down(grid)
  150.         elif response=="d":
  151.             if valid_move(grid, right):
  152.                 return right(grid)
  153.         else:
  154.             print ("Invalid Input Try Again")
  155.  
  156. # Check for win condition
  157. def is_win(grid):
  158.     # FILL IN HERE
  159.     pass
  160.     # loop through rows in grid
  161.     for row in grid
  162.         # check if number 2048 is in the row
  163.         if 2048 in row:
  164.             # return true if number 2048 in row
  165.             return True
  166.     # return False otherwise
  167.     return False
  168.    
  169.  
  170. # Check for loss condition
  171. def is_lose(grid):
  172.     # FILL IN HERE
  173.    
  174.     # check if there are any valid moves left (left, right, up, dow
  175.     return not valid_move(grid, left) and not valid_move(grid, right) and not valid_move(grid, up) and not valid_move(grid, down)
  176.  
  177. # Graphics helper to draw a square
  178. def draw_square(size,position,color1,color2):
  179.     # FILL IN HERE
  180.    
  181.     # bring turtle pen up
  182.     t.penup()
  183.     # put turtle in position
  184.     t.setposition(position)
  185.     # bring pen down
  186.     t.pendown()
  187.     # set pen color to color1 and color2
  188.     t.color(color1, color2)
  189.     # begin the pen fill
  190.     t.begin_fill()
  191.     # Loop up to number 4
  192.     for i in range(4):
  193.         # move forward size amount of steps with turtle
  194.         t.forward(size)
  195.         # turn() right 90 degrees with turtle
  196.         t.right(90)
  197.     # end the pen fill
  198.     t.end_fill()
  199.  
  200.  
  201. # Color scheme choices
  202. bgcolor="#3873ad"
  203. gridcolor="#8bb3da"
  204. tilecolor="#d8e6f3"
  205.    
  206. # Draw background grid
  207. def drawgrid():
  208.     draw_square(640,(-320,320),bgcolor,bgcolor)
  209.     for i in range(4):
  210.         for j in range(4):
  211.             draw_square(140,(-320+16+156*j,320-16-156*i),gridcolor,gridcolor)
  212.  
  213. # Helper to change color of tile
  214. def change_tile_color(number, color):
  215.     # FILL IN HERE
  216.     pass
  217.  
  218.  
  219. # Helper to draw a tile with a number
  220. def draw_tile(number,position):
  221.     # FILL IN HERE
  222.    
  223.     # draw square with size of 140, position, and tilecolor
  224.     draw_square(140, position, tilecolor, tilecolor)
  225.     # set color of turtle to blue and gold
  226.     t.color("blue","gold")
  227.     # bring the pen up
  228.     t.penup()
  229.     # put turtle in x=position[0] + 70, y = position[1] - 107
  230.     t.setposition(position[0] + 70, position[1] - 107)
  231.     # put the pen down
  232.     t.pendown()
  233.     # write the number with turtle
  234.     t.write(number, align="center", font=("Ubuntu", 48, "normal"))
  235.  
  236.  
  237. # Can_move prevents the user from spamming buttons before the graphics have finished updating
  238. can_move=True
  239.  
  240. # Render the grid on the background
  241. def render():
  242.     t.clear()
  243.     drawgrid()
  244.     for i in range(4):
  245.         for j in range(4):
  246.             if grid[i][j]!="":
  247.                 draw_tile(grid[i][j],(-320+16+156*j,320-16-156*i))
  248.     global can_move
  249.     t.penup()
  250.     t.goto((320,320))
  251.     t.pendown()
  252.     t.write("Score:"+str(score),align="right",font=("Ubuntu",60,"normal"))
  253.     can_move=True
  254.     t.update()
  255.  
  256. # Event handlers for the different directions
  257. def handle_left():
  258.     global can_move
  259.     if can_move and valid_move(grid,left):
  260.         can_move=False
  261.         global score
  262.         score+=left(grid)
  263.         newtile(grid)
  264.         render()
  265.         if is_win (grid):
  266.             t.goto((0,0))
  267.             t.write("You Win!",align="center",font=("Ubuntu",60,"normal"))
  268.             time.sleep(10)
  269.             t.bye()
  270.         if is_lose (grid):
  271.             t.write("You lose!",align="center",font=("Ubuntu",60,"normal"))
  272.             t.update()
  273.             time.sleep(10)
  274.             t.bye()
  275.  
  276. def handle_right():
  277.     global can_move
  278.     # FILL IN HERE
  279.  
  280.  
  281. def handle_up():
  282.     global can_move
  283.     if can_move and valid_move(grid,up):
  284.         can_move=False
  285.         global score
  286.         score+=up(grid)
  287.         newtile(grid)
  288.         render()
  289.         if is_win (grid):
  290.             t.goto((0,0))
  291.             t.write("You Win!",align="center",font=("Ubuntu",60,"normal"))
  292.             time.sleep(10)
  293.             t.bye()
  294.         if is_lose (grid):
  295.             t.write("You lose!",align="center",font=("Ubuntu",60,"normal"))
  296.             t.update()
  297.             time.sleep(10)
  298.             t.bye()
  299.  
  300. def handle_down():
  301.     global can_move
  302.     # FILL IN HERE
  303.  
  304.  
  305. # Set up the game
  306. newtile(grid)
  307. newtile(grid)
  308. t.ht()
  309. t.getscreen().delay(0)
  310. t.tracer(0,0)
  311. render()
  312. t.onkey(handle_left,"Left")
  313. t.onkey(handle_right,"Right")
  314. t.onkey(handle_up,"Up")
  315. t.onkey(handle_down,"Down")
  316. t.listen()
  317. t.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement