def run_game(current_pressed): dt_sum = 0 dt_count = 0 lastTime = time.time() game = Game(window) game.update(0) game.draw() if current_pressed[K_w]: game.ship.acc[1] += 1000 if current_pressed[K_a]: game.ship.acc[0] -= 1000 if current_pressed[K_s]: game.ship.acc[1] -= 1000 if current_pressed[K_d]: game.ship.acc[0] += 1000 if current_pressed[K_SPACE]: game.ship.shooting = True pygame.display.update() while True: currentTime = time.time() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if event.key == K_w: game.ship.acc[1] += 1000 elif event.key == K_a: game.ship.acc[0] -= 1000 elif event.key == K_s: game.ship.acc[1] -= 1000 elif event.key == K_d: game.ship.acc[0] += 1000 elif event.key == K_SPACE: game.ship.wants_to_shoot = True elif event.type == KEYUP: if event.key == K_w: game.ship.acc[1] -= 1000 elif event.key == K_a: game.ship.acc[0] += 1000 elif event.key == K_s: game.ship.acc[1] += 1000 elif event.key == K_d: game.ship.acc[0] -= 1000 elif event.key == K_SPACE: game.ship.stop_shooting() dt = currentTime - lastTime if PRINT_TIME: dt_sum += dt dt_count += 1 print(dt_sum / dt_count) game.update(dt) game.draw() pygame.display.update() lastTime = currentTime if game.finished: break end_screen(game.score)
def __init__(self, **kwargs): super().__init__(**kwargs) self._game = Game() self._current_speed_is_slow = True self._update_background_size() self._game.level_changed += self._update_background_size self._running = False self._game_timer_event = Clock.schedule_interval( lambda dt: self._make_iteration(dt), 1.0 / self._game.iters_per_second)
def set_up_game(self): """Set up the necessary modules board, squares and players""" GameView.setting_up_game() board = self.set_up_board() players = self.set_up_players(board) self.game = Game(board, players) GameView.done_setting_up_game(self.game)
def load(filename): with open(folder + str(filename), "rb") as file: participants = pickle.load(file) endNameIndex = str.index(filename, filetype) name = filename[:endNameIndex] return Game(name, participants)
def train_from_directory(self, directory, learning_rate, max_epochs): """ Train a neural network based on a set of game logs located in a single directory @param directory: the path to the directory containing the 2048 log files @type directory: str @param learning_rate: The learning rate (between 0 and 1) @type learning_rate: float @param max_epochs: The maximum number of epochs (cycles) @type max_epochs: int """ all_x = None all_y = None for filename in os.listdir(directory): if filename.endswith(".log"): print("OK - File parsed: {}".format( os.path.join(directory, filename))) game = Game.load_game(os.path.join(directory, filename), display_grid=False) x, y = self.parse_inputs_outputs_for_neural_net(game) if all_x is None: all_x = x all_y = y else: all_x = np.concatenate((all_x, x)) all_y = np.concatenate((all_y, y)) else: print("NOK - File not parsed: {}".format( os.path.join(directory, filename))) self.train(all_x, all_y, learning_rate, max_epochs)
def read_game(self): if not self.read_boolean(): return None byte_array = self.read_bytes(565) game = struct.unpack( RemoteProcessClient.BYTE_ORDER_FORMAT_STRING + "qi2db9i19di4d7i4d7i2d3i2di4d7i4d6i4d2i2di", byte_array) return Game(game[0], game[1], game[2], game[3], game[4] != 0, game[5], game[6], game[7], game[8], game[9], game[10], game[11], game[12], game[13], game[14], game[15], game[16], game[17], game[18], game[19], game[20], game[21], game[22], game[23], game[24], game[25], game[26], game[27], game[28], game[29], game[30], game[31], game[32], game[33], game[34], game[35], game[36], game[37], game[38], game[39], game[40], game[41], game[42], game[43], game[44], game[45], game[46], game[47], game[48], game[49], game[50], game[51], game[52], game[53], game[54], game[55], game[56], game[57], game[58], game[59], game[60], game[61], game[62], game[63], game[64], game[65], game[66], game[67], game[68], game[69], game[70], game[71], game[72], game[73], game[74], game[75], game[76], game[77], game[78], game[79], game[80], game[81], game[82], game[83], game[84], game[85], game[86], game[87], game[88], game[89], game[90], game[91], game[92], game[93])
def read_game(self): if not self.read_boolean(): return None return Game(self.read_long(), self.read_int(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_double(), self.read_double(), self.read_double(), self.read_int(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_int(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_double(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_int(), self.read_double(), self.read_double())
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()
def main(): evManager = EventManager() keybd = KeyboardController(evManager) spinner = CPUSpinnerController(evManager) pygameView = PygameView(evManager) game = Game(evManager) spinner.Run()
def init(window): window.bkgd(curses.color_pair(2)) window.clear() window.box() window.keypad(False) window.addstr(0, 2, "NEW GAME") curses.echo() window.addstr(1, 4, "Enter the name of the game: ") gameName = '' while len(gameName) == 0: gameName = window.getstr(1, 32) if len(gameName) == 0: window.addstr(1, 60, "The game name cannot be empty") else: window.addstr(1, 60, " ") participantsCount = 0 participants = [] while participantsCount < 2: window.addstr(2, 4, "Enter the number of participants: ") participantsCount = int(window.getstr(2, 38)) if participantsCount < 2: window.addstr(2, 60, "More then 1 participant needed") else: window.addstr(2, 60, " ") i = 0 while i < participantsCount: window.addstr(i + 3, 4, "Enter the name of participant " + str(i + 1) + ": ") participantName = window.getstr(i + 3, 38) if len(participantName) == 0: window.addstr(i + 3, 60, "The name cannot be empty") else: window.addstr(i + 3, 60, " ") participants.append(Person(participantName)) i += 1 game = Game(str(gameName, "utf-8"), participants) curses.noecho() return game
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()
def test_wawes(self): Orc._velocity = 1 path = [Vector(1, 0), Vector(2, 0)] towers = [Vector(0, 0)] waves = [WavePart([Orc] * 2, Vector(0, 0), path)] level = Level(100, towers, WavesManager(waves, preparation_duration=0, unit_interval=2), '') game = Game(levels=iter((level,))) game.current_level.tick() orcs = self._find(Orc) self.assertEqual(1, len(orcs)) game.current_level.tick() orcs = self._find(Orc) self.assertEqual(1, len(orcs)) game.current_level.tick() orcs = self._find(Orc) self.assertEqual(1, len(orcs))
def test_build_tower(self): game = Game() game.current_level._gold = 100 Mage.cost = 60 loc = game.current_level.towers_locations[0] loc2 = game.current_level.towers_locations[1] game.try_build_tower(Mage, loc) tows = self._find(Mage) self.assertEqual(1, len(tows)) self.assertListEqual(loc, tows[0].location) self.assertEqual(40, game.current_level.gold) game.try_build_tower(Mage, loc2) tows = self._find(Mage) self.assertEqual(1, len(tows))
def read_game(self): if not self.read_boolean(): return None game = RemoteProcessClient.GAME_STRUCT.unpack(self.read_bytes(565)) return Game(game[0], game[1], game[2], game[3], game[4] != 0, game[5], game[6], game[7], game[8], game[9], game[10], game[11], game[12], game[13], game[14], game[15], game[16], game[17], game[18], game[19], game[20], game[21], game[22], game[23], game[24], game[25], game[26], game[27], game[28], game[29], game[30], game[31], game[32], game[33], game[34], game[35], game[36], game[37], game[38], game[39], game[40], game[41], game[42], game[43], game[44], game[45], game[46], game[47], game[48], game[49], game[50], game[51], game[52], game[53], game[54], game[55], game[56], game[57], game[58], game[59], game[60], game[61], game[62], game[63], game[64], game[65], game[66], game[67], game[68], game[69], game[70], game[71], game[72], game[73], game[74], game[75], game[76], game[77], game[78], game[79], game[80], game[81], game[82], game[83], game[84], game[85], game[86], game[87], game[88], game[89], game[90], game[91], game[92], game[93])
class GameView(Widget): gold = StringProperty('Gold:\n') hp = StringProperty('Hp:\n') start_stop_icon = StringProperty() change_speed_icon = StringProperty('res/x1_speed.png') wave = StringProperty('Wave:\n') def __init__(self, **kwargs): super().__init__(**kwargs) self._game = Game() self._current_speed_is_slow = True self._update_background_size() self._game.level_changed += self._update_background_size self._running = False self._game_timer_event = Clock.schedule_interval( lambda dt: self._make_iteration(dt), 1.0 / self._game.iters_per_second) def change_running(self): if self._running: self.stop_game() else: self.start_game() @property def running(self): return self._running def change_speed(self): if self._current_speed_is_slow: self.change_speed_icon = 'res/x2_speed.png' self._game.iters_per_second += 30 else: self.change_speed_icon = 'res/x1_speed.png' self._game.iters_per_second -= 30 self._game_timer_event.timeout = 1 / self._game.iters_per_second self._current_speed_is_slow = not self._current_speed_is_slow def start_game(self): self._running = True self.start_stop_icon = 'res/stop_game.png' def stop_game(self): self._running = False self.start_stop_icon = 'res/play_game.png' @property def game(self): return self._game def _make_iteration(self, dt): if self._running: self._game.make_game_iteration() self.update(dt) def _update_background_size(self): background = Image(self._game.current_level.map_path) Window.size = (background.width, background.height) @staticmethod def _set_color(r, g, b): Color(r / 255, g / 255, b / 255) @staticmethod def _set_hp_bar_color(hp_percent): if hp_percent > 0.5: GameView._set_color(101, 230, 66) elif hp_percent > 0.25: GameView._set_color(244, 229, 66) else: GameView._set_color(219, 40, 24) def update(self, dt): self.gold = f'Gold: {self._game.current_level.gold}\n' self.hp = f'Hp: {self._game.current_level.hp}\n' self.wave = f'Wave: {self.game.current_level.current_wave}\n' with self.canvas: self.canvas.clear() Rectangle(pos=(0, 0), size=Window.size, source=self._game.current_level.map_path) for obj in sorted(GameObject.objects, key=lambda o: -o.location.y): pos = obj.location img = Image(obj.sprite_path) offset = Vector(obj.direction * -img.width / 2, -img.height / 2) offset += obj.graphics_offset size = (obj.direction * img.width, img.height) Rectangle(texture=img.texture, pos=pos + offset, size=size) if not obj.friendly: hp_percent = obj.hp / obj.max_hp offset_percent = (1 - hp_percent) / 2 hp_bar_size = (size[0] * hp_percent, 3) hp_bar_pos = pos + (size[0] * offset_percent, -5) self._set_hp_bar_color(hp_percent) Rectangle(pos=hp_bar_pos + offset, size=hp_bar_size) Color(1, 1, 1)
class Window: """ This class represents a tkinter-based 2048 Graphical User Interface (GUI) """ def __init__(self, nb_rows_columns, base_path): """ Init method to initialize a new Tk Window object (GUI) @param nb_rows_columns: the number of rows and columns @type nb_rows_columns: int @param base_path: the complete directory path where to write the log file @type base_path: str """ self.mode = Modes.MODE_PLAY self.game = None self.grid = None self.nb_rows = nb_rows_columns self.nb_columns = nb_rows_columns self.base_path = base_path self.label_grid_mat = None # General parameters for Tk window self.window = Tk() self.window.title("AI-based 2048") self.window.resizable(0, 0) self.window.configure(bg=tkc.colors['0'][0]) self.window.bind('<KeyRelease>', self.update) # Menu self.menu = Menu(self.window) menu_file = Menu(self.menu, tearoff=0) menu_file.add_command(label="New game", command=self.start_new_game) menu_file.add_command(label="Open game...", command=self.replay_game) self.menu.add_cascade(label="File", menu=menu_file) self.window.config(menu=self.menu) # Labels self.score_text = StringVar() self.score_label = Label(master=self.window, textvariable=self.score_text, font=tkc.text_font, bg=tkc.colors['0'][0]) self.score_label.grid(sticky="W", row=self.nb_rows, columnspan=self.nb_columns - 1) self.mode_text = StringVar() self.mode_label = Label(self.window, textvariable=self.mode_text, font=tkc.text_small_font, fg="white") self.mode_label.grid(row=self.nb_rows, column=self.nb_columns - 1, rowspan=2) self.turn_text = StringVar() self.turn_label = Label(self.window, textvariable=self.turn_text, font=tkc.text_font, bg=tkc.colors['0'][0]) self.turn_label.grid(sticky="W", row=self.nb_rows + 1, columnspan=self.nb_columns - 1) self.next_move = StringVar() self.next_move_label = Label(self.window, textvariable=self.next_move, font=tkc.text_small_font, bg=tkc.colors['0'][0]) self.next_move_label.grid(row=self.nb_rows + 2, columnspan=self.nb_columns) 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() 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() def display_grid(self): """ Method to display the 2048 grid with Tk """ for r in range(self.nb_rows): temp_row_list = list() for c in range(self.nb_columns): frame = Frame(self.window, width=100, height=100, borderwidth=0, bg=tkc.border_color, relief="solid") frame.pack_propagate(False) label = Label(frame, text="{}".format(self.grid.grid[r, c]), anchor="center", font=tkc.tile_font, bg=tkc.colors[str(self.grid.grid[r, c])][0], fg=tkc.colors[str(self.grid.grid[r, c])][1]) label.pack(fill="both", expand=True, padx=5, pady=5) frame.grid(row=r, column=c) temp_row_list.append(label) self.label_grid_mat.append(temp_row_list) def update_grid(self): """ Method to update a 2048 grid displayed """ for r in range(self.nb_rows): for c in range(self.nb_columns): self.label_grid_mat[r][c].configure(text="{}".format(self.grid.grid[r, c]), font=tkc.tile_font, bg=tkc.colors[str(self.grid.grid[r, c])][0], fg=tkc.colors[str(self.grid.grid[r, c])][1]) self.score_text.set("Score: " + str(self.game.current_score)) if self.mode == Modes.MODE_REPLAY: self.turn_text.set( "Round {} / {}".format(self.game.round_count, str(len(self.game.history.grid_history) - 1))) self.next_move.set("Next move: {}".format(self.game.history.direction_state_history[self.game.round_count])) else: self.turn_text.set("Round {}".format(self.game.round_count)) self.window.update_idletasks() 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()
def __init__(self, board_factory, board_controller): self.board_factory = board_factory self.board_controller = board_controller self.game = Game(None, None) self.number_players = -1
"type": 2 } ], "train": [ { "capacity": 15, "idx": 0, "line_idx": 1, "player_id": "dcdfdf83-cbcf-4cec-8ad8-c919c7f6781d", "position": 10, "product": 0, "speed": 0 } ] }''') world = World(posts=world_responce['post'], trains=world_responce['train']) game = Game(lines=game_responce['line'], points=game_responce['point']) def test_defult(): strategy = Strategy(start_data) next_move = strategy.move(world, game) print(next_move) test_move = Move(12, 1, 0) assert next_move.line_idx == test_move.line_idx assert next_move.speed == test_move.speed assert next_move.train_idx == test_move.train_idx
def main(): print("Teste de Primeiro Print") g = Game(["ABC", "Carro"], "Primeira Partida") print("Palavra 1: {}".format(g.palavras[0])) print("{}".format(g.partida)) return None
Scoree(idGift=s.idGift, idQuestion=s.idQuestion, idAnswer=s.idAnswer, value=s.point)) return resScore # CONFIG GAME count = 0 path = 'Start' # Questions questions = getQuestionsFromDB() # Get the 8 questions from DB gifts = getGiftsFromDB() # Get all gifts from DB game = Game(questions, gifts) # Create the game object game.initializeGiftsScore() # Set started values of DB ###### # ROUTE @app.route('/') @app.route('/home') def home(): game.refreshGame(getGiftsFromDB()) # Refresh Game any time to count = 0 return render_template('home.html', language='eng') @app.route('/contactUs/')
def __init__(self): self._game = Game() pass