class Game: def __init__(self): self.browser = Browser() self.app = QApplication(sys.argv) self.timer = QTimer() self.timer.timeout.connect(self.updateEvent) self.ai = AI() self.last_score = 1 def run(self, delay): self.timer.start(delay) self.browser.run() return self.app.exec_() def updateEvent(self): self.timer.stop() (score, board) = self.browser.extractData() if self.last_score > score: self.ai.restart_game() self.last_score = score self.browser.sendMove(self.ai.get_move(score, board)) self.timer.start() # restart the event loop
def test_opponent_next_move_is_winning(self): ai = AI(['x', ' ', 'o', ' ', ' ', ' ', ' ', ' ', 'x']) self.assertEqual(ai.opponent_winning(), 4) self.assertEqual(ai.play(4), Game.X_WINS)
def test_ai_winning(self): ai = AI(['o', ' ', 'x', ' ', ' ', ' ', ' ', ' ', 'o']) self.assertEqual(ai.winning(), 4) self.assertEqual(ai.play(1), Game.O_WINS)
def start_game(game_type): game = Game() ai = AI() while (game.game_finished is False): #clear board so output is not too messy os.system('cls' if os.name == "nt" else 'clear') #print the current board state for the players print_board_state(game.board) #if the game has an AI player get AI to move if it's their turn if (game_type == AI_PLAYS_BLUE or game_type == AI_PLAYS_RED): #if it's the AI's turn call the AI to make a move, else player is prompted for a move if (game.current_player_turn == RED_PLAYER and game_type == AI_PLAYS_RED): game.player_move(ai.get_move(game)) elif (game.current_player_turn == BLUE_PLAYER and game_type == AI_PLAYS_BLUE): game.player_move(ai.get_move(game)) else: game.player_move(get_user_column_input()) #get player move if no AI player or it's still player turn else: game.player_move(get_user_column_input()) #if the game is finished print the board state and let the player know who has won if (game.game_finished): os.system('cls' if os.name == "nt" else 'clear') print_board_state(game.board) print print str(game.winner) + " has won the game!"
def test_ai(): grid = Grid() grid.gprint() ct = CountTime() totalCT = 0 while grid.won==False: # input() print("*******************************************") ai = AI(grid) ct.start() d = ai.nextMove() ct.stop() moved = grid.move(d["move"]) if moved==True: grid.gprint() moveCount = d["moveCount"] cutoffs = d["cutoffs"] print("moveCount:%d\tcutoffs:%d"%(moveCount,cutoffs)) nct = ct.milliseconds() totalCT += nct print("time consume:%d "%(nct)) print("total time consume:%d "%(totalCT)) if grid.won==False: grid.computerMove() else: grid.gprint() else: print("You fail") return
class BrainConnection(): def __init__(self): self.ai = AI(realtimeMode=True) random.seed(self.ai.getRandomness()) self.lastValue = self.ai.getNeuralResult() self.directionValue = 50 #while True: # print self.getDirection() #we get a directional vector between 0 and 100 which is influenced by the #returned values from the brain interface def getDirection(self): currentValue = self.ai.getNeuralResult() if currentValue == self.lastValue: return self.directionValue if self.lastValue > currentValue: if self.directionValue != 100: self.directionValue += 10 else: if self.directionValue != 0: self.directionValue -= 10 self.lastValue = currentValue return self.directionValue #returns entropy data depending on the analogue converted data from the brain interface def getRandomness(self,randrange): return random.randrange(randrange)
def sp(choix_ai_adversaire, num_tirages_MC = 3, num_descentes_dans_arbre = 7, facteur_uct = 0.0): '''Une partie opposant un joueur humain à une intelligence artificielle''' grid = Grille() ai = AI('O') if choix_ai_adversaire == 2: ai = MC('O', num_tirages_MC) elif choix_ai_adversaire == 3: ai = UCT('O', num_tirages_MC, num_descentes_dans_arbre, facteur_uct) le_joueur1_gagne = False mes_coups_possibles = grid.lookForAllowedSteps() input = [] player = 'X' while(input != 'q' and grid.checkVictory() is False and len(mes_coups_possibles)>0): grid.showGrid() input = raw_input("Number 1 through 7 = drop disc, q = quit. \nYour move:") if (input in ['1','2','3','4','5','6','7']): MonCoup = int(input) if grid.drop(player, MonCoup): le_joueur1_gagne = True mes_coups_possibles = grid.lookForAllowedSteps() if(grid.checkVictory() is False and len(mes_coups_possibles)>0): VotreCoup = ai.ai(grid) grid.drop(ai.player, VotreCoup) le_joueur1_gagne = False mes_coups_possibles = grid.lookForAllowedSteps() il_y_a_un_vainqueur = grid.checkVictory() print "The game ended in the following state:" grid.showGrid() print("Y a-t-il un gagnant ?"), print(il_y_a_un_vainqueur) print("Si oui, est-ce le joueur n 1 (X) ?"), print(le_joueur1_gagne)
class Ship: def __init__(self, screen): self.hp = 100 self.ai = 1 self.ai_object = AI(screen, self) self.x = 0 self.y = 0 self.xvel = 0 self.yvel = 0 self.pic = 0 self.screen = screen self.fire_rate = 0 screen.add_ship(self) def set_pic(self, number): self.pic = number def set_player(self): self.ai = 0 def render(self): self.screen.fast_display(self.x, self.y, self.pic) def update(self): self.x += self.xvel self.y += self.yvel if self.ai >= 0: self.ai_object.move(self.ai) if self.y > self.screen.max_y: self.screen.explosion(self.x, self.y) def damage(self, value): self.hp -= value if self.hp < 0: self.screen.remove_ship(self) self.screen.explosion(self.x, self.y) def fire(self, rate, target=None): if self.fire_rate > 0: self.fire_rate -= 1 return self.fire_rate = rate shot = Shot(self.screen, self.x, self.y + 40, self, target) player = self.screen.player dx = player.x - self.x dy = player.y - self.y - 15 total = sqrt(dx ** 2 + dy ** 2) shot.xvel = dx / total * 15 shot.yvel = dy / total * 15 shot.range = 100
def update(self, **kwargs): """ (**kwargs) -> None Updates the aggressive AI. Remember, the ball_x, ball_y, ball_vx (x speed), ball_vy (y speed), paddle_x, and paddle_y, MUST be supplied on every game iteration. """ AI.update(self, **kwargs)
class TestAI(unittest.TestCase): def setUp(self): self.ai = AI(Board(), 0) def test_get_difficulty(self): self.assertEqual(self.ai.get_difficulty(), 0) def test_set_difficulty(self): self.assertEqual(self.ai.set_difficulty(1), True)
def process_text(self): bot = AI(self.msg) print self.msg result = bot.respond(self.msg.content) if options.debug: logging.info('bot response %s',result) if isinstance(result, list): return ObjectDict(msg_type=MSG_TYPE_NEWS,response=result) else: return ObjectDict(msg_type=MSG_TYPE_TEXT,response=sender.decode(result))
class CLI: def __init__(self): self._game = AI() def play(self): outcome = Game.IN_PROGRESS while outcome == Game.IN_PROGRESS: self._draw_board() move = None while move is None: move = self._get_move() outcome = self._game.play(move) self._clear() self._announce_outcome(outcome) def _announce_outcome(self, outcome): if outcome == Game.X_WINS: print('Congratulations! You won!') if outcome == Game.O_WINS: print('Sorry, you loose. Better luck next time') else: print('It\'a a tie') def _get_move(self): try: position = int(input('Enter your move>')) if self._game.valid_move(position): return position print("Wrong input!") except ValueError: print("Wrong input!") return None def _clear(self): os.system('clear') def _draw_board(self): state = self._game.current_state() symbols = {str(place): symbol for place, symbol in enumerate(state)} print(self._fill_board(symbols)) def _fill_board(self, symbols): new_board = [] for character in BOARD: if character in symbols and symbols[character] != Game.EMPTY: new_board.append(symbols[character]) else: new_board.append(character) return "".join(new_board)
class AITest(unittest.TestCase): def setUp(self): self.game = Game() self.AI = AI(self.game.UI.BOARD, self.game.winning_routes) def test_init(self): self.assertEqual(self.AI.BOARD, self.game.UI.BOARD) self.assertEqual(self.AI.winning_routes, self.game.winning_routes) def test_get_correct_position_when_two_places_marked_vertical(self): BOARD = [['X', ' ', ' '], ['X', ' ', ' '], [' ', ' ', ' ']] self.AI.BOARD = BOARD self.assertEqual((2, 0), self.AI.get_best_position()) def test_get_correct_position_when_two_places_marked_horizontal(self): BOARD = [[' ', ' ', ' '], ['X', ' ', 'X'], [' ', ' ', ' ']] self.AI.BOARD = BOARD self.assertEqual((1, 1), self.AI.get_best_position()) def test_get_correct_position_when_two_places_marked_diagonal(self): BOARD = [[' ', ' ', 'X'], [' ', 'X', ' '], [' ', ' ', ' ']] self.AI.BOARD = BOARD self.assertEqual((2, 0), self.AI.get_best_position()) def test_when_only_one_place_is_marked(self): BOARD = [[' ', 'X', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] self.AI.BOARD = BOARD self.AI.attack() for line in self.AI.BOARD: for place in line: if place == 'O': self.assertTrue(True) return self.assertFalse(True)
def simulerMonteCarlo(self, grille, symbole_dont_c_est_le_tour): '''Evaluer une grille par des simulations Monte-Carlo de la fin de la partie''' ai = AI(symbole_dont_c_est_le_tour) num_parties_avec_vainqueur = 0 num_victoires_du_joueur1 = 0 for i in range(self.num_tirages_MC): grille_simulee = Grille(grille) (il_y_a_un_vainqueur, le_joueur1_gagne) = ai.autoComplete(grille_simulee) num_parties_avec_vainqueur += int(il_y_a_un_vainqueur) num_victoires_du_joueur1 += int(le_joueur1_gagne) try: score = (2.0*num_victoires_du_joueur1 - num_parties_avec_vainqueur)/num_parties_avec_vainqueur except ZeroDivisionError: score = 0.5 return score
def __init__(self, unit_roster, xpos, ypos, name, number, dirr, faction, maps, **keywords): super().__init__(unit_roster, xpos, ypos, name, number, dirr, faction, maps, **keywords) self.anim_standing = LoadImages(dirr, ["stand.0.png","stand.1.png", "stand.2.png","stand.3.png","stand.4.png", "stand.5.png"]).sequence self.anim_walking = LoadImages(dirr, ["stand.0.png","stand.1.png", "stand.2.png","stand.3.png","stand.4.png", "stand.5.png"]).sequence self.anim_atk = LoadImages(dirr, ["stand.0.png","stand.1.png", "stand.2.png","stand.3.png","stand.4.png", "stand.5.png","stand.0.png","stand.1.png", "stand.2.png","stand.3.png","stand.4.png", "stand.5.png","stand.0.png","stand.1.png", "stand.2.png","stand.3.png","stand.4.png", "stand.5.png"]).sequence self.anim_warn1 = LoadImages(dirr, ["attack1.11.png","attack1.10.png", "attack1.9.png","attack1.8.png","attack1.7.png", "attack1.6.png","attack1.5.png","attack1.4.png", "attack1.3.png","attack1.2.png","attack1.1.png", "attack1.0.png"]).sequence self.anim_death = LoadImages(dirr, ["die1.0.png","die1.1.png","die1.2.png","die1.3.png","die1.4.png"]).sequence self.deathbeam_effect = LoadImages(dirr, ["Deathbeam.png","Deathbeam1.png","Deathbeam.png","Deathbeam1.png","Deathbeam.png","Deathbeam1.png","Deathbeam.png","Deathbeam1.png","Deathbeam.png","Deathbeam1.png","Deathbeam.png","Deathbeam1.png","Deathbeam.png","Deathbeam1.png","Deathbeam.png","Deathbeam1.png"]).sequence self.special_atk1 = LoadImages("images/teddyghost/", ["skill.12111006.ball.0.png","skill.12111006.ball.1.png", "skill.12111006.ball.2.png","skill.12111006.ball.3.png","skill.12111006.ball.4.png", "skill.12111006.ball.5.png","skill.12111006.ball.6.png", "skill.12111006.ball.7.png"]).sequence self.attacks_dict = {"one": {"energy": 10, "dmg": 5, "x_range": 1000, "y_range": 50}, "two": {"energy": 10, "dmg": 10, "x_range": 40, "y_range": 50}} self.width = 136 #self.anim_attack1ing[0].get_rect().size[0] self.height = 160 #self.anim_skill.12111006.balling[0].get_rect().size[1] self.health_max = 1000 self.health = self.health_max self.step_horz = 32 self.step_vert = 32 self.special_casting = 0 self.special_counter = pygame.time.get_ticks() - 20000 self.atk1_sound = "death_beam_sound" self.special_offset = 50 self.special_dmg = 2 self.AI = AI(self,[[self.Approach],[self.queue_special],[self.queue_warn1]]) self.wave_position = [300,375,450,525,600] self.temp_wave = [] #I HAVE NO IDEA WHY BUT THIS NUMBER MUST BE A MULTIPLE OF 3 FOR ANIMATION TO WORK PROPER for i in range(12): self.temp_wave.append(random.sample(self.wave_position, len(self.wave_position)-1))
def __init__(self, controller, settings): super(Game, self).__init__() # check to make sure that the controller # can handle all of the registered spells # so it does not pop randomly in the middle # of game ;) for spell in AttrReader.items_from_klass(Spell): controller.get_spell_handler(spell) controller.set_game(self) self.controller = controller self.settings = settings self.ai = AI(self.controller._send_msg) self.levels = None self.player = None for event in self.controller.events.values(): self.events[event.name] = event self._turn_num = None self._level_count = None self._current_level = None self._level_generator = LevelGenerator() self._object_generator = ObjectGenerator() self._species_generator = SpeciesGenerator()
def __init__(self, conn, addr, port, name): self.serv_conn = conn self.serv_addr = addr self.serv_port = port self.game_name = name self.ai = AI() self.ai.connection = self.serv_conn
def __init__(self, filename, position, default_velocity = [145.0, 0.0], velocity = [0.0, 0.0], acceleration = [0.0, GRAVITY], jump_amount = JUMP_AMOUNT, health = 1, max_y = None): # self.rect is the creature's RELATIVE position # self.position is the ABSOLUTE position Thing.__init__(self, filename) self.velocity = Vector(velocity[0], velocity[1], y_max = max_y) self.acceleration = Vector(acceleration[0], acceleration[1]) self.default_velocity = Vector(default_velocity[0], default_velocity[1]) self.position = pygame.rect.Rect(self.rect) self.position.topleft = position self.rect.topleft = position self.desired_position = pygame.rect.Rect(self.position) self.jumping = False self.jump_amount = jump_amount self.landed = True self.motion = "right" if self.velocity.x >= 0 else "left" self.health = health self.dead = False self.reload_time = time() - 10 self.reload_wait = .75 #This gets tampered with elsewhere self.AI = AI()
def test_ai_play_a_game(self): ai = AI() self.assertEqual(ai.play(1), Game.IN_PROGRESS) self.assertEqual(ai.at(4), Game.O) self.assertEqual(ai.play(8), Game.IN_PROGRESS) self.assertEqual(ai.at(0), Game.O) self.assertEqual(ai.play(2), Game.IN_PROGRESS) self.assertEqual(ai.at(5), Game.O) self.assertEqual(ai.play(6), Game.O_WINS)
def NextChoice(battle, choices=None): choices = choices or [] if len(choices) < battle.num_pcs: return ChooseMove(battle, choices) # Let the AI make choices, then reformat the choices and pass to executor. choices.extend(AI.make_random_choices(battle)) choices = {choice.pop('user_id'): choice for choice in choices} return ExecuteTurn(battle, choices)
class Client(object): def __init__(self): self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(self, host, port): self.conn.connect((host, port)) info = self.conn.recv(1024) row, col, player = info.split(" ") print "-------------Status------------" print "WORLD_ROWS : %s" %(row) print "WORLD_COLS : %s" %(col) print "PLAYER : %s" %(player) print "-------------------------------\n\n" print "Connected. Waiting..." if int(player) == 1: print "You are RED." else: print "You are BLUE." self.ai = AI(int(row), int(col), int(player)) self.conn.send(self.ai.name+"\n") data = self.conn.recv(1024) print "Teamname:", self.ai.name print "Opponent:", data.strip() def play(self, viewflag=False) : if viewflag == True: gamescene = Gamescene(self.ai) while True: recvdata = self.conn.recv(4096) if recvdata in ["WIN\n", "DRAW\n", "LOSE\n"]: print "Result:", recvdata break recvdata = recvdata.strip().split(" ") self.ai.update(recvdata[1]) print "*" * 20 print "ai.map update : " print self.ai.map print "*" * 20 response = self.ai.think() self.conn.send(response) if viewflag: gamescene.update() gc.collect() def close(self): self.conn.close()
def __init__(self, game, breed): self.game = game self.breed = breed self.health = breed.max_health self.fov = FOV(self.game,self) self.ai = AI(self.game,self) self.status_effects = [] self.energy = 0
def __init__(self): self.browser = Browser() self.app = QApplication(sys.argv) self.timer = QTimer() self.timer.timeout.connect(self.updateEvent) self.ai = AI() self.last_score = 1
def __init__(self, game_name, cursor_lib): self.game_name = game_name self.ai = AI() self.turn_counter = 0 self.time = 0 self.world = get_world() self.io, self.user_controller = self.init_nonserializable_objects(cursor_lib)
def run_game(): """ runs the game :D """ game_board = Board() player1 = Human("1") player2 = AI("2") print(player1, "vs", player2) # players_turn = 1 while not game_board.has_winner: col = player1.get_move(game_board) game_board.add_piece(col, player1.piece) col = player2.get_move(game_board) game_board.add_piece(col, player2.piece) game_board.print_board()
class Game(): def __init__(self, game_size=4): self.game_progress = 0 self.game_steps = list() self.game_size = game_size self.player = Player(game_size) self.ai = AI(game_size) def play(self): while True: self.game_progress += 1 print print "Step %d" % self.game_progress print answer = self.player.play() if answer['bulls'] == self.game_size: print("Congratz! You won!") exit() else: print("%db %dc" % (answer['bulls'], answer['cows'])) repeat_question = None while self.game_progress > len(self.game_steps): asked_number, answer = self.ai.play(repeat_question) self.game_steps.append((asked_number, answer)) if answer['bulls'] == self.game_size: print("Hehe, I won!") exit() if len(self.ai.possible_numbers) == 0: print("You, liar!") step = raw_input("On which step did you lie: ") while not re.match(r'^\d+$', step) or not (1 <= int(step) <= len(self.game_steps)): print("Invalid step.") step = raw_input("On which step did you lie: ") step = int(step)-1 repeat_question = self.game_steps[step][0] self.game_steps = self.game_steps[:step] self.ai.replay(self.game_steps) else: repeat_question = None
class TestCowsAndBulls(unittest.TestCase): def setUp(self): self.ai = AI() def test_contrain(self): self.ai.possible_numbers = ((1,2,3,4), (1,2,3,5), (1,2,3,6), (7,8,9,0), (1,2,5,6)) result = self.ai.constrain((1,2,5,6), {'cows': 1, 'bulls': 2}) self.assertEquals(result, ((1,2,3,5),))
def run_instance(instance_num): #change the number after randTSP to switch to different number of cities graph fo = open("randTSP/15/instance_%s.txt"%instance_num, "rw+") # fo = open("randTSP/problem36.txt", "rw+") number_of_city = int(fo.readline()) cities = [] #prepare data for a star algorithm for line in fo: city_info = line.split() cities.append(City(city_info[0], city_info[1], city_info[2])) fo.close() # performing A* Search Algorithm, starting from the first node -- city A astar = AI(cities) result = astar.perfroming_AI() #plot the result fig, ax = plt.subplots() x = [] y = [] names = [] for r in result: print r.name x.append(r.x) y.append(r.y) names.append(r.name) ttl = str(AI.node_expand) + " nodes have expended" print "result is ----------> ",AI.node_expand, "<----------" plt.title(ttl) plt.plot(x, y) for i, txt in enumerate(names): ax.annotate(txt, (x[i], y[i])) plt.show()
def __init__(self,wplayer='human',bplayer='human',clock=60*60,logfile='d:\\temp\\chesslog.txt'): self.zboard = board(plainboardinit) self.white = {'col':'w', 'player':wplayer, 'time':clock, 'hist': [], 'is_in_check':False} self.black = {'col':'b', 'player':bplayer, 'time':clock, 'hist': [], 'is_in_check':False} self.turn = self.white self.turn_count = 1 self.undo_stack = [] self.ai = AI() self.full_notation = '' # quite as the values in hist, but with the count and # + ? ! with open(logfile,'w') as f: self.logfile = logfile #sys.stdout
def main(args): gameType = args[1] if len(args) > 1 else constants.NO_AI game = BigBoard() ai = AI(game) print 'Welcome to Ultimate Tic-Tac-Toe! X goes first. Denote moves ' \ 'with an ordered pair (row, col) where the top left is (0,0)\n\n' \ 'Example move: 4,4' if gameType == constants.TWO_AI: ai2 = AI(game) print game while not game.getState(): game.makeMove(ai2.getNextMove()) print game if not game.getState(): game.makeMove(ai.getNextMove()) print game else: print game while not game.getState(): # game ongoing move = raw_input('Enter your move: ') try: coords = (int(move[0]), int(move[2])) except: coords = (9, 9) if game.makeMove(coords) == constants.ILLEGAL_MOVE: print 'Illegal move. Try again: ' else: print game if gameType == constants.ONE_AI and not game.getState(): game.makeMove(ai.getNextMove()) print game result = game.getState() if result == constants.X_WIN: print 'X wins!' elif result == constants.O_WIN: print 'O wins!' else: print 'Tie game!'
def test_minimax_maximize(): # minimax() returns the maximum value possible test_ai = AI('B') test_board = Board([Piece('9WN'), Piece('17BN'), Piece('21BN')], 'B') assert test_ai.minimax(test_board, True, 1, 'B') == 1 assert test_ai.minimax(test_board, True, 2, 'B') == 1
def main(): #personality = Personality('Test', '/tmp/test-ai/') personality = Personality('Phong', '/tmp/phong-ai/') ai = AI(personality) ai.loadModule(Context(ai)) ai.loadModule(Markov(ai)) ai.loadModule(ConsoleFeedback(ai)) ai.run() while True: ai.processEvent(InstrumentationEvent()) if sys.stdin.isatty(): sys.stdout.write("> ") try: line = sys.stdin.readline() except KeyboardInterrupt: ai.stop() return event = IncomingEvent(text=line.strip(), sender='console', recipient=personality.name) ai.processEvent(event)
#! /usr/bin/env python # -*- coding: utf-8 -*- # python imports import os import sys # chillin imports from chillin_client import GameClient # project imports from ai import AI from ks.models import World config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gamecfg.json") if len(sys.argv) > 1: config_path = sys.argv[1] ai = AI(World()) app = GameClient(config_path) app.register_ai(ai) app.run()
parser.add_argument('-d', help='Sets difficulty.', default='hard', choices=['easy', 'hard'], type=str) parser.add_argument('-v', help='Sets visual mode.', action='store_true') parser.add_argument('-r', help='Restores the saved model.', default=1, choices=[0, 1], type=int) args = parser.parse_args() print(args) # Initialize variables. ai = AI(restore=bool(args.r), save=True) player = [] raindrops = [] raindrop_counter = 0 raindrop_counter_target = 0 x = [] y = [] def reset(): """Resets the game state.""" global player, raindrops, raindrop_counter, x, y player = [9, 4] raindrops = [] if args.d == 'hard': add_rain()
def setUp(self): self.game = Game() self.AI = AI(self.game.UI.BOARD, self.game.winning_routes)
# Recurrent Neural Networks # Partie 1 - Préparation des données # Librairies import pandas as pd import numpy as np import sys from bdd import Bdd from data import Data from ai import AI folder = sys.argv[1] #folder = "" filename = "predict_fuel_dep_and_pdv.h5" idpdv = 33700023 idcarburant = 1 training_set = pd.DataFrame(columns=['A', 'B', 'C', 'D']) bdd = Bdd(True) training_set = bdd.filledTrainingSetFuelDepAndPdv(training_set, idpdv, idcarburant) training_set = np.flip(training_set, 0) data = Data(400) data.filledDataFuelDepAndPdv(training_set) ai = AI(folder, filename) ai.prepetualTraining(data.getXTrain(), data.getYTrain()) ai.save()
return _add_piece def _end_message(self, message): self._message_box = tki.Toplevel() message_display = tki.Entry(self._message_box, justify="center", width=50) message_display.pack() message_display.insert(0, message) # Disable any more pieces being added to the board. for button in self._buttons: button.config(state="disabled") if __name__ == "__main__": game1 = Game() ai = AI() root = tki.Tk() coin_img = tki.PhotoImage(file = "coin_img.gif") background_tile_img = tki.PhotoImage(file = "blank_tile.gif") player_1_piece_img = tki.PhotoImage(file = "red_piece.gif") player_2_piece_img = tki.PhotoImage(file = "yellow_piece.gif") GameBoard(root, game1) root.mainloop() #player1 = False #player2 = False #while True: # if player1 != player2: # if not player1:
def __init__(self): self.voice = Voice() self.brain = AI() self.recognizer = Recognizer()
args = parser.parse_args() logger = logging.getLogger("Acrobot") LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s" logging.basicConfig(filename="Acrobot.log", level=logging.DEBUG, format=LOG_FORMAT) env = gym.make('Acrobot-v1') input_shape = (args.ModelInputShape[0], args.ModelInputShape[1]) action_size = env.action_space.n batch_size = args.BatchSize Model_Name = "Acrobot-dqn.h5" agent = AI(action_size, input_shape, batch_size) if "Acrobot-dqn.h5" in os.listdir(): agent.load(Model_Name) Epochs = args.Epochs temp = [] done = False state = env.reset() actions = [] tot_reward = 0 while not done: env.render() state = np.reshape(state, [1, input_shape[0], input_shape[1]]) Q = agent.act(state) actions.append(Q) state, reward, done, info = env.step(Q)
from ai import AI, Action from services import Services from dbcall import Dtbase import os services = Services() ai = AI() action = Action() db = Dtbase() if __name__ == "__main__": loginsuccess = action.dbCheck() if loginsuccess == True: while True: query = ai.takeCommand().lower() if "time" in query: services.clock() elif 'date' in query: services.date() elif 'search wikipedia for' in query: services.wikisearch(query) elif 'search in chrome' in query: services.chromesearch() elif 'send mail' in query: services.mailService() elif 'memory mode' in query: ai.speak('Switching to memory mode!!!') ai.speak('Begin a phrase with the word remember followed by what you would like me to remember.') query = ai.takeCommand().lower()
def learn(self, player, speed): old_ai = AI('Old AI', 'X') new_ai = AI('New AI', 'O') self.speed = speed counter = 0 self.learning = 1 start_time = time.clock() for i in range(10, 0, -1): counter += 1 new_ai.co1 += i self.mock_round(old_ai, new_ai, counter) if new_ai.co1 - i > 0: counter += 1 new_ai.co1 -= i self.mock_round(old_ai, new_ai, counter) counter += 1 new_ai.co2 += i self.mock_round(old_ai, new_ai, counter) if new_ai.co2 - i > 0: counter += 1 new_ai.co2 -= i self.mock_round(old_ai, new_ai, counter) counter += 1 new_ai.co3 += i self.mock_round(old_ai, new_ai, counter) if new_ai.co3 - i > 0: counter += 1 new_ai.co3 -= i self.mock_round(old_ai, new_ai, counter) counter += 1 new_ai.co3 += i self.mock_round(old_ai, new_ai, counter) if new_ai.co3 - i > 0: counter += 1 new_ai.co3 -= i self.mock_round(old_ai, new_ai, counter) counter += 1 new_ai.co4 += i self.mock_round(old_ai, new_ai, counter) if new_ai.co4 - i > 0: counter += 1 new_ai.co4 -= i self.mock_round(old_ai, new_ai, counter) counter += 1 new_ai.co5 += i self.mock_round(old_ai, new_ai, counter) if new_ai.co5 - i > 0: counter += 1 new_ai.co5 -= i self.mock_round(old_ai, new_ai, counter) player.switch(old_ai) self.learning = 0 print """\n%s\n%s\n%s\nFinished learning! %d games in %d seconds. Final intelligence scores:\n (co1: %d co2: %d, co3: %d, co4: %d, co5: %d)\n%s\n%s\n%s\n""" % ('/'*40,'/'*40,'/'*40, counter,\ time.clock() - start_time,\ player.co1, player.co2, player.co3, player.co4, player.co5,\ '/'*40,'/'*40,'/'*40)
class FourInARow: """Class representing a game of connect-4 with graphics""" def __init__(self, parent, player, port, ip=None): """Instructor of FourInARow object""" self._end_game = False self.__init_graphics__() self._game = Game() self._root = parent self._status = None self._player = player self.__init__ai_or_human() self.__init__ip_distinguisher(ip) self.__communicator = Communicator(self._root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message) def __init_graphics__(self): """initiates the graphic of the game""" self._player1_disc = PhotoImage(file=PLAYER_ONE_DISK) self._player2_disc = PhotoImage(file=PLAYER_TWO_DISK) self._player1_turn = PhotoImage(file=PLAYER_ONE_TURN) self._player2_turn = PhotoImage(file=PLAYER_TWO_TURN) self._win_disc = PhotoImage(file=WIN_DISC) self._player1_won = PhotoImage(file=PLAYER_ONE_WIN_SCREEN) self._player2_won = PhotoImage(file=PLAYER_TWO_WIN_SCREEN) self._draw_screen = PhotoImage(file=DRAW_SCREEN) def __init__ai_or_human(self): """initiates the type of player""" if self._player == HUMAN_PLAYER: self.__init__new_canvas(BOARD) self._canvas.bind("<Button-1>", self.game_screen_callback) if self._player == AI_PLAYER: self.__init__new_canvas(BOARD) self._ai = AI() self._root.after(1, self.make_ai_move) def __init__ip_distinguisher(self, ip): """initiates the player num whether ip is None or not""" if ip is not None: self._player_num = self._game.PLAYER_TWO else: self._player_num = self._game.PLAYER_ONE def __init__new_canvas(self, img): """this method receives an image initiates a new canvas with it.""" self._background = PhotoImage(file=img) self._canvas = Canvas(self._root, height=BACKGROUND_HEIGHT, width=BACKGROUND_WIDTH) self._canvas.create_image(3, 3, image=self._background, anchor=NW) self._canvas.pack() def make_ai_move(self): """makes a move for an ai player""" if not self._end_game: if self._game.get_current_player() == self._player_num: col = self._ai.find_legal_move(self._game, self.general_move) self.__communicator.send_message(str(col)) self._root.after(1, self.make_ai_move) def __handle_message(self, text=None): """this method receives text that represent a column-index and operates general_move with this column.""" if text: column = int(text) self.general_move(column) def game_screen_callback(self, event): """the callback method for the game-screen. The method receives an event and operates other func whether the event was under certain conditions or not""" # numbers in this function represent coordinates on the screen only! # if self._game.get_current_player() != self._player_num: # return x = event.x y = event.y for col in range(game.COLUMNS): if x in range(39 + col * 63, 86 + col * 63) and 26 < y < 447: if self.general_move(col): self.__communicator.send_message(str(col)) def general_move(self, column): """this is the general method for making moves in the game. It receives a column-index and inserts the current player's disc in this column (in the game's board and in the graphic screen as well). If something went wrong during the process an exception is raised.""" self._game.make_move(column) row_counter = 0 for i in range(len(self._game.get_board()) - 1, -1, -1): if self._game.get_board()[i][column] == game.board.FREE_SPACE: break row_counter += 1 self.add_disc(column, game.ROWS - row_counter) return True def add_disc(self, col, row): """adds a current player's graphic disc to the screen.""" # numbers in this function represent coordinates on the screen only! if self._game.get_current_player() == Game.PLAYER_ONE: self._canvas.create_image(64 + 64 * col, 70 + 56.5 * row, image=self._player1_disc) self._canvas.create_image(559, 211, image=self._player1_turn) else: self._canvas.create_image(64 + 64 * col, 70 + 56.5 * row, image=self._player2_disc) self._canvas.create_image(559, 211, image=self._player2_turn) self.game_status() def game_status(self): """checks for the game status. Whether one of the players won or its a draw, and operates other methods according to the status.""" self._status = self._game.get_winner() if self._status[0] in [self._game.PLAYER_ONE, self._game.PLAYER_TWO]: self.show_winner(self._status[0], self._status[1]) self._canvas.bind("<Button-1>", self.exit_game) self._end_game = True if self._status[0] == self._game.DRAW: self._canvas.create_image(3, 3, image=self._draw_screen, anchor=NW) self._canvas.bind("<Button-1>", self.exit_game) self._end_game = True def show_winner(self, winner, win_discs_list): """if a winner was found in the game status method, this method show's the winner's discs that made a sequence and the winner player himself.""" # numbers in this function represent coordinates on the screen only! for disc in win_discs_list: row, col = disc self._canvas.create_image(64 + 64 * col, 70 + 56.5 * row, image=self._win_disc) if winner == self._game.PLAYER_ONE: self._canvas.create_image(3, 3, image=self._player1_won, anchor=NW) else: self._canvas.create_image(3, 3, image=self._player2_won, anchor=NW) def exit_game(self, event): """this method ends the game (including graphics).""" if event: self._root.quit() self._root.destroy()
class Game: def __init__(self, conn, addr, port, name): self.serv_conn = conn self.serv_addr = addr self.serv_port = port self.game_name = name self.ai = AI() self.ai.connection = self.serv_conn #Attempt to connect to the server def connect(self): while True: try: #Attempting to connect self.serv_conn.connect((self.serv_addr, self.serv_port)) except socket.error: #Failed to connect time.sleep(1) else: #Client connected return True def receive(self): data = utility.receive_string(self.serv_conn) message = json.loads(data) if message['type'] == 'changes': self.update_game(message) elif message['type'] == 'player_id': self.ai.my_player_id = message['args']['id'] elif message['type'] == 'game_over': raise GameOverException(message["args"]["winner"], message["args"]["reason"]) return message def wait_for(self, *types): while True: message = self.receive() if message['type'] in types: return message #Attempt to login to the server def login(self): login_json = client_json.login.copy() login_json['args']['username'] = self.ai.username utility.send_string(self.serv_conn, json.dumps(login_json)) message = self.wait_for('success', 'failure') if message['type'] == 'success': #Login success return True else: #Login failed return False #Attempt to create a game on the server def create_game(self): create_game_json = client_json.create_game.copy() if self.game_name is not None: create_game_json['args']['game_name'] = self.game_name utility.send_string(self.serv_conn, json.dumps(create_game_json)) message = self.wait_for('success', 'failure') if message['type'] == "success": self.game_name = message['args']['name'] print("Game created: {}".format(self.game_name)) return True else: #Game creation failed return False #Receive Player ID from server def recv_player_id(self): self.wait_for('player_id') return True #Runs before main_loop has began. def init_main(self): self.wait_for('start_game') self.ai.init() return True #Runs after main_loop has finished. def end_main(self): self.ai.end() return True #Main connection loop until end of game. def main_loop(self): while True: message = self.wait_for('start_turn', 'game_over') if message['type'] == 'game_over': return True if self.ai.my_player_id == self.ai.player_id: utility.v_print("Turn Number: {}".format(self.ai.turn_number)) self.ai.run() utility.send_string(self.serv_conn, json.dumps(client_json.end_turn)) def get_log(self): log_json = client_json.get_log.copy() utility.send_string(self.serv_conn, json.dumps(log_json)) message = self.wait_for('success', 'failure') if message['type'] == "success": file = open(self.game_name + '.glog', 'wb') file.write(message['args']['log'].encode('utf-8')) file.close() #Update game from message def update_game(self, message): if message.get("type") != "changes": return False for change in message.get("args").get("changes"): if change.get("action") == "add": self.change_add(change) elif change.get("action") == "remove": self.change_remove(change) elif change.get("action") == "update": self.change_update(change) elif change.get("action") == "global_update": self.change_global_update(change) return True #Parse the add action def change_add(self, change): values = change.get("values")
MODIFY = 0 THROTTLE = .03 #Lower = worse performance win = pygcurse.PygcurseWindow(WINWIDTH, WINHEIGHT, fullscreen=False) win.autoupdate = False pygame.display.set_caption('So I made this game...') inp = inputr.KeyboardInput() p1 = Player('Joe', '@') p1.levels = { '0': Map(0, level0.nice, level0.info, p1).genHitMap(), '1': Map(1, level1.nice, level1.info, p1).genHitMap(), '2': Map(2, level2.nice, level2.info, p1).genHitMap() } p1.selectMap(1) p1.ai = [AI('Mr. Starting Bot', p1, color=BLUE, Map=1).spawn()] p1.inv.addItem(BadApple()) p1.inv.addItem(WoodSword()) win.fill(bgcolor=BLACK) win.putchars('Teh Game', 20, 3, fgcolor=WHITE) win.putchars('[enter]', 21, 4, fgcolor=WHITE, update=True) #win.update() inp.waitFor('enter') reqs.startup() def addEntity(entity, li): global ENTITIES if li == -1: li = BAD_ENTITIES elif li == 1: li = ENTITIES
class GameScene(Scene): """Main game scene.""" def __init__(self, director, background=(0, 0, 0)): super().__init__(director) self.background = background self.menu_scene = None self.ai_mode_on = False self.screen_rect = director.screen.get_rect() self.player_one = [ Paddle(director, 1, "blue", [pygame.K_w, pygame.K_s]), Paddle(director, 2, "blue", [pygame.K_a, pygame.K_d]), Paddle(director, 3, "blue", [pygame.K_a, pygame.K_d]) ] self.player_two = [ Paddle(director, 4, "red", [pygame.K_j, pygame.K_l]), Paddle(director, 5, "red", [pygame.K_i, pygame.K_k]), Paddle(director, 6, "red", [pygame.K_j, pygame.K_l]) ] self.ball = Ball(director, self.player_one, self.player_two) self.ai = AI(self.player_two, self.ball) self.intermission = True self.count_down = 300 text_rect = pygame.Rect(0, 0, 500, 100) text_rect.center = self.screen_rect.center self.ready_text = Text(text_rect, 80, (0, 150, 0), director.screen, "Ready?") self.set_text = Text(text_rect, 80, (0, 150, 0), director.screen, "Set") self.go_text = Text(text_rect, 80, (0, 150, 0), director.screen, "Go!") self.player_one_score_rect = pygame.Rect(0, 30, 60, 60) self.player_one_score_rect.centerx = self.screen_rect.centerx - 80 self.player_one_score_text = Text(self.player_one_score_rect, 80, (255, 255, 255), director.screen, "0") self.player_two_score_rect = pygame.Rect(0, 30, 60, 60) self.player_two_score_rect.centerx = self.screen_rect.centerx + 80 self.player_two_score_text = Text(self.player_two_score_rect, 80, (255, 255, 255), director.screen, "0") self.play_up_to_text_rect = pygame.Rect(0, 120, 40, 40) self.play_up_to_text_rect.centerx = self.screen_rect.centerx self.play_up_to_text = Text(self.play_up_to_text_rect, 40, (140, 0, 0), director.screen, "7") self.player_one_score = 0 self.player_two_score = 0 self.play_up_to = 7 def set_menu_scene(self, scene): self.menu_scene = scene def keydown(self, key): for i in range(len(self.player_one)): self.player_one[i].keydown(key) for i in range(len(self.player_two)): self.player_two[i].keydown(key) def keyup(self, key): for i in range(len(self.player_one)): self.player_one[i].keyup(key) for i in range(len(self.player_two)): self.player_two[i].keyup(key) def reset_board(self): for i in range(len(self.player_one)): self.player_one[i].reset() for i in range(len(self.player_two)): self.player_two[i].reset() self.ball.reset() self.count_down = 3000 self.intermission = True def reset(self): self.reset_board() self.player_one_score = 0 self.player_two_score = 0 self.play_up_to = 7 self.player_one_score_text.text = str(self.player_one_score) self.player_one_score_text.prep_img() self.player_two_score_text.text = str(self.player_two_score) self.player_two_score_text.prep_img() self.play_up_to_text.text = str(self.play_up_to) self.play_up_to_text.prep_img() def update(self): if self.intermission is False: for i in range(len(self.player_one)): self.player_one[i].update() for i in range(len(self.player_two)): self.player_two[i].update() if self.ai_mode_on: self.ai.update() self.ball.update() if self.ball.rect.top <= 0 or \ self.ball.rect.bottom >= self.screen_rect.bottom or \ self.ball.rect.left <= 0 or \ self.ball.rect.right >= self.screen_rect.right: if self.ball.rect.centerx > self.screen_rect.centerx: self.player_one_score += 1 self.player_one_score_text.text = \ str(self.player_one_score) self.player_one_score_text.prep_img() if self.player_one_score is self.play_up_to: self.menu_scene.reset() self.director.scene = self.menu_scene else: self.player_two_score += 1 self.player_two_score_text.text = \ str(self.player_two_score) self.player_two_score_text.prep_img() if self.player_two_score is self.play_up_to: self.menu_scene.reset() self.director.scene = self.menu_scene self.reset_board() else: if self.count_down is 0: self.intermission = False else: self.count_down -= 1 def render(self): self.director.screen.fill(self.background) pygame.draw.line(self.director.screen, (200, 200, 200), (self.screen_rect.centerx, 0), (self.screen_rect.centerx, self.screen_rect.bottom)) pygame.draw.rect(self.director.screen, (255, 255, 255), self.player_one_score_rect, 1) self.player_one_score_text.render() pygame.draw.rect(self.director.screen, (255, 255, 255), self.player_two_score_rect, 1) self.player_two_score_text.render() pygame.draw.rect(self.director.screen, (255, 255, 255), self.play_up_to_text_rect, 1) self.play_up_to_text.render() for i in range(len(self.player_one)): self.player_one[i].render() for i in range(len(self.player_two)): self.player_two[i].render() self.ball.render() if self.intermission: if self.count_down > 2000: self.ready_text.render() elif self.count_down > 1000: self.set_text.render() else: self.go_text.render()
parser.add_argument("--playai", action='store_true', default=False, help="Play game with AI") parser.add_argument("--playnaiveai", action='store_true', default=False, help="Play game with naive AI") args = parser.parse_args() verbose = args.verbose if args.train: if verbose: print("Contiune to train AI with state shape: {0}".format(__default_state_shape__)) from train import TrainAI from ai import AI ai = AI( state_shape=__default_state_shape__, action_dim=__default_action_dim__, verbose=verbose ) if verbose: print("Loading AI model from file: [{0}] ... ".format(__filename__),end="") ai.load_nnet(__filename__) if verbose: print("OK!") trainai = TrainAI( state_shape=__default_state_shape__, ai=ai, verbose=verbose ) trainai.start(__filename__)
# Import necessary stuff import random from game import Game from monsters.stupid_monster import StupidMonster # TODO This is your code! sys.path.insert(1, '../group13') from ai import AI # Create the game random.seed(8) # TODO Change this if you want different random choices g = Game.fromfile('map.txt') g.add_monster(StupidMonster( "stupid", # name "S", # avatar 3, 9 # position )) # TODO Add your character g.add_character(AI( "Chut", # name "C", # avatar 0, 0, 100 # position )) # Run! g.go(1)
works with different files for each class, no player class, choose which one to begin, both players may be computers """ if __name__ == '__main__': """ player 1: human/pc player 2: pc """ depth = 4 WIN = 5000 LOOSE = -5000 DRAW = 0 # human vs ai, human starts ac = ArduinoCommunication() mybrain = AI(player=2, depth=depth, win=WIN, loose=LOOSE) myboard = Board(win=WIN, loose=LOOSE, draw=DRAW) mygame = Game(start_player=1, board=myboard, comm=ac, both_are_pc=False, player_2_ai=mybrain) mygame.start() # # ai vs ai # brain_1 = AI(player=1, depth=10, win=WIN, loose=LOOSE) # brain_2 = AI(player=2, depth=10, win=WIN, loose=LOOSE) # myboard = Board(win=WIN, loose=LOOSE, draw=DRAW) # mygame = Game(start_player=2, board=myboard, both_are_pc=True, player_1_ai=brain_1, player_2_ai=brain_2) # mygame.start()
def main(): """The application's entry point. """ print("ANNFlappy V0.0.3. Window dimensions: " + str(WIN_WIDTH) + ', ' + str(WIN_HEIGHT)) brain = AI(20) brain.best_fit = 0 index = 0 if os.path.exists("best_fit.genome"): print("Filling with best candidate from another run.") for genome in brain.genomes: genome.load("best_fit.genome") brain.anns[index].set_internal_data(genome.genome) index += 1 if (len(brain.genomes) / 2) < index: break brain.best_fit = brain.genomes[0].fitness print("Name of the candidate: " + brain.genomes[0].name) else: print("Starting from scratch.") print("Populated " + str(index) + " genomes from file.") pygame.init() display_surface = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) pygame.display.set_caption('ANN Flappy Bird') clock = pygame.time.Clock() score_font = pygame.font.SysFont(None, 32, bold=True) # default font images = load_images() the_end = False player_nr = 0 rounds = 0 print('SHALL WE PLAY A GAME?') while not the_end: done = paused = False if len(brain.anns) <= player_nr: brain.evolve() player_nr = 0 player = brain.anns[player_nr] print('Player ' + str(player_nr)) if rounds == 0: brain.genomes[player_nr].fitness = 0 next_ai_clock = 0 # the bird stays in the same x position, so bird.x is a constant # center bird on screen bird = Bird(50, int(WIN_HEIGHT / 2 - Bird.HEIGHT / 2), 2, (images['bird-wingup'], images['bird-wingdown'])) pipes = deque() # this counter is only incremented if the game isn't paused frame_clock = 0 score = 0 while not done: clock.tick(FPS) # Handle this 'manually'. If we used pygame.time.set_timer(), # pipe addition would be messed up when paused. if not (paused or frame_clock % msec_to_frames(PipePair.ADD_INTERVAL)): pp = PipePair(images['pipe-end'], images['pipe-body']) pipes.append(pp) for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE): done = the_end = True break elif e.type == KEYUP and e.key in (K_PAUSE, K_p): paused = not paused # elif e.type == MOUSEBUTTONUP or (e.type == KEYUP and # e.key in (K_UP, K_RETURN, K_SPACE)): # bird.msec_to_climb = Bird.CLIMB_DURATION if paused: continue # don't draw anything # Wait a little before next action so as to not allow the AI to go # mad with key presses. if next_ai_clock < time.clock(): ai_data = list() ai_data.append(bird.y) ai_data.append(pipes[0].x - bird.x) # Distance from pipe ai_data.append(pipes[0].top_height_px + # End of top pipe 90 - # Most of the free space bird.y) # The bird if player.action(ai_data): bird.msec_to_climb = Bird.CLIMB_DURATION # Try to stop the network from going nuts with the clicks brain.genomes[player_nr].fitness -= 0.5 next_ai_clock = time.clock() + 0.25 # check for collisions pipe_collision = any(p.collides_with(bird) for p in pipes) if pipe_collision or (0 >= bird.y or bird.y >= WIN_HEIGHT - Bird.HEIGHT): done = True for x in (0, WIN_WIDTH / 2): display_surface.blit(images['background'], (x, 0)) while pipes and not pipes[0].visible: pipes.popleft() for p in pipes: p.update() display_surface.blit(p.image, p.rect) bird.update() display_surface.blit(bird.image, bird.rect) # update and display score for p in pipes: if p.x + PipePair.WIDTH < bird.x and not p.score_counted: score += 1 # Give some credit for passing a pipe. brain.genomes[player_nr].fitness += 10 p.score_counted = True score_surface = score_font.render(str(score), True, (255, 255, 255)) score_x = WIN_WIDTH / 2 - score_surface.get_width() / 2 display_surface.blit(score_surface, (score_x, PipePair.PIECE_HEIGHT)) pygame.display.flip() frame_clock += 1 brain.genomes[player_nr].fitness += 1 pygame.display.set_caption('ANN Flappy Bird- Generation ' + str(brain.generation) + ' - player ' + str(player_nr) + ' - round ' + str(rounds) + ' - fitness ' + str(brain.genomes[player_nr].fitness)) print('Game over for player ' + brain.genomes[player_nr].name + '! Score: %i' % score) print("Fitness: " + str(brain.genomes[player_nr].fitness)) rounds += 1 if rounds == 5: if brain.genomes[player_nr].fitness > brain.best_fit: print("Best fit ever, saving to file.") brain.genomes[player_nr].save("best_fit.genome") brain.best_fit = brain.genomes[player_nr].fitness player_nr += 1 print("Last round for player.") rounds = 0 pygame.quit()
""" DQN learning for tic tac toe """ import yaml from ai import AI if __name__ == "__main__": # Load the YAML config file CONFIG_FILE = 'config.yml' with open(CONFIG_FILE, 'r') as ymlfile: CONFIG = yaml.load(ymlfile) if CONFIG: AI_GAME = AI(CONFIG) AI_GAME.learn()
class Game: def __init__(self, map_file_name, curiosity=True): self.env = Environment(map_file_name) self.cat = Cat(("orange", (255, 165, 0)), 0, 0) self.mouse = Mouse(("gray", (128, 128, 128)), 0, 0) self.cheese = Cheese(("yellow", (255, 255, 0)), 0, 0) self.init_agents_position() self.action = Action() self.feed = 0 self.eaten = 0 self.age = 0 self.ai = AI() pygame.init() self.size = 40 self.screen = None self.activated = False self.curiosity = curiosity def show_game(self): if self.screen is None: self.screen = pygame.display.set_mode( (self.env.width * self.size, self.env.height * self.size)) self.activated = True def redraw(self): if self.screen is None: return for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() self.redraw_cells() self.redraw_cheese() self.redraw_mouse() self.redraw_cat() pygame.display.set_caption("age:%s,feed:%s,eaten:%s" % (self.age, self.feed, self.eaten)) pygame.display.flip() time.sleep(0.4) def redraw_cells(self): if self.screen is None: return for cell in self.env.get_all_cells(): self.screen.fill( cell.color[1], (cell.x * self.size, cell.y * self.size, self.size, self.size)) def redraw_cat(self): if self.screen is None: return font = pygame.font.Font(None, 30) label = font.render("Cat", 1, (255, 0, 0)) self.screen.fill(self.cat.color[1], (self.cat.x * self.size, self.cat.y * self.size, self.size, self.size)) self.screen.blit(label, (self.cat.x * self.size, self.cat.y * self.size)) def redraw_cheese(self): if self.screen is None: return font = pygame.font.Font(None, 20) label = font.render("Cheese", 1, (255, 0, 0)) self.screen.fill(self.cheese.color[1], (self.cheese.x * self.size, self.cheese.y * self.size, self.size, self.size)) self.screen.blit( label, (self.cheese.x * self.size, self.cheese.y * self.size)) def redraw_mouse(self): if self.screen is None: return font = pygame.font.Font(None, 20) label = font.render("Mouse", 1, (255, 0, 0)) self.screen.fill(self.mouse.color[1], (self.mouse.x * self.size, self.mouse.y * self.size, self.size, self.size)) self.screen.blit(label, (self.mouse.x * self.size, self.mouse.y * self.size)) def pick_random_location(self, agent, other_agents): while True: cell = self.env.get_random_cell() for other_agent in other_agents: if other_agent.get_position() == cell.get_position(): break else: if not cell.is_wall(): agent.set_position(cell.get_position()) return def init_agents_position(self): agents = [self.cat, self.mouse, self.cheese] for cur_a in agents: self.pick_random_location(cur_a, [a for a in agents if a != cur_a]) def get_full_state(self): """ 在现有规则下的所有可能状态 1.墙里不能有其他东西 2.cat,cheese,mouse可以在同一个格 """ state = [] cat_position = self.cat.get_position() cheese_position = self.cheese.get_position() mouse_position = self.mouse.get_position() for cell in self.env.get_all_cells(): cell_position = cell.get_position() if cell.is_wall(): state.append(1) elif cell_position == mouse_position == cat_position == cheese_position: state.append(2) elif cell_position == mouse_position == cat_position: state.append(3) elif cell_position == mouse_position == cheese_position: state.append(4) elif cell_position == cat_position == cheese_position: state.append(5) elif cell_position == mouse_position: state.append(6) elif cell_position == cat_position: state.append(7) elif cell_position == cheese_position: state.append(8) else: state.append(9) return tuple(state) def get_reward(self): """ 这里假设猫在同一格里总是先发现和吃掉老鼠 对于老鼠来说奔跑是需要体力的 """ if self.mouse.get_position() == self.cat.get_position(): return -100 elif self.mouse.get_position() == self.cheese.get_position(): return 50 else: return -1 def update(self): cur_state = self.get_full_state() reward = self.get_reward() action = self.ai.choose_action(cur_state) if self.mouse.get_position() == self.cat.get_position(): self.pick_random_location(self.mouse, [self.cat, self.cheese]) self.eaten += 1 elif self.mouse.get_position() == self.cheese.get_position(): self.pick_random_location(self.cheese, [self.mouse, self.cat]) self.feed += 1 self.cat.update(self.env.get_cell(self.mouse.x, self.mouse.y), self.env) self.mouse.update(action, self.env) next_state = self.get_full_state() self.ai.learn_q(cur_state, action, reward, next_state) self.age += 1 self.ai.epsilon = self.age**-0.2 if self.curiosity else 0
class GridWorld(): def __init__(self): pygame.init() pygame.display.set_caption("Grid World") self.clock = pygame.time.Clock() self.last_tick = pygame.time.get_ticks() self.screen_res = [400, 470] self.font = pygame.font.SysFont("Calibri", 16) self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32) self.show_checked = True self.quit = False self.type = "dfs" self.grid = Grid(True) self.ai = AI(self.grid, self.type) self.run = False self.pause = False def loop(self): while True: self.draw() self.clock.tick(60) self.mpos = pygame.mouse.get_pos() if self.run and not self.pause: if self.ai.finished: if not self.ai.failed: self.ai.get_result() self.run = False else: self.ai.make_step() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() if event.key == K_c: self.ai.set_search() self.run = False if event.key == K_RETURN: if not self.run: self.ai.set_search() self.run = True self.pause = False else: self.pause = not self.pause if not self.run: if event.key == K_w: self.grid.save("saved_grid") if event.key == K_l: try: with open("saved_grid") as file: self.grid.load(file.read()) except: print("no saved file present") if event.key == K_m: self.grid.random() if event.key == K_n: self.grid.random_clear() if event.key == K_1: self.grid.clear_path() self.type = "dfs" self.ai.set_type(self.type) if event.key == K_2: self.grid.clear_path() self.type = "bfs" self.ai.set_type(self.type) if event.key == K_3: self.grid.clear_path() self.type = "ucs" self.ai.set_type(self.type) if event.key == K_4: self.grid.clear_path() self.type = "astar" self.ai.set_type(self.type) for node in self.grid.nodes.values(): if node.get_rect(pygame)[1].collidepoint( game.mpos): if event.key == K_p: self.grid.reset() node.make_puddle() if event.key == K_r: self.grid.reset() node.make_grass() if event.key == K_x: self.grid.reset() node.clear() if event.key == K_s: self.grid.reset() self.grid.set_start(node.pos) if event.key == K_g: self.grid.reset() self.grid.set_goal(node.pos) def blitInfo(self): line1 = self.font.render( "Esc: exit; Enter: search/pause; c: clear path; m: random board (clear first)", 1, WHITE) line2 = self.font.render( "s: place start; g: place goal; p: place puddle; r: place grass; x: clear node", 1, WHITE) line3 = self.font.render( "w: save board; l: load board, n: no obstacles", 1, WHITE) line4 = self.font.render("1: DFS, 2: BFS, 3: UCS, 4: A*", 1, WHITE) if self.ai.finished and not self.ai.failed: score = str(self.ai.final_cost) elif self.ai.finished and self.ai.failed: score = "[no path]" else: score = "..." line5 = self.font.render( "Mode: {}; Score: {}".format(self.type, score), 1, WHITE) self.screen.blit(line1, (5, 5)) self.screen.blit(line2, (5, 20)) self.screen.blit(line3, (5, 35)) self.screen.blit(line4, (5, 50)) self.screen.blit(line5, (5, NODE_W * self.grid.height + OFFSET[1] + 5)) def draw(self): self.screen.fill(0) self.grid.update(self, pygame) self.blitInfo() pygame.display.update()
class Game(): def __init__(self): self.table = self.get_init_state() self.n_pieces = 4 self.max_pieces = 8 * 8 self.n_possible_moves = 0 self.players = ['w', 'b'] self.computer_piece = 'b' self.points = {'w': 2, 'b': 2} self.next_player = {'w': 'b', 'b': 'w'} def get_init_state(self): table = [['_' for x in range(8)] for y in range(8)] table[3][3] = 'b' table[3][4] = 'w' table[4][3] = 'w' table[4][4] = 'b' return table def print_table(self): print "" for x in range(9): for y in range(9): if (x == 0): if (y == 0): print " ", else: print chr(y + 96), "", elif (y == 0): print x, else: print self.table[x - 1][y - 1] + " ", print "" print "" def play(self): self.quitted = False while True: try: AI_player = raw_input( "Which player should AI be? ('b' or 'w')") if (AI_player == 'w' or AI_player == 'b'): self.computer_piece = AI_player self.AI = AI(self, 3, AI_player) break else: print "Wrong input format, try again (write w or b)" except: print "Wrong input format caused error. Write w or b" while (self.n_pieces < self.max_pieces): print "\n" print "===================== NEW ROUND =======================" print "Current game board: " piece = self.players[self.n_pieces % 2] if (piece == self.computer_piece): state = self.AI.get_next_state() self.set_state(state) self.print_table() else: self.update_possible_moves(piece) print "Possible number of moves for", print "player", piece + ":", self.n_possible_moves if (self.quitted or self.n_possible_moves == 0): break self.print_table() self.delete_tips() self.play_next_round(piece) self.print_score() print "Game finished!" self.print_score() def delete_tips(self): for row in range(8): for col in range(8): if self.table[row][col] == 'x': self.table[row][col] = '_' def update_possible_moves(self, piece): self.n_possible_moves = 0 self.possible_moves = [] for row in range(8): for col in range(8): if self.legal_move(self.table, piece, row, col): self.table[row][col] = 'x' self.n_possible_moves += 1 self.possible_moves.append((row, col)) def get_possible_moves(self, state, piece): possible_moves = [] for row in range(8): for col in range(8): if self.legal_move(state, piece, row, col): possible_moves.append((row, col)) return possible_moves def get_state(self): return self.table def get_current_piece(self): if (self.n_pieces % 2 == 0): return 'w' else: return 'b' def get_state_piece(self, state): n_pieces = get_piece_count(state) return self.players[n_pieces % 2] def get_piece_count(self, state): n_pieces = 0 for row in range(8): for col in range(8): if state[row][col] == 'w' or state[row][col] == 'b': n_pieces += 1 return n_pieces def set_state(self, state): self.table = state self.n_pieces = get_piece_count(self.table) def get_score(self, state, piece): score = 0 for row in range(8): for col in range(8): if (state[row][col] == piece): score += 1 return score def calc_score(self): score_w = 0 score_b = 0 for x in range(8): for y in range(8): if (self.table[x][y] == 'b'): score_b += 1 elif (self.table[x][y] == 'w'): score_w += 1 return score_w, score_b def print_score(self): score_w, score_b = self.calc_score() print "______________________" print "Score: " print "White: ", score_w, "Black: ", score_b print "______________________" def play_from_state(self, state, current_piece, x, y): piece = self.next_player[current_piece] self.put_piece(state, piece, x, y) return self.table, piece def computer_play_next_round(self, piece, x, y): print piece, "player next." self.put_piece(self.table, piece, x, y) print "Computer played:", str(x + 1) + chr(y + 96) def play_next_round(self, piece): print piece, "player next." while True: try: print "_____________________________________________" coords = raw_input("Where do you want to put \n" + "your piece (e.g. 1a)? (type q to quit) \n") if (coords == 'q'): self.quit() elif (len(coords) == 2): x = int(coords[0]) - 1 y = ord(coords[1]) - 97 if not (0 <= y < 8): raise ValueError self.put_piece(self.table, piece, x, y) else: raise ValueError break except (NameError, ValueError, IndexError) as e: print "Wrong input format, try again! (e.g. 3c)" except IllegalMoveError as e: pass print "_____________________________________________" def quit(self): self.print_table() self.print_score() self.quitted = True print "Quitting..." sys.exit() def put_piece(self, state, piece, x, y): self.table = state if (piece == 'w' or piece == 'b'): if (self.legal_move(state, piece, x, y)): self.convert_table(piece, x, y) self.table[x][y] = piece self.n_pieces += 1 self.print_table() else: print "Illegal move" raise IllegalMoveError else: print "Wrong format for piece. Please write 'w' or 'b'!" def convert_table(self, piece, x, y): for row_dir in range(-1, 2): for col_dir in range(-1, 2): if (row_dir == 0 and col_dir == 0): continue if self.direction_ok(self.table, piece, x, y, row_dir, col_dir): self.convert_direction(piece, x, y, row_dir, col_dir) def convert_direction(self, piece, x, y, row_dir, col_dir): x += row_dir y += col_dir while (self.table[x][y] != piece and self.table[x][y] != '_'): self.table[x][y] = piece x += row_dir y += col_dir def legal_move(self, state, piece, x, y): if (state[x][y] == '_'): for row_dir in range(-1, 2): for col_dir in range(-1, 2): if (row_dir == 0 and col_dir == 0): continue if self.direction_ok(state, piece, x, y, row_dir, col_dir): return True return False def direction_ok(self, state, piece, x, y, row_dir, col_dir): x += row_dir y += col_dir if not self.in_boundaries(x, y): return False if piece == 'w' and state[x][y] != 'b': return False if piece == 'b' and state[x][y] != 'w': return False x += row_dir y += col_dir while (self.in_boundaries(x, y)): if (state[x][y] == piece): return True x += row_dir y += col_dir return False def in_boundaries(self, x, y): if ((0 <= x < 8) and (0 <= y < 8)): return True return False
class GameEngine: def __init__(self, state_shape, filename='best_model.h5', verbose=False): self.verbose = verbose self.ai = AI(state_shape=state_shape, verbose=self.verbose) self.ai.load_nnet(filename) self.state_shape = state_shape self.channel = self.state_shape[2] - 1 # Even number # state_shape = [lenght, height, channel] self.chessboard = ChessBoard(board_shape=self.state_shape[:2]) self.boards = list() # Train data self.states = list() self.chesses = [1, -1] self.current_player = 0 # Control game self.waitingforplay = True self.human_flag = False def get_availables(self): actions = self.chessboard.get_availables() return actions def update_current_player(self): self.current_player += 1 self.current_player %= 2 def update_states(self): ''' Update states state: [X_{t-channel+1}, Y_{t-channel+1}, ..., X{t}, Y{t}, C] ''' player = self.current_player opposite_player = (self.current_player + 1) % 2 state = np.zeros(self.state_shape) # feature plane state[:, :, -1] = player * np.ones(self.state_shape[:-1]) # state planes time_steps = int(self.channel / 2) len_boards = len(self.boards) for i in range(time_steps, ): if len_boards - 1 - i >= 0: index = 2 * i board = self.boards[len_boards - 1 - i] state[:, :, self.channel - 1 - index] = 1 * (board == self.chesses[player]) state[:, :, self.channel - 1 - (index + 1)] = 1 * (board == self.chesses[opposite_player]) # Append it into the state list self.states.append(state) def get_state(self): ''' Get state vector of the current player ''' if len(self.states) == 0: state = np.zeros(self.state_shape) else: state = np.array(self.states[-1]) return state def play(self, action): ''' Play game formally ''' flag = self.chessboard.play(action) # Update data board = self.chessboard.get_board() self.boards.append(board) self.update_current_player() self.update_states() return flag def get_availables(self): actions = self.chessboard.get_availables() return actions def play_human(self, pos): Nx, Ny = self.chessboard.get_shape() action = pos[0] + Nx * pos[1] if action in self.get_availables(): self.human_flag = self.play(action) self.waitingforplay = False def start(self): self.ui = viewer.UI(pressaction=self.play_human, chessboardinfo=self.chessboard.get_board()) self.ui.start() while True: while self.waitingforplay: pass if self.human_flag: self.endgame(role='Human') break action = self.ai.play(self) computer_flag = self.play(action) if computer_flag: self.endgame(role='Computer') break self.ui.setchessboard(self.chessboard.get_board()) self.waitingforplay = True def endgame(self, role): print(role + " Win") self.ui.gameend(role) sys.exit()
from game_engine import GameStatus from game_engine import GameEngine from ai import AI import pickle import time import numpy as np import config config.init() ai1 = AI(1) ai2 = AI(2, dont_use_nn=True) game = GameEngine() game.reset_game() game.show_board() # lets put two ais in front of each other: while game.get_game_status() == GameStatus.IN_PROGRESS: board, player = game.get_game_state() if player == 1: action = ai1.select_action(board) else: action = ai2.select_action(board) # action = int(input("select a column to drop your block: ")) game.register_action(player, action) print("player {} took action {}".format(player, action)) game.show_board() print("game state {}".format(game.get_game_status())) # print("Consumed %sB memory" % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) # ValueEstimator(5, 42, 10)
class GameGrid(Frame): def __init__(self): Frame.__init__(self) self.grid() self.master.title('2048') self.grid_cells = [] self.init_grid() self.init_matrix() self.update_grid_cells() self.AI = AI() self.run_game() self.mainloop() def run_game(self): while True: self.board.move(self.AI.get_move(self.board)) self.update_grid_cells() self.add_random_tile() self.update_grid_cells() if len(self.board.get_available_moves()) == 0: self.game_over_display() break self.update() def game_over_display(self): for i in range(4): for j in range(4): self.grid_cells[i][j].configure(text="", bg=BACKGROUND_COLOR_CELL_EMPTY) self.grid_cells[1][1].configure(text="TOP", bg=BACKGROUND_COLOR_CELL_EMPTY) self.grid_cells[1][2].configure(text="4 TILES:", bg=BACKGROUND_COLOR_CELL_EMPTY) top_4 = list( map(int, reversed(sorted(list(self.board.grid.flatten()))))) self.grid_cells[2][0].configure(text=str(top_4[0]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048]) self.grid_cells[2][1].configure(text=str(top_4[1]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048]) self.grid_cells[2][2].configure(text=str(top_4[2]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048]) self.grid_cells[2][3].configure(text=str(top_4[3]), bg=BACKGROUND_COLOR_DICT[2048], fg=CELL_COLOR_DICT[2048]) self.update() def init_grid(self): background = Frame(self, bg=BACKGROUND_COLOR_GAME, width=SIZE, height=SIZE) background.grid() for i in range(GRID_LEN): grid_row = [] for j in range(GRID_LEN): cell = Frame(background, bg=BACKGROUND_COLOR_CELL_EMPTY, width=SIZE / GRID_LEN, height=SIZE / GRID_LEN) cell.grid(row=i, column=j, padx=GRID_PADDING, pady=GRID_PADDING) # font = Font(size=FONT_SIZE, family=FONT_FAMILY, weight=FONT_WEIGHT) t = Label(master=cell, text="", bg=BACKGROUND_COLOR_CELL_EMPTY, justify=CENTER, font=FONT, width=4, height=2) t.grid() grid_row.append(t) self.grid_cells.append(grid_row) def gen(self): return randint(0, GRID_LEN - 1) def init_matrix(self): self.board = GameBoard() self.add_random_tile() self.add_random_tile() def update_grid_cells(self): for i in range(GRID_LEN): for j in range(GRID_LEN): new_number = int(self.board.grid[i][j]) if new_number == 0: self.grid_cells[i][j].configure( text="", bg=BACKGROUND_COLOR_CELL_EMPTY) else: n = new_number if new_number > 2048: c = 2048 else: c = new_number self.grid_cells[i][j].configure( text=str(n), bg=BACKGROUND_COLOR_DICT[c], fg=CELL_COLOR_DICT[c]) self.update_idletasks() def add_random_tile(self): if randint(0, 99) < 100 * 0.9: value = 2 else: value = 4 cells = self.board.get_available_cells() pos = cells[randint(0, len(cells) - 1)] if cells else None if pos is None: return None else: self.board.insert_tile(pos, value) return pos
class Game: #Make board board = chess.Board() # standard board #board = chess.Board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") #board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1") # castling testing case #board = chess.Board("3r4/K7/3r4/k7/8/8/8/8 b KQkq - 0 1") # check mate case #Make Electronics Control Class Electronics_control = Electronics_Control() Move_validation = move_val() cpu_AI = AI() hint_AI = AI(4) ai_on = False ai_move = None ai_turn = False white_pos = [[False for i in range(0, 8)] for j in range(0, 8)] black_pos = [[False for i in range(0, 8)] for j in range(0, 8)] #Variables for initial placement and some for live_highlighting brightness = 3 setup_array = [ [None for i in range(0, 6)] for j in range(0, 2) ] #2D array holding the tuples of the locations for each type of piece (pawn, knight, bishop... as well as white and black) #Color Scheme (tuples) color_dict = { 'red': (255, 0, 0), 'green': (0, 255, 0), 'blue': (0, 0, 255), 'magenta': (255, 0, 255), 'yellow': (255, 255, 0), 'cyan': (0, 255, 255), 'black': (0, 0, 0), 'white': (255, 255, 255) } #2D array of tuples indicating the color of each square. Initialize with all LEDs OFF LED_data = [[(0, 0, 0) for i in range(0, 8)] for j in range(0, 8)] ############ #Variables for live_highlighting selected_piece = 0 #a square location (ex: 0 - 63) move_made = None #temporarily holds moves made (in UCI format ex: g1f3) castle_list = None #holds the king's castle move (i.e. 'E1G1' format) array_legal_moves = [] #will hold the squares for the legal moves king_in_check = False #will hold true/false value that says if king is in check king_pos = None #will highlight king square in red illegal_move = None #will hold true/false value that says if an illegal move was made #castling_state = False #Tracks if castling happened #castling_state_array = [False, False, False, False] # loc 1 - w_kingside, loc 2 - w_queenside, loc 3 - b_kingside, loc 4 - b_queenside end_turn = False #Only true if user hits clock or time runs out #highlight arrays highlight_legal = True highlight_illegal = True highlight_king = True highlight_last = True highlight_hint = True highlight_wrong_move = False legal_move_highlight = [ ] #holds locations to highlight for legal move highilighting last_move_highlight = [ ] #holds locations to highlight for last move highlighting illegal_array = [ ] #will hold array of two positions to show move from and move to square and highlight them yellow wrong_move_array = [] king_check_highlight = [ ] #holds locations to highlight for king check highlighting castle_move_highlight = [ ] #holds locations to highlight for castle (if castling was done) hint_highlight = [] ai_move_highlight = [] #piece_danger_highlight = [] chess_w = None chess_b = None rotate_board = 90 #movement move_buffer = None warning_message = "Illegal Move" def __init__(self, settings=None): print("New 'Game' class object created") self.board = chess.Board() # this line clears board correctly # now can open new game without old board existing print(self.board) if settings != None: if settings["p1 color"]: # P1 is white self.chess_w = "P1" self.chess_b = "P2" else: self.chess_w = "P2" self.chess_b = "P1" if settings["num players"] == 1: # make AI level = settings["ai diff"] self.cpu_AI.set_level(level) if settings["p2 color"]: # P2 is white self.chess_w = "AI{}".format(level) self.cpu_AI.set_color(True) self.ai_make_move() else: self.cpu_AI.set_color(False) self.chess_b = "AI{}".format(level) #rotate board based on p1 color if settings["p1 color"]: self.rotate_board = 90 else: self.rotate_board = 270 hint_on = settings["tutor on"] #settings["game timer"] #settings["move timer"] self.start_list_LED_array() def __del__(self): print("deleted") def update_settings(self, h_hint, h_legal, h_illegal, h_king, h_last): self.highlight_hint = h_hint self.highlight_legal = h_legal self.highlight_illegal = h_illegal self.highlight_king = h_king self.highlight_last = h_last #Initial Board setup functions def start_list_LED_array(self): #row = 0 - white, 1 - black #col = 0 - Pawn, 1 - Knight, 2 - Bishop, ... , 6 - King self.setup_array = [[None for i in range(0, 6)] for j in range(0, 2)] self.setup_array[0][0] = list( self.board.pieces(chess.PAWN, chess.WHITE)) self.setup_array[0][1] = list( self.board.pieces(chess.KNIGHT, chess.WHITE)) self.setup_array[0][2] = list( self.board.pieces(chess.BISHOP, chess.WHITE)) self.setup_array[0][3] = list( self.board.pieces(chess.ROOK, chess.WHITE)) self.setup_array[0][4] = list( self.board.pieces(chess.QUEEN, chess.WHITE)) self.setup_array[0][5] = list( self.board.pieces(chess.KING, chess.WHITE)) self.setup_array[1][0] = list( self.board.pieces(chess.PAWN, chess.BLACK)) self.setup_array[1][1] = list( self.board.pieces(chess.KNIGHT, chess.BLACK)) self.setup_array[1][2] = list( self.board.pieces(chess.BISHOP, chess.BLACK)) self.setup_array[1][3] = list( self.board.pieces(chess.ROOK, chess.BLACK)) self.setup_array[1][4] = list( self.board.pieces(chess.QUEEN, chess.BLACK)) self.setup_array[1][5] = list( self.board.pieces(chess.KING, chess.BLACK)) #Place the pieces according to the chess piece layout in board() def make_start_LED_array(self, which_piece): self.clear_board_LED() for x_1 in range(0, len(self.setup_array[0][which_piece - 1])): #setup white pieces tile_val = self.setup_array[0][which_piece - 1][x_1] row = tile_val // 8 col = tile_val % 8 if self.white_pos[row][col] == False: self.LED_data[row][col] = self.color_dict[ "magenta"] #white pieces for x_2 in range(0, len(self.setup_array[1][which_piece - 1])): #setup black pieces tile_val = self.setup_array[1][which_piece - 1][x_2] row = tile_val // 8 col = tile_val % 8 if self.black_pos[row][col] == False: self.LED_data[row][col] = self.color_dict[ "cyan"] #black pieces #Check if all of the pieces of that specific type is placed on the board. If so, it will move onto the next type of piece after this function def check_start_up_state(self, which_piece): [self.white_pos, self.black_pos ] = self.Electronics_control.refresh_board(self.LED_data, self.brightness, self.rotate_board) #print(len(self.setup_array[0][which_piece-1])) for x_1 in range(0, len(self.setup_array[0][which_piece - 1])): #check for white pieces tile_val = self.setup_array[0][which_piece - 1][x_1] row_w = tile_val // 8 col_w = tile_val % 8 if self.white_pos[row_w][col_w] == False: #print("No piece at", row_w, " ", col_w) return False #just exit the function because at least one of the pieces are not in the list for x_2 in range(0, len(self.setup_array[1][which_piece - 1])): #check for black pieces tile_val = self.setup_array[1][which_piece - 1][x_2] row_b = tile_val // 8 col_b = tile_val % 8 if self.black_pos[row_b][col_b] == False: #print("No piece at", row_b, " ", col_b) return False #just exit the function because at least one of the pieces are not in the list #only execute the following line if all of the pieces are in the correct location #which_piece = which_piece + 1 #move onto next piece #print("ALL PIECE ARE IN THE CORRECT LOCATION. LOOK AT NEXT PIECE") self.LED_data = [[(0, 0, 0) for i in range(0, 8)] for j in range(0, 8)] return True def save_game(self, filename, date): # In event header save # - tutor T/F # - four other setting options T/F # - move timer 04 # - time left white 00004 # - time left black 00010 game = chess.pgn.Game() game = chess.pgn.Game.from_board( self.board) #updates the board with the moves made settings_str = "" settings_str = settings_str + str(self.highlight_hint)[0] settings_str = settings_str + str(self.highlight_legal)[0] settings_str = settings_str + str(self.highlight_illegal)[0] settings_str = settings_str + str(self.highlight_king)[0] settings_str = settings_str + str(self.highlight_last)[0] game.headers["Event"] = settings_str game.headers["Date"] = date game.headers["White"] = self.chess_w game.headers["Black"] = self.chess_b game.headers["Round"] = self.board.turn game.headers["Result"] = self.board.result() #saves it to the pgn new_pgn = open( "./saves/{}.pgn".format(filename), "w", encoding="utf-8") #Open/Save it to a file called test.pgn exporter = chess.pgn.FileExporter(new_pgn) game.accept(exporter) def load_game(self, filename): self.board = chess.Board() pgn = open("./saves/{}.pgn".format(filename)) loaded_game = chess.pgn.read_game(pgn) self.chess_w = loaded_game.headers["White"] self.chess_b = loaded_game.headers["Black"] self.result = loaded_game.headers["Result"] settings_str = loaded_game.headers["Event"] self.highlight_hint = settings_str[0] == 'T' self.highlight_legal = settings_str[1] == 'T' and self.highlight_hint self.highlight_illegal = settings_str[2] == 'T' and self.highlight_hint self.highlight_king = settings_str[3] == 'T' and self.highlight_hint self.highlight_last = settings_str[4] == 'T' and self.highlight_hint for move in loaded_game.mainline_moves(): self.board.push(move) self.start_list_LED_array() if self.chess_w[0:2] == "AI": self.cpu_AI.set_level(int(self.chess_w[-1])) self.cpu_AI.set_color(True) if self.board.turn == chess.WHITE: self.ai_make_move() elif self.chess_b[0:2] == "AI": self.cpu_AI.set_level(int(self.chess_b[-1])) self.cpu_AI.set_color(False) if self.board.turn == chess.BLACK: self.ai_make_move() if self.chess_w == "P1": self.rotate_board = 90 else: self.rotate_board = 270 def hint(self): self.hint_highlight = [] move = self.hint_AI.hint(self.board) row = move.to_square // 8 col = move.to_square % 8 self.hint_highlight.append([row, col]) row = move.from_square // 8 col = move.from_square % 8 self.hint_highlight.append([row, col]) def clear_board_LED(self): self.LED_data = [ [(0, 0, 0) for i in range(0, 8)] for j in range(0, 8) ] #2D array of tuples indicating the color of each square. Initialize with all LEDs OFF #repopulate past move and check if applicable def checking_king_check(self): self.king_check_highlight = [] [self.king_in_check, attackers_array] = self.Move_validation.is_check(self.board) if (self.king_in_check == True): #print("A KING IS IN CHECK") #highlight king in red self.king_pos = self.board.king(self.board.turn) row = self.king_pos // 8 col = self.king_pos % 8 self.king_check_highlight.append([row, col]) #highlight attackers in red for x in range(0, len(attackers_array)): row = attackers_array[x] // 8 col = attackers_array[x] % 8 self.king_check_highlight.append([row, col]) #adds highlighting squares to array if a piece is lifted def piece_lifted(self): #highlight square that's lifted (blue) row = self.selected_piece // 8 col = self.selected_piece % 8 self.legal_move_highlight.append( [row, col, self.color_dict["white"]] ) #Add the lifted piece's location to the lifted piece's LED highlighting #show legal moves (green) self.array_legal_moves = self.Move_validation.piece_legal_moves( self.board, self.selected_piece) #print("ARRAY_LEGAL_MOVES is ", self.array_legal_moves) #convert UCI to square number for x in range(0, len(self.array_legal_moves)): row = self.array_legal_moves[x].to_square // 8 col = self.array_legal_moves[x].to_square % 8 self.legal_move_highlight.append( [row, col, self.color_dict["green"]]) #pushes the move when the turn has ended #NEED TO CHANGE THIS CODE FOR THE NEW REVISION. IT WILL ALSO ASSIGN THE HIGHLIGHTING IN HERE. def end_turn_move(self): self.ai_on = self.chess_w[0:2] == "AI" or self.chess_b[0:2] == "AI" self.ai_turn = (self.chess_w[0:2] == "AI" and self.board.turn) or (self.chess_b[0:2] == "AI" and not self.board.turn) end_turn_ai = self.ai_on and self.ai_turn and self.move_buffer == self.ai_move end_turn_ai = (self.ai_on and not self.ai_turn and self.move_buffer != None) or end_turn_ai end_turn_2p = not self.ai_on and self.move_buffer != None if end_turn_2p or end_turn_ai: self.board.push(self.move_buffer) self.clear_board_LED() #Move was made. Highlight prev_player_move cyan or other color (from and to square) self.last_move_highlight = [ ] #Reset it before appending new last move row_1 = self.move_buffer.from_square // 8 col_1 = self.move_buffer.from_square % 8 self.last_move_highlight.append([row_1, col_1]) row_2 = self.move_buffer.to_square // 8 col_2 = self.move_buffer.to_square % 8 self.last_move_highlight.append([row_2, col_2]) #Reset variables for the next player self.move_made = None #clear because it's a new player's turn self.selected_piece = None self.array_legal_moves = [ ] #new player turn so no move should be listed self.illegal_array = [] #should be cleared by the end of the turn self.illegal_move = False #should already be false. NOT SURE IF THIS IS NEEDED TO BE STATED HERE #self.castling_state = False #Tracks if castling happened #self.castling_state_array = [False, False, False, False] # loc 1 - w_kingside, loc 2 - w_queenside, loc 3 - b_kingside, loc 4 - b_queenside self.checking_king_check() self.hint_highlight = [] if self.ai_on and not self.ai_turn: self.ai_make_move() print(self.board) print("") if self.board.turn: return ["White", None] else: return ["Black", None] return ["illegal", self.warning_message] def ai_make_move(self): self.ai_move_highlight = [] self.ai_move = self.cpu_AI.AI_move(self.board) row = self.ai_move.to_square // 8 col = self.ai_move.to_square % 8 self.ai_move_highlight.append([row, col]) row = self.ai_move.from_square // 8 col = self.ai_move.from_square % 8 self.ai_move_highlight.append([row, col]) print("ai move: {}".format(self.ai_move)) def assign_highlight(self): self.clear_board_LED() self.ai_turn = (self.chess_w[0:2] == "AI" and self.board.turn) or (self.chess_b[0:2] == "AI" and not self.board.turn) #Last Move if self.highlight_last: for x in range(0, len( self.last_move_highlight)): #Only 2 squares are higlighted self.LED_data[self.last_move_highlight[x][0]][ self.last_move_highlight[x][1]] = self.color_dict["blue"] #King Check if self.highlight_king: for x in range(0, len(self.king_check_highlight)): self.LED_data[self.king_check_highlight[x][0]][ self.king_check_highlight[x][1]] = self.color_dict["red"] #Castle Check # Highlight the rook that needs to move for x in range(0, len(self.castle_move_highlight)): self.LED_data[self.castle_move_highlight[x][0]][ self.castle_move_highlight[x][1]] = self.color_dict["magenta"] #Legal Moves if self.highlight_legal and not self.ai_turn: for x in range(0, len(self.legal_move_highlight)): row = self.legal_move_highlight[x][0] col = self.legal_move_highlight[x][1] self.LED_data[row][col] = self.legal_move_highlight[x][2] #Hint if self.highlight_hint and not self.ai_turn: for x in range(0, len(self.hint_highlight)): row = self.hint_highlight[x][0] col = self.hint_highlight[x][1] self.LED_data[row][col] = self.color_dict["magenta"] #AI Move if self.ai_turn: for x in range(0, len(self.ai_move_highlight)): row = self.ai_move_highlight[x][0] col = self.ai_move_highlight[x][1] self.LED_data[row][col] = self.color_dict["magenta"] #Illegal Move (Technically this is already processed) if self.highlight_illegal: for x in range(0, len(self.illegal_array)): self.LED_data[self.illegal_array[x][0]][ self.illegal_array[x][1]] = self.color_dict["yellow"] #Wrong move made if self.highlight_wrong_move: for x in range(0, len(self.wrong_move_array)): tile_val = self.wrong_move_array[x] row = tile_val // 8 col = tile_val % 8 my_color = self.color_dict["yellow"] if self.board.turn and not self.black_pos[row][ col]: # whites turn self.LED_data[row][col] = my_color elif not self.board.turn and not self.white_pos[row][ col]: # blacks turn self.LED_data[row][col] = my_color [self.white_pos, self.black_pos ] = self.Electronics_control.refresh_board(self.LED_data, self.brightness, self.rotate_board) def wrong_color_moved(self): not_turn = not self.board.turn self.wrong_move_array = [] self.wrong_move_array.extend( list(self.board.pieces(chess.PAWN, not_turn))) self.wrong_move_array.extend( list(self.board.pieces(chess.KNIGHT, not_turn))) self.wrong_move_array.extend( list(self.board.pieces(chess.BISHOP, not_turn))) self.wrong_move_array.extend( list(self.board.pieces(chess.ROOK, not_turn))) self.wrong_move_array.extend( list(self.board.pieces(chess.QUEEN, not_turn))) self.wrong_move_array.extend( list(self.board.pieces(chess.KING, not_turn))) def live_move_highlight(self): [self.selected_piece, self.move_made, self.castle_list ] = self.Move_validation.determine_move_made(self.board, self.white_pos, self.black_pos) #print("Selected piece/square: ",self.selected_piece) #print("Move made: ", self.move_made) #print("castle_list: ", self.castle_list) #if no move was made (just lifted a piece or nothing happens) then move_made = None. Will have to make a condition for that so that nothing on the board is highlighted unless if a piece is lifted #self.castle_state_check() #checks if there's castling in progress self.legal_move_highlight = [ ] #reset the array to add new legal moves into legal_move_highlight array self.illegal_array = [] self.wrong_color_moved() self.remove_rook_highlight() # remove rook highlight from castling if ( self.selected_piece != None and self.castle_list == None ): #piece is lifted (When swapping or killing a piece no square will be highlighted; the physical process of replacing and removing a piece on the board) self.piece_lifted() #logic to load legal_move highlight squares if (self.move_made != None): #a move was made #and self.castle_list == None): #a move was made self.illegal_move = self.Move_validation.is_legal_move( self.board, self.move_made) #check if move was illegal if (self.illegal_move == False or (self.ai_on and self.ai_turn and self.move_made != self.ai_move)): #It is an illegal move self.warning_message = "Illegal Move Made" self.move_buffer = None #Do not push the move (don't update the board with the illegal move) #highlight yellow (from and to squares) row_1 = self.move_made.from_square // 8 #assuming that it is actually from UCI and not just a regular string to make it have the appearance of UCI. If just a regular string with the look of UCI, then perform the code found at (***!!!) col_1 = self.move_made.from_square % 8 self.illegal_array.append([ row_1, col_1 ]) #add the from and to squares to the illegal move array row_2 = self.move_made.to_square // 8 col_2 = self.move_made.to_square % 8 self.illegal_array.append([row_2, col_2]) #touchscreen will need to make an if condition that stops other moves/highlighting/reading if an illegal move was made #if (self.illegal_move != False): #no illegal move was made #call game reading funtions else: #legal move was made (King check condition done elsewhere) # castling is in progress. king has moved but rook has not moved yet. # don't add the move to the buffer yet. if not (self.castle_highlight_check()): self.move_buffer = self.move_made #save the move for the move buffer elif self.castle_list != None: # castling happened (both a king and rook have been moved) print("Castle has happened already: ", self.castle_list) # castle_list can be 'e1c1', 'e1g1', 'e8c8', 'e8g8' # push the castle_list to the move_buffer self.move_buffer = self.castle_list self.castle_move_highlight = [ ] # castling is now DONE, remove rook highlight else: # if no move was made self.move_buffer = None self.warning_message = "No Move Made" def check_end_game(self): return self.board.is_game_over() # highlights the position that the rook should move to to complete the castle # returns true if castling in progress (king has moved but not rook) # returns false if castling not in progress def castle_highlight_check(self): self.board.push( self.move_made) # have to push move to check the king location # kind of a hack if (self.board.turn == chess.BLACK): print("white's turn") if (self.move_made.uci() == "e1g1" and self.board.piece_at(chess.G1).symbol() == "K"): print("white kingside castle") self.castle_move_highlight.append([0, 7]) self.castle_move_highlight.append([0, 5]) self.board.pop() return True elif (self.move_made.uci() == "e1c1" and self.board.piece_at(chess.C1).symbol() == "K"): print("white queenside castle") self.castle_move_highlight.append([0, 0]) self.castle_move_highlight.append([0, 3]) self.board.pop() return True else: print("no white castle") self.board.pop() return False # # elif (self.board.turn == chess.WHITE): print("black's turn") if (self.move_made.uci() == "e8g8" and self.board.piece_at(chess.G8).symbol() == "k"): print("black kingside castle") self.castle_move_highlight.append([7, 7]) self.castle_move_highlight.append([7, 5]) self.board.pop() return True elif (self.move_made.uci() == "e8c8" and self.board.piece_at(chess.C8).symbol() == "k"): print("black queenside castle") self.castle_move_highlight.append([7, 0]) self.castle_move_highlight.append([7, 3]) self.board.pop() return True else: print("no black castle") self.board.pop() return False # # def remove_rook_highlight(self): # this SHOULD only remove the rook highlighting if you undo the king's move # right now this removes highlight if you lift rook (not intentional) # TODO: fix this if (self.move_made == None): self.castle_move_highlight = [] # this section does not work because move_buffer is none if castling is not complete yet # if only moved the king, the move_buffer is empty ''' if (self.move_buffer != None): self.board.push(self.move_made) no_longer_w_king_castle = (self.move_buffer.uci() == "e1g1" and self.board.piece_at(chess.G1).symbol() != "K") no_longer_w_queen_castle = (self.move_buffer.uci() == "e1c1" and self.board.piece_at(chess.C1).symbol() != "K") no_longer_b_king_castle = (self.move_buffer.uci() == "e8g8" and self.board.piece_at(chess.G8).symbol() != "k") no_longer_b_queen_castle = (self.move_buffer.uci() == "e8c8" and self.board.piece_at(chess.C8).symbol() != "k") if (no_longer_w_king_castle) or (no_longer_w_queen_castle): #remove rook highlight self.castle_move_highlight = [] if (no_longer_b_king_castle) or (no_longer_b_queen_castle): #remove rook highlight self.castle_move_highlight = [] self.board.pop() ''' def reset_board(self): self.board = None self.board = chess.Board() def toggle_info(self): self.highlight_wrong_move = not self.highlight_wrong_move
class Game: def __init__(self): self.deck = Deck() self.player_one = Player(self.deck.deal_hand()) #self.player_two = Player(self.deck.deal_hand()) self.ai = AI(self.deck.deal_hand()) self.trump_suit = self.deck.get_trump_suit() #print(self.trump_suit) self.player_one_on_hand = True self.runtime() def turn(self): #print(f"{self.player_one.get_hand()} {self.ai.get_hand()}") player_one_choice = 0 player_two_choice = self.ai.select(self.player_one.get_card_from_hand(player_one_choice), self.trump_suit) #player_two_choice = random.randint(0, self.player_two.get_hand_size() - 1) card1 = self.player_one.get_card_from_hand(player_one_choice) card2 = self.ai.get_card_from_hand(player_two_choice) if self.player_one_on_hand: self.grab(card1, card2) else: self.grab(card2, card1) self.draw(card1, card2) def draw(self, card1, card2): self.player_one.remove_card_from_hand(card1) self.ai.remove_card_from_hand(card2) if self.deck.get_deck_size(): if self.player_one_on_hand: self.player_one.add_to_hand(self.deck.draw()) self.ai.add_to_hand(self.deck.draw()) else: self.ai.add_to_hand(self.deck.draw()) self.player_one.add_to_hand(self.deck.draw()) def grab(self, p1_card, p2_card): cards = Cards() if cards.compare_cards(p1_card, p2_card, self.trump_suit): if not self.player_one_on_hand: self.player_one_on_hand = False self.ai.add_to_pile(p1_card, p2_card) else: self.player_one_on_hand = True self.player_one.add_to_pile(p1_card, p2_card) else: if self.player_one_on_hand: self.player_one_on_hand = False self.ai.add_to_pile(p1_card, p2_card) else: self.player_one_on_hand = True self.player_one.add_to_pile(p1_card, p2_card) def runtime(self): while self.player_one.get_hand(): self.turn() # print(self.player_one.get_pile()) # print(self.ai.get_pile()) # print(self.player_one.get_points()) # print(self.ai.get_points()) def win(self): if self.player_one.get_points() > self.ai.get_points(): return True return False
def addBot(name, skill, index): global botDict addPlayer(name) botDict[name] = AI(name, index, skill)
class GameControl: def __init__(self, player_color, is_computer_opponent): self.turn = player_color self.winner = None self.board = None self.board_draw = None self.held_piece = None self.ai_control = None if is_computer_opponent: self.ai_control = AI("B") if player_color == "W" else AI("W") self.setup() def get_turn(self): return self.turn def get_winner(self): return self.winner def setup(self): # Initial setup pieces = [] for opponent_piece in range(0, 12): pieces.append(Piece(str(opponent_piece) + 'BN')) for player_piece in range(20, 32): pieces.append(Piece(str(player_piece) + 'WN')) self.board = Board(pieces, self.turn) self.board_draw = BoardGUI(self.board) pass def draw_screen(self, display_surface): self.board_draw.draw_board(display_surface) self.board_draw.draw_pieces(display_surface) if self.held_piece is not None: self.held_piece.draw_piece(display_surface) def hold_piece(self, mouse_pos): piece_clicked = self.board_draw.get_piece_on_mouse(mouse_pos) board_pieces = self.board.get_pieces() has_jump_restraint = False # True if any piece can jump in one of its moves, forcing the player to jump if piece_clicked is None: return if piece_clicked["piece"]["color"] != self.turn: return # Determines if player has a jump restraint for piece in board_pieces: for move in piece.get_moves(self.board): if move["eats_piece"]: if piece.get_color() == piece_clicked["piece"]["color"]: has_jump_restraint = True else: continue break piece_moves = board_pieces[piece_clicked["index"]].get_moves( self.board) if has_jump_restraint: piece_moves = list( filter(lambda move: move["eats_piece"] == True, piece_moves)) move_marks = [] # Gets possible moving positions and tells BoardGUI to draw them for possible_move in piece_moves: row = self.board.get_row_number(int(possible_move["position"])) column = self.board.get_col_number(int(possible_move["position"])) move_marks.append((row, column)) self.board_draw.set_move_marks(move_marks) self.board_draw.hide_piece(piece_clicked["index"]) self.set_held_piece(piece_clicked["index"], board_pieces[piece_clicked["index"]], mouse_pos) def release_piece(self): if self.held_piece is None: return position_released = self.held_piece.check_collision( self.board_draw.get_move_marks()) moved_index = self.board_draw.show_piece() piece_moved = self.board.get_piece_by_index(moved_index) # Only moves the piece if dropped in a proper move mark if position_released is not None: self.board.move_piece( moved_index, self.board_draw.get_position_by_rect(position_released)) self.board_draw.set_pieces( self.board_draw.get_piece_properties(self.board)) self.winner = self.board.get_winner() # Check if player can eat another piece, granting an extra turn. jump_moves = list( filter(lambda move: move["eats_piece"] == True, piece_moved.get_moves(self.board))) if len(jump_moves) == 0 or piece_moved.get_has_eaten() == False: self.turn = "B" if self.turn == "W" else "W" self.held_piece = None self.board_draw.set_move_marks([]) def set_held_piece(self, index, piece, mouse_pos): # Creates a HeldPiece object to follow the mouse surface = self.board_draw.get_surface(piece) offset = get_surface_mouse_offset( self.board_draw.get_piece_by_index(index)["rect"], mouse_pos) self.held_piece = HeldPiece(surface, offset) def move_ai(self): # Gets best move from an AI instance and moves it. if self.turn == "W": return optimal_move = self.ai_control.get_move(self.board) index_moved = -1 piece_moved = None for index, piece in enumerate(self.board.get_pieces()): if piece.get_position() == optimal_move["position_from"]: index_moved = index piece_moved = piece break else: raise RuntimeError( "AI was supposed to return a move from an existing piece but found none." ) self.board.move_piece(index_moved, int(optimal_move["position_to"])) self.board_draw.set_pieces( self.board_draw.get_piece_properties(self.board)) self.winner = self.board.get_winner() # Check if AI can eat another piece, granting an extra turn. jump_moves = list( filter(lambda move: move["eats_piece"] == True, piece_moved.get_moves(self.board))) if len(jump_moves) == 0 or piece_moved.get_has_eaten() == False: self.turn = "B" if self.turn == "W" else "W"