Example #1
0
class ControllerTest(unittest.TestCase):
	
	grid = None

	def setUp(self):
		self.grid = Grid()
		self.grid.writeCell("cell content",(0,0))	
		self.grid.writeCell("one on one",(1,1))	

	def test_cell_click(self):
		"""when a cell is clicked, its text should appear 
			in the top_text"""

		controller = Controller(self.grid)

		controller.clickAt((0,0))
		self.assertEqual("cell content",controller.getTopText())


	def test_top_text_edit(self):
		controller = Controller(self.grid)
		controller.clickAt((1,1))
		controller.writeTopText("A new hope")

		self.assertEqual("A new hope", controller.getCurrentCellContent())
Example #2
0
    def update(self, event):
        """
        Method to react to keyboard events

        @param event: The Tk event fired
        @type event: tkinter.Event
        """
        if self.mode == Modes.MODE_PLAY:
            if event.keysym in [v.value for v in Directions]:
                if not self.game.ended_game:
                    self.game.play_one_direction(Directions(event.keysym), 0)
                    self.update_grid()
                if self.game.ended_game:
                    self.game.save_game(self.base_path)
                    print(self.game.history)
                    print("END OF GAME after {} turns with score {}".format(self.game.round_count,
                                                                            self.game.current_score))
            elif event.keysym in ["c"]:
                self.game.ended_game = False
                if len(self.game.history.grid_history) > 1:
                    self.game.history.direction_state_history.pop()
                    self.game.history.direction_index_history.pop()
                    self.game.history.grid_history.pop()
                    self.game.history.score_history.pop()
                    self.game.round_count -= 1
                    t_str_state = self.game.history.grid_history[-1]
                    self.grid.grid = Grid.from_string(t_str_state, self.nb_rows, self.nb_columns)
                    self.game.current_score = self.game.history.score_history[-1]
                    self.update_grid()

        elif self.mode == Modes.MODE_REPLAY:
            if event.keysym == "Right":
                if self.game.round_count + 1 < len(self.game.history.grid_history):
                    self.game.round_count += 1
            elif event.keysym == "Left":
                if self.game.round_count - 1 >= 0:
                    self.game.round_count -= 1
            elif event.keysym == "Up":
                if self.game.round_count + 50 < len(self.game.history.grid_history):
                    self.game.round_count += 50
                else:
                    self.game.round_count = len(self.game.history.grid_history) - 1
            elif event.keysym == "Down":
                if self.game.round_count - 50 >= 0:
                    self.game.round_count -= 50
                else:
                    self.game.round_count = 0
            t_str_state = self.game.history.grid_history[self.game.round_count]
            self.grid.grid = Grid.from_string(t_str_state, self.nb_rows, self.nb_columns)
            self.game.current_score = self.game.history.score_history[self.game.round_count]
            self.update_grid()
Example #3
0
    def something_moved(self, previous_state):
        """
        Method to determine if at least one tile has moved between two Grid snapshots (current, previous)

        @param previous_state: the previous Grid state (or snapshot) in inline str representation format
        @type previous_state: str
        @return: whether at least one tile has moved compared to the previous Grid snapshot
        @rtype: bool
        """
        state_a = Grid.from_string(previous_state, self.nb_rows,
                                   self.nb_columns)
        state_b = Grid.from_string(self.grid_history[-1], self.nb_rows,
                                   self.nb_columns)
        return not np.array_equal(state_a, state_b)
 def __init__(self):
     self.grid = Grid(10, 20)
     self.game_display_mode = pygame.display.set_mode((380, 443))
     self.game_display = GameDisplay(self.game_display_mode, (0, 0, 0))
     self.grid_display = GridDisplay(self.game_display_mode, self.grid)
     self.pygame_display = PygameDisplay()
     self.colour = (5, 205, 25)
     self.velocity_time = 0.4
class ControllerTest(unittest.TestCase):

    grid = None

    def setUp(self):
        self.grid = Grid()
        self.grid.writeCell("cell content", (0, 0))
        self.grid.writeCell("one on one", (1, 1))

    def test_cell_click(self):
        """when a cell is clicked, its text should appear 
			in the top_text"""

        controller = Controller(self.grid)

        controller.clickAt((0, 0))
        self.assertEqual("cell content", controller.getTopText())

    def test_top_text_edit(self):
        controller = Controller(self.grid)
        controller.clickAt((1, 1))
        controller.writeTopText("A new hope")

        self.assertEqual("A new hope", controller.getCurrentCellContent())
Example #6
0
 def start_new_game(self):
     """
     Method to reset the GUI and start a new GUI
     """
     self.mode = Modes.MODE_PLAY
     self.mode_text.set("PLAY")
     self.next_move.set("Press <c> to cancel")
     if self.label_grid_mat:
         del self.label_grid_mat
     self.label_grid_mat = list()
     self.mode_label.configure(bg="blue")
     grid = Grid(self.nb_rows)
     self.game = Game(grid, init_grid_with_two_tiles=True)
     self.grid = grid
     self.score_text.set("Score: 0")
     self.turn_text.set("Round 0")
     self.display_grid()
     self.window.mainloop()
Example #7
0
 def replay_game(self):
     """
     Method to visualize a 2048 game from log file
     """
     self.mode = Modes.MODE_REPLAY
     self.mode_text.set("REPLAY")
     self.mode_label.configure(bg="red")
     filepath = filedialog.askopenfilename(initialdir=".", title="Select file",
                                           filetypes=(("2048 replay files", "*.log"), ("all files", "*.*")))
     if filepath != '':
         self.game = Game.load_game(filepath)
         t_str_state = self.game.history.grid_history[0]
         try:
             self.grid.grid = Grid.from_string(t_str_state, self.nb_rows, self.nb_columns)
             self.update_grid()
         except ValueError:
             print("Incorrect matrix dimensions!")
     else:
         self.start_new_game()
Example #8
0
    def load_game(log_file_path, display_grid=True):
        """
        Static method to load a 2048 game log to visualize it through the GUI

        @param log_file_path: the path of the log to load
        @type log_file_path: str
        @param display_grid: whether or not to print the initial state of the 2048 game
        @type display_grid: bool

        @return: a Game object that contains all the game history (tile positions, directions and score)
        @rtype: Game
        """
        with open(log_file_path, 'r') as f:
            nb_rows_columns = int(f.readline().strip().split(' ')[0])
            grid = Grid(nb_rows_columns)
            game = Game(grid,
                        init_grid_with_two_tiles=False,
                        display_grid=display_grid)
            line = f.readline()
            while line:
                l_split = line.strip().split(' ')
                if len(l_split) > 3:
                    game.history.score_history.append(int(l_split[1]))
                    game.history.grid_history.append(' '.join(l_split[2:-2]))
                    if l_split[-2] != "WIN" and l_split[-2] != "LOOSE":
                        game.history.direction_state_history.append(
                            Constants.Directions(l_split[-2]))
                    else:
                        game.history.direction_state_history.append(
                            Constants.States(l_split[-2]))
                    m = re.search(
                        r"\[([-0-9]+)\]",
                        l_split[-1])  # Regex to extract index from brackets
                    game.history.direction_index_history.append(int(
                        m.group(1)))
                line = f.readline()
        return game
class GameController:

    def __init__(self):
        self.grid = Grid(10, 20)
        self.game_display_mode = pygame.display.set_mode((380, 443))
        self.game_display = GameDisplay(self.game_display_mode, (0, 0, 0))
        self.grid_display = GridDisplay(self.game_display_mode, self.grid)
        self.pygame_display = PygameDisplay()
        self.colour = (5, 205, 25)
        self.velocity_time = 0.4

    def start(self):
        self.grid.addObserver(self.game_display)
        self.grid.addObserver(self.grid_display)
        self.grid.addObserver(self.pygame_display)
        self.pygame_display.start()
        self.grid.set_falling_piece(Piece([(5, 1), (5, 2), (6, 1), (6, 2)], self.colour))

    def iterate(self):
        if self.grid.current_piece.block_list:
            self.grid.gravity()
        else:
            self.grid.set_falling_piece(Piece([(5, 1), (5, 2), (6, 1), (6, 2)], self.colour))

    def sleep(self):
        time.sleep(float(self.velocity_time))

    def event_handling_process(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_LEFT:
                    self.grid.move_to_left()
                elif event.key == K_RIGHT:
                    self.grid.move_to_right()
                elif event.key == K_DOWN:
                    self.velocity_time = 0.1
            if event.type == KEYUP:
                if event.key == K_DOWN:
                    self.velocity_time = 0.4
 def setUp(self):
     self.grid = Grid()
     self.grid.writeCell("cell content", (0, 0))
     self.grid.writeCell("one on one", (1, 1))
Example #11
0
	def test_read_empty_cell_should_return_empty_string(self):
		grid = Grid()
		self.assertEqual("",grid.readCell((0,0)))
Example #12
0
	def test_writing_a_cell_should_not_modify_others(self):
		grid = Grid()	

		grid.writeCell("hello",(0,0))	
		self.assertEqual("hello",grid.readCell((0,0)))

		grid.writeCell("good bye",(0,0))
		self.assertEqual("good bye",grid.readCell((0,0)))
		
		grid.writeCell("In a new cell",(0,1))
		self.assertEqual("good bye",grid.readCell((0,0)))
		self.assertEqual("In a new cell",grid.readCell((0,1)))
Example #13
0
def main():
    grid = Grid(10, 10, 10)
    run(grid)
Example #14
0
 def setUp(cls):
     cls.grid = Grid(10, 20)
     cls.DEFAULT_COLOR = (0, 0, 0)
Example #15
0
	def setUp(self):
		self.grid = Grid()
		self.grid.writeCell("cell content",(0,0))	
		self.grid.writeCell("one on one",(1,1))