def fight(ann, best, dump=False): board = game.getEmptyBoard() current = 'O' action = random.randint(0, game.BOARD_SIZE * game.BOARD_SIZE - 1) board, won = game.move(board, action, current) if dump: print(game.render(board)) current = 'O' if current == 'X' else 'X' while True: entry = state_lists_to_batch([board], current) probs = best(entry)[0] if current == 'O' else ann(entry)[0] while True: action = np.argmax(probs) if action not in game.possible_moves(board): probs[action] = -np.inf else: break board, won = game.move(board, action, current) if dump: print(game.render(board)) if len(game.possible_moves(board)) == 0: return None if won: break current = 'O' if current == 'X' else 'X' return best if current == 'O' else ann
def user_play(game): key = KEY_RIGHT # init key prevKey = key while True: key_arr = read_stdin() if len(key_arr) == 0: key = prevKey elif len(key_arr) == 3: if key_arr[2] == 'A': key = KEY_UP if key_arr[2] == 'B': key = KEY_DOWN if key_arr[2] == 'C': key = KEY_RIGHT if key_arr[2] == 'D': key = KEY_LEFT prevKey = key game.move_snake(key) game.update() game.render() print "render_dxy_state" print "----------------" game.render_dxy_state() print "----------------" if game.done: break time.sleep(0.25)
def main(): while True: game.handle_inputs() game.update() game.render()
def displayInventory(self): li = self.niceInv() choice = reqs.selectionScreen(li, 'Inventory:', ORANGE, '[Enter] to select | [R] to dump | [Q] to exit', ORANGE, True) if choice[0] != None and choice[1] != None: if self.inv[choice[0]].type == 'food': self.eatObj(self.inv[choice[0]]) elif self.inv[choice[0]].type == 'weapon' and self.mode == 0: self.weaponChoice = choice[0] #self.atkObj(self.inv[choice[0]]) game.render()
def displayInventory(self): li = self.niceInv() choice = reqs.selectionScreen( li, 'Inventory:', ORANGE, '[Enter] to select | [R] to dump | [Q] to exit', ORANGE, True) if choice[0] != None and choice[1] != None: if self.inv[choice[0]].type == 'food': self.eatObj(self.inv[choice[0]]) elif self.inv[choice[0]].type == 'weapon' and self.mode == 0: self.weaponChoice = choice[0] #self.atkObj(self.inv[choice[0]]) game.render()
model.add(Activation('relu')) model.add(Dense(256)) model.add(Activation('relu')) model.add(Dense(size)) # model.add(Activation('linear')) # print(model.summary()) # Finally, we configure and compile our agent. You can use every # built-in Keras optimizer and even the metrics! # model.compile(SGD(lr=1e-3), metrics=['mae']) model.compile(optimizer='adam', loss='mae', metrics=['accuracy']) model.fit(x_train, y_train, epochs=100, batch_size=32, validation_data=(x_val, y_val)) for i in range(10): print("Before:") game.render(x_val[i][:-1].reshape(shape)) print("After:") game.render(y_val[i].reshape(shape)) print("Prediction:") game.render(np.round( model.predict(x_val[i].reshape(1, 17))).reshape(shape)) # Okay, now it's time to learn something! We visualize the training # here for show, but this slows down training quite a lot. You can # always safely abort the training prematurely using Ctrl + C. # model.fit(env, nb_steps=50000, verbose=2) # test: # dqn.test(env, nb_episodes=5, visualize=True)
def render(self, mode='human', close=False): # Render the environment to the screen game.render(self.arr) raw_input("Enter to continue.") os.system('clear')
playerOne.load("./save/cfOne2000.h5") playerTwo.load("./save/cfTwo2000.h5") done = 0 batch_size = 42 for e in range(EPISODES): cf.reset() state = cf.board state = np.reshape(state, [1, state_size]) time = 0 # time is used just to count frames as a measurement of how long the ai lasted while True: sleep(5) time += 1 actionOne = playerOne.act(state) moveOne = cf.dropTile(actionOne, 1) cf.render() print("/////////////////") currentBoard = np.reshape(cf.board, [1, state_size]) actionTwo = playerTwo.act(currentBoard) moveTwo = cf.dropTile(actionTwo, -1) cf.render() print("/////////////////") nextStateOne = cf.board backupBoard = cf.board currentBoard = np.reshape(cf.board, [1, state_size]) cf.dropTile(playerOne.act(currentBoard), 1) nextStateTwo = cf.board cf.board = backupBoard rewardOne = time rewardTwo = time
stats = stats.Stats() score_sum = 0.0 time_sum = 0.0 score_cnt = 0.0 steps_wo_r = 0 quality_max = 0.0 for e in range(EPISODES): game.reset() state = game.get_state() for t in range(MAX_STEPS): action = agent.act(state) key = action2key[game.key][action] if int(e / 100) * 100 == e: game.render() print "key:", key2str[key], " action:", action2str[ action], " time:", t quality = score_sum / (score_cnt + 1) msg_str = "episode: {}/{}, epsilon: {:.2}, q: {:0.2f}, mem: {}, mem_done: {}, time: {}"\ .format(e, EPISODES, agent.epsilon, quality, len(agent.memory), len(agent.memory_done), time_sum/100.0) print msg_str # print "----------------" # game.render_dxy_state() # print "----------------" time.sleep(0.05) next_state, reward = game.step(key) #if reward == 0: # steps_wo_r += 1 #else:
delta_time = 0 clock = pygame.time.Clock() t = pygame.Surface((width,height)) t.set_alpha(180) t.fill((0,0,0)) image = pygame.image.load("img/miljo.png") image = pygame.transform.scale(image,(width, height)) while(1): delta_time = float(clock.tick(400)) for event in pygame.event.get(): if(event.type == pygame.QUIT): sys.exit() game.input(delta_time) game.update(delta_time) screen.blit(image,(0,0,width,height)) game.render(screen) screen.blit(t, (0,0)) pygame.display.flip()
assert_equal(len(map.keys()), 26) assert_equal(isinstance(map, dict), True) assert_equal(len(map['Path A'].keys()), 4) assert_equal('about' in map['Path A'], True) assert_equal('stuff' in map['Path A'], True) assert_equal('enemy' in map['Path A'], True) assert_equal('neighbors' in map['Path A'], True) assert_equal(isinstance(map['Path A'], dict), True) assert_equal(isinstance(map['Path A']['about'], str), True) assert_equal(isinstance(map['Path A']['stuff'], list), True) assert_equal(isinstance(map['Path A']['enemy'], bool), True) assert_equal(isinstance(map['Path A']['neighbors'], list), True) #render(x) test_world = create_world() assert_equal(render(test_world), '\nThere is a fork in the road\nTo the right is the path,\nto the left are the woods,\nand next to you is a path to a broken down house.\nYour health is 5/5\n********************************************************************************************************************\n\n') assert_equal(render(test_world), render_location(test_world) + render_player(test_world)) #render_location(x) test_world = create_world() location = test_world['player']['location'] assert_equal(render_location(test_world), test_world['map'][location]['about']) #render_enemy(x) test_world = create_world() test_world['player']['location'] = 'Bear' assert_equal(render_enemy(test_world), bear(test_world)) test_world['player']['location'] = 'Tunnel' assert_equal(render_enemy(test_world), tunnel(test_world)) test_world['player']['location'] = 'Path E' assert_equal(render_enemy(test_world), path_e(test_world))
pygame.display.set_icon(screen_icon) clock = pygame.time.Clock() player1 = User(PieceColor.WHITE) player2 = SmartBot(PieceColor.BLACK) game = game.Game([player1, player2], BOX_WIDTH) while True: click = None for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: row = math.floor(event.pos[1] / BOX_WIDTH) column = math.floor(event.pos[0] / BOX_WIDTH) click = board.get_box(row, column) text_click = text_select.get_text_select() if text_click: click = text_click text_select.set_text_select(None) game.handle_turn(game.pieces, click) game.render(display_surface, BOX_WIDTH, colors.BLACK, colors.WHITE, font) pygame.display.update() clock.tick(FPS)