#! /usr/bin/python3 import random, copy def game_logic(l): oldHash = hash(tuple(l)) line_state = True global moved merge = True while line_state: for i in range(board_line-1): if l[i] == None and l[i+1] != None: mi=l.pop(i+1) l.pop(i) l.insert(i,mi) l.insert(i+1,None) elif l[i] != None and l[i] == l[i+1] and merge != False: mi=l.pop(i) l.insert(i,int(mi)*2) mi=l.pop(i+1) l.insert(i+1,None) merge = False oldHash = hash(tuple(l)) moved = True newHash = hash(tuple(l)) if oldHash == newHash: # print('Exiting: Boxes didn't move') line_state = False else: # print('Repeating: Boxes moved') oldHash = newHash moved = True return l def movement(): m = input('\nMove the numbers: ') global moved global board global board_reset moved=False board_temp=copy.deepcopy(board) #TODO: Simplify movement if m == 'h': for i in range(0,board_size,board_line): # print('line',i) board[i:i+board_line]=game_logic(board[i:i+board_line]) elif m == 'j': for i in range(board_line): rl = board[i::board_line] # print('column',i) board[i::board_line]=game_logic(rl[::-1])[::-1] elif m == 'k': for i in range(board_line): # print('column',i) rl = board[i::board_line] board[i::board_line]=game_logic(rl) elif m == 'l': for i in range(0,board_size,board_line): # print('line',i) rl = board[i:i+board_line] board[i:i+board_line]=game_logic(rl[::-1])[::-1] elif m == 'u': board=board_reset print(board) #raise ValueError('Can not move this way') else: raise ValueError('Can not move this way') if m != 'u' and moved == True: board_reset=copy.deepcopy(board_temp) # try: # direction in ['h','j','k','l'] # print(direction) # except: # print('wtf') def print_board(): for i in range(0,board_size,board_line): print(board[i:i+board_line]) def add_number(): global board indices = [i for i, x in enumerate(board) if x == None] p = random.choice(indices) board[p] = random.choices([2,4],weights=[80,20])[0] print('\nNew number at position',p+1) #TODO: Make a class so i can remove globals and simplify code # class Game(): # def init(): global board global board_reset game_state = True board = [] board_line = 3 board_size = board_line**2 for i in range(board_size): board.insert(i,None) add_number() board_reset = copy.deepcopy(board) # def run(): global moved while game_state: print('\nnew choice') print_board() try: movement() except ValueError: # continue pass if moved == False: print('DID NOT MOVE') continue try: add_number() except IndexError: # catch game over here game_state = False print('Game Over')