class SessionTetris(Session): def __init__(self): self.game = Tetris() self.last_damage = 0 def clear_callback(payload): self.last_damage = payload[0] self.game.on('clear', clear_callback) def act(self, a): action = game.controller.keys[a] for key in self.game.controller.keys: if key in autorepeat_keys: key_pressed = key in self.game.controller.pressed_keys and \ self.game.controller.pressed_keys[key][0] == True if key != action and key_pressed: self.game.controller.keyup(key) elif key == action and not key_pressed: self.game.controller.keydown(key) else: if key == action: self.game.controller.keydown(key) self.game.controller.keyup(key) def get_state(self): playfield = self.game.playfield_dropping playfield = list( [[0 if playfield[y][x] is not None else 1 for x in range(10)] for y in range(20)]) holdnext = self.game.holding_piece + self.game.drop.next_n_piece(5) holdnext = list([piece.rotation_shape for piece in holdnext]) return playfield, holdnext def get_reward(self): return self.last_damage / 12 def update(self): self.game.update() return self.game.finished
def start_game(is_opponent=False): pygame.init() game = Tetris() game.start_game() if is_opponent: opponent = Tetris(name='Opponent') game.connect_opponent(opponent) opponent.start_game() opponent.connect_opponent(game) screen = display.set_mode((1280, 720), pg_locals.DOUBLEBUF) vis = Visualizer(game, screen) display.set_caption('NenwTris') clock = time.Clock() key_mapping = { pg_locals.K_LEFT: Controller.key_left, pg_locals.K_RIGHT: Controller.key_right, pg_locals.K_x: Controller.key_spin_cw, pg_locals.K_z: Controller.key_spin_ccw, pg_locals.K_c: Controller.key_hold, pg_locals.K_DOWN: Controller.key_softdrop, pg_locals.K_SPACE: Controller.key_harddrop } game_delay = 0 opponent_delay = 0 events = [] def handle_event(ev): if ev.type == pg_locals.QUIT: pygame.quit() sys.exit() elif ev.type == pg_locals.KEYDOWN: if ev.key in key_mapping: if not game_paused: game.controller.keydown(key_mapping[ev.key]) else: events.append(ev) elif ev.type == pg_locals.KEYUP: if ev.key in key_mapping: if not game_paused: game.controller.keyup(key_mapping[ev.key]) else: events.append(ev) while True: game_paused = game_delay > 0 for ev in event.get(): handle_event(ev) for i in range(len(events)): handle_event(events.pop(0)) if game_delay <= 0: game.update() else: game_delay -= 1 if is_opponent: if opponent_delay <= 0: opponent.update() else: opponent_delay -= 1 game_delay_delta, opponent_delay_delta = vis.update() opponent_delay += opponent_delay_delta else: game_delay_delta, = vis.update() game_delay += game_delay_delta clock.tick(60)