Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.59 KB | None | 0 0
  1. import pygame
  2. import sys
  3. import random
  4. import tkinter as tk
  5.  
  6.  
  7. SCORE = 0
  8. pygame.font.init()
  9. HEIGHT = 600
  10. WIDTH = 900
  11. MARGIN = 50
  12. cols = 4
  13. rows = 4
  14. board = None
  15. GRID_COLOR = (255, 255, 255)
  16. NUM_ON_BOX_COLOR = (0, 0, 0)
  17. BOARD_BACKGROUND_COLOR = (40, 122, 180)
  18. GAME_BACKGROUND_COLOR = (60, 142, 200)
  19. GUI_ON_RIGHT_COLOR = (20, 29, 30)
  20. SCORE_TEXT_COLOR = (255, 0, 0)
  21. TITLE_TEXT_COLOR = (156, 80, 210)
  22.  
  23.  
  24. VAL_TO_COLOR = {
  25.     2: (0, 255, 0),
  26.     4: (0, 255, 127),
  27.     8: (0, 250, 154),
  28.     16: (124, 252, 0),
  29.     32: (127, 255, 0),
  30.     64: (50, 205, 50),
  31.     128: (173, 255, 47),
  32.     256: (0, 128, 0),
  33.     1024: (34, 139, 34),
  34.     2048: (0, 100, 0),
  35.     4096: (154, 205, 50),
  36.     8192: (60, 179, 113),
  37.     16384: (46, 139, 87),
  38.     32768: (143, 188, 143),
  39.     65536: (107, 142, 35),
  40.     131072: (85, 107, 47),
  41.     262144: (128, 128, 0)
  42. }
  43.  
  44.  
  45. class Board(object):
  46.     def __init__(self):
  47.         self.pos = (MARGIN, MARGIN)
  48.         self.rows = rows
  49.         self.cols = cols
  50.         self.body = [[None, None, None, None],
  51.                      [None, None, None, None],
  52.                      [None, None, None, None],
  53.                      [None, None, None, None]]
  54.  
  55.     def update(self):
  56.         for event in pygame.event.get():
  57.             if event.type == pygame.QUIT:
  58.                 pygame.quit()
  59.                 sys.exit()
  60.             keys = pygame.key.get_pressed()
  61.             for key in keys:
  62.                 if keys[pygame.K_LEFT]:
  63.                     self.send_move("left")
  64.                     return
  65.                 elif keys[pygame.K_RIGHT]:
  66.                     self.send_move("right")
  67.                     return
  68.                 elif keys[pygame.K_UP]:
  69.                     self.send_move("up")
  70.                     return
  71.                 elif keys[pygame.K_DOWN]:
  72.                     self.send_move("down")
  73.                     return
  74.  
  75.     def draw(self, surface):
  76.         size_btw_x = (HEIGHT - 2 * MARGIN + 1) // self.cols
  77.         size_btw_y = (HEIGHT - 2 * MARGIN + 1) // self.rows
  78.         x = self.pos[1]
  79.         y = self.pos[0]
  80.         for l in range(self.cols + 1):
  81.             pygame.draw.line(surface, GRID_COLOR, (x, self.pos[1]), (x, HEIGHT - MARGIN))
  82.             x += size_btw_x
  83.         for l in range(self.rows + 1):
  84.             pygame.draw.line(surface, GRID_COLOR, (self.pos[0], y), (HEIGHT - MARGIN, y))
  85.             y += size_btw_y
  86.         for i in range(len(self.body)):
  87.             for obj in self.body[i]:
  88.                 if type(obj) is Box:
  89.                     obj.draw(surface)
  90.  
  91.     def send_move(self, dirn):
  92.         if dirn.__eq__("left"):
  93.             for i in range(len(self.body)):
  94.                 for j in range(1, len(self.body[i])):
  95.                     if type(self.body[i][j]) is Box:
  96.                         self.body[i][j].move("left")
  97.         elif dirn.__eq__("right"):
  98.             for i in range(len(self.body)):
  99.                 for j in range(len(self.body[i]) - 2, -1, -1):
  100.                     if type(self.body[i][j]) is Box:
  101.                         self.body[i][j].move("right")
  102.         elif dirn.__eq__("up"):
  103.             for i in range(1, len(self.body)):
  104.                 for j in range(len(self.body[i])):
  105.                     if type(self.body[i][j]) is Box:
  106.                         self.body[i][j].move("up")
  107.         elif dirn.__eq__("down"):
  108.             for i in range(len(self.body) - 2, -1, -1):
  109.                 for j in range(len(self.body[i])):
  110.                     if type(self.body[i][j]) is Box:
  111.                         self.body[i][j].move("down")
  112.         empty_spot = False
  113.         for i in range(len(self.body)):
  114.             for obj in self.body[i]:
  115.                 if obj is None:
  116.                     empty_spot = True
  117.         if empty_spot:
  118.             spawn_box()
  119.  
  120.     @staticmethod
  121.     def reset():
  122.         global board
  123.         board = Board()
  124.         spawn_box()
  125.  
  126.  
  127. class Box(object):
  128.     def __init__(self, yx, value):
  129.         self.color = VAL_TO_COLOR[value]
  130.         self.y = yx[0]
  131.         self.x = yx[1]
  132.         self.w = (HEIGHT - 2 * MARGIN + 1) // board.cols
  133.         self.h = (HEIGHT - 2 * MARGIN + 1) // board.rows
  134.         self.value = value
  135.         self.pos = (MARGIN + self.w * self.x, MARGIN + self.h * self.y)
  136.  
  137.     def move(self, dirn):
  138.         x = self.x
  139.         y = self.y
  140.         if dirn.__eq__("up"):
  141.             stop = 0
  142.             while y != stop:
  143.                 if board.body[y - 1][x] is None:
  144.                     board.body[y][x], board.body[y - 1][x] = board.body[y - 1][x], board.body[y][x]
  145.                     self.y -= 1
  146.                     y -= 1
  147.                     self.pos = (MARGIN + self.w * self.x, MARGIN + self.h * self.y)
  148.                     continue
  149.                 elif type(board.body[y - 1][x]) is Box:
  150.                     if self.value == board.body[y - 1][x].value:
  151.                         merge_box(self, board.body[y - 1][x])
  152.                 break
  153.         elif dirn.__eq__("down"):
  154.             stop = 3
  155.             while y != stop:
  156.                 if board.body[y + 1][x] is None:
  157.                     board.body[y][x], board.body[y + 1][x] = board.body[y + 1][x], board.body[y][x]
  158.                     self.y += 1
  159.                     y += 1
  160.                     self.pos = (MARGIN + self.w * self.x, MARGIN + self.h * self.y)
  161.                     continue
  162.                 elif type(board.body[y + 1][x]) is Box:
  163.                     if self.value == board.body[y + 1][x].value:
  164.                         merge_box(self, board.body[y + 1][x])
  165.                 break
  166.         elif dirn.__eq__("left"):
  167.             stop = 0
  168.             while x != stop:
  169.                 if board.body[y][x - 1] is None:
  170.                     board.body[y][x], board.body[y][x - 1] = board.body[y][x - 1], board.body[y][x]
  171.                     self.x -= 1
  172.                     x -= 1
  173.                     self.pos = (MARGIN + self.w * self.x, MARGIN + self.h * self.y)
  174.                     continue
  175.                 elif type(board.body[y][x - 1]) is Box:
  176.                     if self.value == board.body[y][x - 1].value:
  177.                         merge_box(self, board.body[y][x - 1])
  178.                 break
  179.         elif dirn.__eq__("right"):
  180.             stop = 3
  181.             while x != stop:
  182.                 if board.body[y][x + 1] is None:
  183.                     board.body[y][x], board.body[y][x + 1] = board.body[y][x + 1], board.body[y][x]
  184.                     self.x += 1
  185.                     x += 1
  186.                     self.pos = (MARGIN + self.w * self.x, MARGIN + self.h * self.y)
  187.                     continue
  188.                 elif type(board.body[y][x + 1]) is Box:
  189.                     if self.value == board.body[y][x + 1].value:
  190.                         merge_box(self, board.body[y][x + 1])
  191.                 break
  192.  
  193.     def draw(self, surface):
  194.         self.color = VAL_TO_COLOR[self.value]
  195.         pygame.draw.rect(surface, self.color, (self.pos[0] + 1, self.pos[1] + 1, self.w - 1, self.h - 1))
  196.         if self.value >= 1000000:
  197.             size = 30
  198.         elif self.value >= 100000:
  199.             size = 40
  200.         else:
  201.             size = 50
  202.         font = pygame.font.SysFont(None, size, "bold")
  203.         text = font.render(str(self.value), False, NUM_ON_BOX_COLOR)
  204.         surface.blit(text, (self.pos[0] + (self.w - text.get_rect().width) / 2, self.pos[1] +
  205.                             (self.h - text.get_rect().height) / 2))
  206.  
  207.  
  208. def merge_box(box_hitter, box_target):
  209.     global SCORE
  210.     box_target.value += box_hitter.value
  211.     SCORE += box_target.value
  212.     board.body[box_hitter.y][box_hitter.x] = None
  213.  
  214.  
  215. def spawn_box():
  216.     x = random.randint(0, 3)
  217.     y = random.randint(0, 3)
  218.     while type(board.body[y][x]) is Box:
  219.         x = random.randint(0, 3)
  220.         y = random.randint(0, 3)
  221.     val = random.choice([2, 4])
  222.     o = Box((y, x), val)
  223.     board.body[y][x] = o
  224.  
  225.  
  226. def draw_menu(surface):
  227.     pygame.draw.rect(surface, BOARD_BACKGROUND_COLOR, (MARGIN, MARGIN, HEIGHT - 2 * MARGIN, HEIGHT - 2 * MARGIN))
  228.     x = pygame.draw.rect(surface, GUI_ON_RIGHT_COLOR, (HEIGHT - MARGIN / 2, MARGIN, WIDTH - HEIGHT, HEIGHT - 2 * MARGIN))
  229.     font = pygame.font.SysFont("Times New Roman", 30, "bold")
  230.     s_text = font.render(f"Score: {SCORE}", False, SCORE_TEXT_COLOR)
  231.     surface.blit(s_text, (HEIGHT - MARGIN / 2 + (x.width - s_text.get_rect().width) / 2, MARGIN + x.height / 2))
  232.     t_font = pygame.font.SysFont("Perpetua", 100, "bold")
  233.     title_text = t_font.render("2048", False, TITLE_TEXT_COLOR)
  234.     surface.blit(title_text, (HEIGHT - MARGIN / 2 + (x.width - title_text.get_rect().width) / 2, MARGIN + x.height / 8))
  235.  
  236.  
  237. def redraw_window(surface):
  238.     surface.fill(GAME_BACKGROUND_COLOR)
  239.     draw_menu(surface)
  240.     board.draw(surface)
  241.     pygame.display.update()
  242.  
  243.  
  244. def check_game_over():
  245.     for rs in range(len(board.body)):
  246.         for obj in board.body[rs]:
  247.             if obj is None:
  248.                 return False
  249.     for i in range(len(board.body)):
  250.         for j in range(1, len(board.body[i])):
  251.             if board.body[i][j].value == board.body[i][j - 1].value:
  252.                 return False
  253.     for i in range(len(board.body)):
  254.         for j in range(len(board.body[i]) - 2, -1, -1):
  255.             if board.body[i][j].value == board.body[i][j + 1].value:
  256.                 return False
  257.     for i in range(1, len(board.body)):
  258.         for j in range(len(board.body[i])):
  259.             if board.body[i][j].value == board.body[i - 1][j].value:
  260.                 return False
  261.     for i in range(len(board.body) - 2, -1, -1):
  262.         for j in range(len(board.body[i])):
  263.             if board.body[i][j].value == board.body[i + 1][j].value:
  264.                 return False
  265.     return True
  266.  
  267.  
  268. def save_score(name, master):
  269.     global SCORE
  270.     x = name
  271.     while " " in x:
  272.         x = x.replace(" ", "")
  273.     if x.__eq__(""):
  274.         name = "UNNAMED"
  275.     num = 0
  276.     try:
  277.         with open("scores.txt", "r") as file:
  278.             for line in file:
  279.                 num += 1
  280.     except FileNotFoundError:
  281.         with open("scores.txt", "w") as file:
  282.             file.write("\t\t\t{:11} | \t\t{:10} \n".format("NAME", "SCORE"))
  283.         with open("scores.txt", "r") as file:
  284.             for line in file:
  285.                 num += 1
  286.     with open("scores.txt", "a") as file:
  287.         file.write("{})\t\t{:15} | {:10}\n".format(num, name[:15], SCORE))
  288.     SCORE = 0
  289.     try:
  290.         master.destroy()
  291.     except:
  292.         pass
  293.  
  294.  
  295. def mbox():
  296.     r_h = 500
  297.     r_w = 500
  298.     root = tk.Tk()
  299.     root.title("You lost")
  300.     root.attributes("-topmost", True)
  301.  
  302.     canvas = tk.Canvas(root, height=r_h, width=r_w, bg="orange")
  303.     canvas.pack()
  304.  
  305.     prompt = tk.Label(canvas, text=f"Score: {SCORE}.\nPlease Enter your name to\nsave your score:", bg="orange",
  306.                       font=("Courier", 22, "bold"))
  307.     prompt.place(anchor="n", relx=0.5, rely=0.2, relwidth=0.9, relheight=0.3)
  308.  
  309.     entry = tk.Entry(canvas, font=("Calibri", 28, "bold"))
  310.     entry.place(anchor="n", relx=0.5, rely=0.45, relwidth=0.8, relheight=0.1)
  311.  
  312.     save_button = tk.Button(canvas, font=("Courier", 22, "bold"), text="Save",
  313.                             command=lambda: save_score(entry.get(), root))
  314.     save_button.place(anchor="n", relx=0.5, rely=0.56, relwidth=0.3, relheight=0.1)
  315.  
  316.     root.mainloop()
  317.  
  318.  
  319. def main():
  320.     global board
  321.     window = pygame.display.set_mode((WIDTH, HEIGHT))
  322.     clock = pygame.time.Clock()
  323.     board = Board()
  324.     spawn_box()
  325.     flag = True
  326.     while flag:
  327.         pygame.time.delay(50)
  328.         clock.tick(10)
  329.         if check_game_over():
  330.             mbox()
  331.             board.reset()
  332.         board.update()
  333.         redraw_window(window)
  334.  
  335.  
  336. if __name__ == "__main__":
  337.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement