Advertisement
Guest User

Python 2048 main

a guest
May 2nd, 2014
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. # random number generator
  2. import random
  3. # grid utility routines
  4. import util
  5. # grid value merging routines
  6. import push
  7.  
  8. def add_block (grid):
  9. """add a random number to a random location on the grid"""
  10. # set distributon of number possibilities
  11. options = [2,2,2,2,2,4]
  12. # get random number
  13. chosen = options[random.randint(0,len(options)-1)]
  14. found = False
  15. while (not found):
  16. # get random location
  17. x = random.randint (0, 3)
  18. y = random.randint (0, 3)
  19. # check and insert number
  20. if (grid[x][y] == 0):
  21. grid[x][y] = chosen
  22. found = True
  23.  
  24. def play ():
  25. """generate grid and play game interactively"""
  26. # create grid
  27. grid = []
  28. util.create_grid (grid)
  29. # add 2 starting random numbers
  30. add_block (grid)
  31. add_block (grid)
  32. won_message = False
  33. while (True):
  34. util.print_grid (grid)
  35. key = input ("Enter a direction:\n")
  36. if (key in ['x', 'u', 'd', 'l', 'r']):
  37. # make a copy of the grid
  38. saved_grid = util.copy_grid (grid)
  39. if (key == 'x'):
  40. # quit the game
  41. return
  42. # manipulate the grid depending on input
  43. elif (key == 'u'):
  44. push.push_up (grid)
  45. elif (key == 'd'):
  46. push.push_down (grid)
  47. elif (key == 'r'):
  48. push.push_right (grid)
  49. elif (key == 'l'):
  50. push.push_left (grid)
  51. # check for a grid with no more gaps or legal moves
  52. if util.check_lost (grid):
  53. print ("Game Over!")
  54. return
  55. # check for a grid with the final number
  56. elif util.check_won (grid) and not won_message:
  57. print ("Won!")
  58. won_message = True
  59. # finally add a random block if the grid has changed
  60. if not util.grid_equal (saved_grid, grid):
  61. add_block (grid)
  62.  
  63. # initialize the random number generator to a fixed sequence
  64. random.seed (12)
  65. # play the game
  66. play ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement