def place_fruit(self, pos: Position = None): if pos is None: pos = Position.random(self.game_map.n, self.game_map.m) while pos in self.snake: pos = Position.random(self.game_map.n, self.game_map.m) self.game_map.set(pos, -1) return pos
def test_run_command_success(self): plateau = Plateau(5, 5) position = Position(1, 2) rover = Rover(plateau, position, 'N') rover.run_command('L') self.assertEqual(rover.position, Position(1, 2)) self.assertEqual(rover.heading, 'W')
def test_process(self): plateau = Plateau(5, 5) position = Position(1, 2) rover = Rover(plateau, position, 'N') rover.process('LMLMLMLMM') self.assertEqual(rover.position, Position(1, 3)) self.assertEqual(rover.heading, 'N')
def test_move_east(self): plateau = Plateau(5, 5) position = Position(1, 2) heading = 'E' rover = Rover(plateau, position, heading) self.assertEqual(rover.position, position) res = rover.move() self.assertEqual(res, True) self.assertEqual(rover.position, Position(2, 2))
def test_invalid_y(self): with self.assertRaises(ValueError) as e: x, y = 10, -1 position = Position(x, y) self.assertEqual(type(e.exception), ValueError) self.assertEqual(str(e.exception), "Invalid y: {}".format(y))
def test_invalid_x(self): with self.assertRaises(ValueError) as e: x, y = -1, 10 position = Position(x, y) self.assertEqual(type(e.exception), ValueError) self.assertEqual(str(e.exception), "Invalid x: {}".format(x))
def test_condition_one(self): test_grid = Grid(size=4) game = GameOfLife(grid=test_grid) for x in range(0, 4): [ test_grid.set_cell( Cell(live=Life(status=True), position_x=Position(x), position_y=Position(y))) for y in range(0, 4) ] self.assertEqual( False, game.apply_rule_one( Cell(live=Life(status=True), position_x=Position(2), position_y=Position(2))))
def test_snake_eating_itself(): map = GameMap(4,4) game = Game(map, [Position(x=1,y=2)],234) game.print() print(game.step(Direction.RIGHT)) game.print() print(game.step(Direction.RIGHT)) game.print() print(game.step(Direction.DOWN)) game.print() print(game.step(Direction.LEFT)) game.print() print(game.step(Direction.LEFT)) game.print() print(game.step(Direction.LEFT)) game.print() print(game.step(Direction.UP)) game.print() print(game.step(Direction.UP)) game.print() print(game.step(Direction.RIGHT)) game.print() print(game.step(Direction.RIGHT)) game.print() print(game.step(Direction.RIGHT)) game.print() print(game.step(Direction.DOWN)) game.print() print(game.step(Direction.LEFT)) game.print() # let snake eat itself print(game.step(Direction.UP)) game.print()
def test___str__(self): plateau = Plateau(5, 5) position = Position(1, 2) rover = Rover(plateau, position, 'N') self.assertEqual( str(rover), '{} {} {}'.format(rover.position.x, rover.position.y, rover.heading))
def test_spin_right(self): plateau = Plateau(5, 5) position = Position(1, 2) initial_heading = 'N' rover = Rover(plateau, position, initial_heading) self.assertEqual(rover.heading, initial_heading) rover.spin_right() self.assertEqual(rover.heading, rover.DIRECTIONS[initial_heading]['R'])
def test_current_position(self): plateau = Plateau(5, 5) position = Position(1, 2) rover = Rover(plateau, position, 'N') self.assertEqual( rover.current_position, '{} {} {}'.format(rover.position.x, rover.position.y, rover.heading))
def __init__(self): self.size = (settings.COLNO, settings.ROWNO) self.cells = [[Cell(Position(y, x)) for x in range(self.size[1])] \ for y in range(self.size[0])] self.next_state = [[0 for x in range(self.size[1])] \ for y in range(self.size[0])] for i in range(self.size[0]): for j in range(self.size[1]): self.cells[i][j] == Cell(Position(i, j)) self.rule_dict = RuleInitialiser("rules.txt").generate_dict() self.__init__loop() self.changed_cells = []
def move_not_available(self): plateau = Plateau(5, 5) position = Position(1, 8) initial_heading = 'N' rover = Rover(plateau, position, initial_heading) with self.assertRaises(Exception) as e: res = rover.move() self.assertEqual(type(e.exception), Exception) self.assertEqual(str(e.exception), "Move not available")
def test___str__(self): plateau = Plateau(5, 5) position = Position(1, 2) rover = Rover(plateau, position, 'N') self.assertEqual( str(rover.plateau), '0 0 0 0 0 0\n' '0 0 0 0 0 0\n' '0 0 0 0 0 0\n' '0 1 0 0 0 0\n' '0 0 0 0 0 0\n' '0 0 0 0 0 0\n')
def test_run_command_unrecognized_command(self): plateau = Plateau(5, 5) position = Position(1, 2) rover = Rover(plateau, position, 'N') command = 'A' with self.assertRaises(Exception) as e: rover.run_command(command) self.assertEqual(type(e.exception), Exception) self.assertEqual(str(e.exception), "Unrecognized command: {0}".format(command))
def main(): plateau = Plateau(5, 5) position = Position(1, 2) # Create rover instance rovers = Rovers(plateau, position, Rovers.directions.get('N')) instructions = input('Enter Instructions:') rovers.validate_instruction(instructions) print(rovers) rovers.set_position(3, 3, Rovers.directions.get('E')) instructions_new = input('Enter New Instructions:') rovers.validate_instruction(instructions_new) print(rovers)
def test_table(table: Table, n: int): map = GameMap(n, n) game = Game(map, [Position.random(n, n)]) # game = Game(map, [Position.random(n, n)]) while True: print('Current State') game.print() current_state = calculate_distances(game) best_action = take_action(current_state, table) print(f'Action: {best_action}') result = game.step(best_action) print(f'Result of move: {result}') if result < 0: print('Game over') return sleep(2)
def main(): n = 4 settings = QLearningSettings(learning_rate=0.8, discount_factor=0.5, episodes=1000, epsilon=0.0001, current_episode=0) map = GameMap(n, n) game = Game(map, [Position(0, 0)]) table = load_table() if table is None: table = Table(n) table = start_training(game, table, settings) # save_table(table) test_table(table, n)
def main(): input_plateau = input().split() plateau_x, plateau_y = int(input_plateau[0]), int(input_plateau[1]) plateau = Plateau(plateau_x, plateau_y) rovers = [] while True: input_rover = input().split() if not input_rover: break rover_x, rover_y, heading = int(input_rover[0]), int( input_rover[1]), input_rover[2] position = Position(rover_x, rover_y) rover = Rover(plateau, position, heading) commands = input() rover.process(commands) rovers.append(rover) for rover in rovers: print(rover)
def start_training(game: Game, table: Table, settings: QLearningSettings) -> Table: current_episode = 0 highest_score = -1 while current_episode < settings.episodes: current_state = calculate_distances(game) best_action = take_action(current_state, table) if random.random() < settings.epsilon: random_action = random.randint(0, 3) best_action = list(Direction)[random_action] success = update_state(best_action, table, settings, game) if not success: score = len(game.snake) print(f'Score: {score}') print(f'Epsiode: {current_episode + 1}') if highest_score < score: highest_score = score start = Position.random(game.game_map.n, game.game_map.n) game = Game(game.game_map, [start]) current_episode += 1 print(f'Highest Score: {highest_score}') return table
pygame.display.init() screen = pygame.display.set_mode((settings.SCREENWIDTH, settings.SCREENHEIGHT)) fps_clock = pygame.time.Clock() grid = Grid() #for i in range(Settings.COLLNO): # for j in range(Settings.ROWNO): ## grid.cells[i][j] = Cell(Position(i, j)) WHITE = (255, 255, 255) is_paused = True FPS = settings.FPS cell = Cell(Position(3, 3)) fpscount = 0 take_screenshot = False while True: mousePressed = False for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() elif event.key == pygame.K_p: is_paused = not is_paused
def __init__(self, fn, text): self.fn = fn self.text = text self.pos = Position(-1, 0, -1, fn, text) self.current_char = None self.advance()
class Lexer: def __init__(self, fn, text): self.fn = fn self.text = text self.pos = Position(-1, 0, -1, fn, text) self.current_char = None self.advance() def advance(self): self.pos.advance(self.current_char) self.current_char = self.text[self.pos.idx] if self.pos.idx < len( self.text) else None def make_tokens(self): tokens = [] while self.current_char is not None: if self.current_char in " \t": self.advance() elif self.current_char in ";\n": tokens.append(Token(TT_NEWLINE, pos_start=self.pos)) self.advance() elif self.current_char == '#': self.skip_comment() elif self.current_char in DIGITS: tokens.append(self.make_number()) elif self.current_char in LETTERS: tokens.append(self.make_identifier()) elif self.current_char == '"': tokens.append(self.make_string()) elif self.current_char == "+": tokens.append(Token(TT_PLUS, pos_start=self.pos)) self.advance() elif self.current_char == "-": tokens.append(self.make_minus_or_arrow()) elif self.current_char == "*": tokens.append(Token(TT_MUL, pos_start=self.pos)) self.advance() elif self.current_char == "/": tokens.append(Token(TT_DIV, pos_start=self.pos)) self.advance() elif self.current_char == "§": tokens.append(Token(TT_SAFEDIV, pos_start=self.pos)) self.advance() elif self.current_char == "(": tokens.append(Token(TT_LPAREN, pos_start=self.pos)) self.advance() elif self.current_char == ")": tokens.append(Token(TT_RPAREN, pos_start=self.pos)) self.advance() elif self.current_char == '[': tokens.append(Token(TT_LSQUARE, pos_start=self.pos)) self.advance() elif self.current_char == ']': tokens.append(Token(TT_RSQUARE, pos_start=self.pos)) self.advance() elif self.current_char == "^": tokens.append(Token(TT_POW, pos_start=self.pos)) self.advance() elif self.current_char == "!": tok, error = self.make_not_equals() if error: return [], error tokens.append(tok) elif self.current_char == "=": tokens.append(self.make_equals()) elif self.current_char == "<": tokens.append(self.make_less_than()) elif self.current_char == ">": tokens.append(self.make_greater_than()) elif self.current_char == ",": tokens.append(Token(TT_COMMA, pos_start=self.pos)) self.advance() else: pos_start = self.pos.copy() char = self.current_char self.advance() return [], IllegalCharError(pos_start, self.pos, "'" + char + "'") tokens.append(Token(TT_EOF, pos_start=self.pos)) return tokens, None def make_number(self): num_str = "" dot_count = 0 pos_start = self.pos.copy() while self.current_char != None and self.current_char in DIGITS + ".": if self.current_char == ".": if dot_count == 1: break dot_count += 1 num_str += "." else: num_str += self.current_char self.advance() if dot_count == 0: return Token(TT_INT, int(num_str), pos_start, self.pos) else: return Token(TT_FLOAT, float(num_str), pos_start, self.pos) def make_string(self): string = str() pos_start = self.pos.copy() escape_char = False self.advance() all_escape_chars = {"n": "\n", "t": "\t"} while self.current_char != None and (self.current_char != '"' or escape_char): if escape_char: string += all_escape_chars.get(self.current_char, self.current_char) else: if self.current_char == "\\": escape_char = True else: string += self.current_char self.advance() escape_char = False self.advance() return Token(TT_STRING, string, pos_start, self.pos) def make_identifier(self): id_str = "" pos_start = self.pos.copy() while self.current_char is not None and self.current_char in LETTERS_DIGITS + '_': id_str += self.current_char self.advance() tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER return Token(tok_type, id_str, pos_start, self.pos) def make_minus_or_arrow(self): tok_type = TT_MINUS pos_start = self.pos.copy() self.advance() # CATCH -> if self.current_char == ">": self.advance() tok_type = TT_ARROW return Token(tok_type, pos_start=pos_start, pos_end=self.pos) def make_not_equals(self): pos_start = self.pos.copy() self.advance() # CATCH != if self.current_char == "=": self.advance() return Token(TT_NE, pos_start=pos_start, pos_end=self.pos), None self.advance() return None, ExpectedCharError(pos_start, self.pos, "'=' after '!'") def make_equals(self): # IF SINGLE = tok_type = TT_EQ pos_start = self.pos.copy() self.advance() # CATCH == if self.current_char == "=": self.advance() tok_type = TT_EE return Token(tok_type, pos_start=pos_start, pos_end=self.pos) def make_less_than(self): # IF < tok_type = TT_LT pos_start = self.pos.copy() self.advance() # CATCH <= if self.current_char == "=": self.advance() tok_type = TT_LTE return Token(tok_type, pos_start=pos_start, pos_end=self.pos) def make_greater_than(self): # IF > tok_type = TT_GT pos_start = self.pos.copy() self.advance() # CATCH >= if self.current_char == "=": self.advance() tok_type = TT_GTE return Token(tok_type, pos_start=pos_start, pos_end=self.pos) def skip_comment(self): self.advance() while self.current_char != '\n': self.advance() self.advance()
def test_generate_live_cell(self): state = Life(True) posX = Position(0) posY = Position(0) cell = Cell(live=state,position_x= posX, position_y = posY) self.assertEqual(True, cell.live)
def test_position(self): position = Position(10, 20) self.assertEqual(position.x, 10) self.assertEqual(position.y, 20)
def test_eq(self): x, y = 10, 10 position = Position(x, y) position_other = Position(x, y) self.assertEqual(position, position_other)
def test_not_eq(self): x, y = 10, 10 position = Position(x, y) x_other, y_other = 5, 5 position_other = Position(x_other, y_other) self.assertNotEqual(position, position_other)
def test_empty_position(self): position = Position() self.assertEqual(position.x, 0) self.assertEqual(position.y, 0)
def test_move_available_east_inside(self): width, height = 10, 10 plateau = Plateau(width, height) position, heading = Position(5, 5), 'E' self.assertEqual(plateau.move_available(position, heading), True)
def test_move_not_available_east_boundary(self): width, height = 10, 10 plateau = Plateau(width, height) position, heading = Position(10, 5), 'E' self.assertEqual(plateau.move_available(position, heading), False)