def start(self): print "Welcome! Do you want to go first? [y/n]" if raw_input() == "n": isValid = True # Hack! self.currentPlayer = self.player2 # aiOn segir til um hvort spilari spilar mot mennskun spilara eda tolvu aiOn = True if aiOn: comPlayer = ai() difficulty = 2 # 2 tölva fljót að hugsa, gæti gert klaufavillur, 3 tölva lengi að hugsa. # Medan enginn hefur unnid while self.winner == 0: # Teikna bord self.gameBoard.draw() if aiOn: if self.currentPlayer > 0: isValid = self.action.makemove(self.gameBoard, self.currentPlayer) print "== Human plays ==" elif self.currentPlayer < 0: print "== Computer plays ==" self.gameBoard.insert(self.currentPlayer,comPlayer.getComputerMove(self.gameBoard,self.currentPlayer,difficulty)) elif not aiOn: # 2 mennskir spilarar isValid = self.action.makemove(self.gameBoard, self.currentPlayer) # Ath hvort spilari hafi unnid self.winner = self.gameBoard.isWinner(self.currentPlayer) # Skiptum! if isValid == True: self.currentPlayer *= -1 self.gameBoard.draw() print "And the winner is:" print self.winner
def set_up_ai(ainum): AI = ai.ai(ainum) aipersonality = input("Would you like ai player " + str(ainum) + " to be (1)Agressive, (2)Defensive, or (3)Balanced? (1,2,3) \n") while aipersonality != 1 and aipersonality != 2 and aipersonality != 3: print "ERROR: not a valid input" aipersonality = input("Would you like ai player" + str(ainum) + " to be (1)Agressive, (2)Defensive, or (3)Balanced? (1,2,3) \n") if aipersonality == 1: AI.agressive_personality() elif aipersonality == 2: AI.defensive_personality() aidifficulty = input("Set the difficulty of ai player " + str(ainum) + " in range(1-6). Note, higher difficulty = more processing time \n") while 1 > aidifficulty or 6 < aidifficulty: print "ERROR: not a valid input" aidifficulty = input("Set the difficulty of ai player " + str(ainum) + " in range(1-6). Note, higher difficulty = more processing time \n") AI.set_MAX_DEPTH(aidifficulty) aieasymode = input("Easy mode for ai player " + str(ainum) + "? Answer 0 for no, 1 for yes. This setting causes the AI to use a simpler heuristic. \n") while aieasymode != 0 and aieasymode != 1: print "ERROR: not a valid input" aieasymode = input("Easy mode for ai player " + str(ainum) + "? Answer 0 for no, 1 for yes. This setting causes the AI to use a simpler heuristic. \n") if aieasymode == 1: AI.easy_mode() return AI
def __init__(self, mapName): self.mapBoard = self.generateBoard(mapName) self.mapCharacters = self.generateCharacters(mapName) self.height = len(self.mapBoard) self.width = len(self.mapBoard[0]) self.gameboard = gameBoard(self.mapBoard, self.mapCharacters, self.height, self.width, self.mapLords) self.weights = [] self.ai = ai(self.gameboard, self.height, self.width, self.weights)
def onexecute(self): # make an instance of all the functions # common.c = common() common.inventorytotal = playertotals() common.mp = morepanel() common.e = event() common.ai = ai() common.ip = infopanel() common.en = entity() common.cv = civilization() common.g = graphics() common.sounds = sounds.sounds() # initialize pygame pygame.init() # Read from config file opt = open(os.path.join(common.rootdir, "options.json"), 'r') y = json.loads(opt.read()) common.srclocation = os.path.join("texturepacks", y['texturepack']) common.enablesky = bool(y['sky']) opt.close() # load the window common.screen = pygame.display.set_mode( (common.width, common.height), RESIZABLE) pygame.display.set_caption(common.name+" v."+str(common.version)); common.running = True common.screen.fill((255,255,255)) # load all images/resources common.g.loadall() pygame.display.set_icon(civilization.buildingtextures[0]) # do cursors common.hand = pygame.cursors.compile(hand_str, 'x', '.', "o") common.grabber = pygame.cursors.compile(grabber_str, 'x', '.', "o") #Starts music common.sounds.playmusic("Into_the_Unknown") self.fromlauncher()
def spawn(self, subject, *args): '''spawn an entity ''' if subject == 'mob': print 'mob made' shot = shooter(1, 20) AI = ai.ai(stats.DUMB) W = stats.WIDTH * random.random() H = stats.HEIGHT * random.random() pathname = os.path.abspath(os.path.curdir) pathname += '/art/man/' mob = anything((W, H),'Bob',pathname, shooter=shot, ai= AI) mob.shooter.getTarget() return mob else : print 'spawn nothing'
def start(self): comPlayer1 = ai() comPlayer2 = robbiai() difficulty = 2 # 2 tölva fljót að hugsa, gæti gert klaufavillur, 3 tölva lengi að hugsa. print "Welcome! Do you want Cthulhu to go first? [y/n]" if raw_input() == "n": self.currentPlayer = self.player2 # Medan enginn hefur unnid while self.winner == 0: # Teikna bord self.gameBoard.draw() if self.currentPlayer > 0: #player 1 self.gameBoard.insert(self.currentPlayer,comPlayer1.getComputerMove(self.gameBoard,self.currentPlayer,difficulty)) print "===================" print " Cthulhu " print "===================" elif self.currentPlayer < 0 : #player 2 self.gameBoard.insert(self.currentPlayer,comPlayer2.computerPlayer(self.gameBoard,self.currentPlayer,difficulty)) print "===================" print " Spaghetti Monster " print "===================" self.winner = self.gameBoard.isWinner(self.currentPlayer) # Skiptum! self.currentPlayer *= -1 self.gameBoard.draw() print "AND THE WINNER IS!!!" if self.winner > 0: print "===================" print " Cthulhu " print "===================" elif self.winner < 0: print "===================" print " Spaghetti Monster " print "===================" print "WooooHoooo - The crowd goes Wild"
from ai import ai from client import client from sys import argv import time import threading args = argv args0 = ['play.py', 'http://localhost:8080/', 'secret0', 'yeet0'] args1 = ['play.py', 'http://localhost:8080/', 'secret1', 'yeet1'] args2 = ['play.py', 'http://localhost:8080/', 'secret2', 'yeet2'] args3 = ['play.py', 'http://localhost:8080/', 'secret3', 'yeet3'] time_client = client(args0[1], args0[2], args0[3]) player0 = ai(client(args0[1], args0[2], args0[3])) player1 = ai(client(args1[1], args1[2], args1[3])) player2 = ai(client(args2[1], args2[2], args2[3])) player3 = ai(client(args3[1], args3[2], args3[3])) def waiting(): while True: i = 0 running = True while running: player = time_client.get_turn() print('waiting on %i for %i secs' % (player, i)) time.sleep(1) if player != time_client.get_turn(): running = False
carrom_.board.draw_striker_arrow_pointer(win_, carrom_.striker, max_speed) pygame.display.update() while not carrom.game_over: """ Initialize the striker position """ carrom.striker.position = carrom.board.get_striker_position( carrom.player_turn) if players[carrom.player_turn] == "ai": """ Just refresh the board """ carrom.draw(win) carrom.board.show_notification(win, "AI thinking") pygame.display.flip() handle_events() """ let the ai make the decision for the striker """ ai(carrom, max_angle, max_speed, decelerate, e, dt) """ just indicate to the user, the ai's decision """ carrom.draw(win) carrom.board.draw_striker_arrow_pointer(win, carrom.striker, max_speed) carrom.board.show_notification(win, "AI decided") pygame.display.flip() handle_events() """wait for some time """ pygame.time.delay(100) elif players[carrom.player_turn] == "random": """ Just refresh the board """ carrom.draw(win) carrom.board.show_notification(win, "Random AI thinking") pygame.display.flip() handle_events()
def ui(): ai()
def game(music_play): import gameOver pygame.init() pygame.display.set_caption('Ultimate Snake') screen = pygame.display.set_mode(size, pygame.FULLSCREEN) game = True while game == True: #plays the music if its not off if music_play != "off": music.play(-1) #defines the bgColor, color and the speed of the snake bgColor = 0, 0, 0 color = 255, 255, 255 snake2 = aiClasses.Snake(screen, 320, 280, "images/green.bmp") snake = aiClasses.Snake(screen, 320, 240, "images/part.bmp") score2 = aiClasses.Score(screen, True) score = aiClasses.Score(screen) food = aiClasses.Food(screen, snake, snake2) food2 = aiClasses.Food(screen, snake, snake2, True) snk2Dead = False font = pygame.font.SysFont("Helvetica", 25) font2 = pygame.font.SysFont("Helvetica", 40) came_from = "R" came_from2 = "" pCount = 0 clock.tick_busy_loop() timer = 180000 #sets the time of the game to 3min #game will end in 3min pause = 0 while True: clock.tick_busy_loop() pos_xy = [] #defines a list with x,y position of each part #of the snake #appends the positions to pos_xy for each in snake2.parts[3:]: pos_xy.append((each.position.x, each.position.y)) #finds the difference in positions between the AI snake and #and the food1 and food2 position foodPos = math.fabs(snake2.head.position.x - food.position[0]) food2Pos = math.fabs(snake2.head.position.x - food2.position[0]) #decides which food is closer and goes for that food if foodPos >= food2Pos: goFood = 2 else: goFood = 1 if snk2Dead == False: #tells the AI to move, calls the ai function ai.py if goFood == 2: came_from, came_from2 = ai.ai(food2, snake2, came_from, came_from2, pos_xy) elif goFood == 1: came_from, came_from2 = ai.ai(food, snake2, came_from, came_from2, pos_xy) goFood = 0 #if the escape key is pressed then the game will quit for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() #press 'p' to pause and unpause the game #it goes into a infinite loop when "p" is pressed if event.type == KEYDOWN: if event.key == K_p: pygame.mixer.pause() pCount = 1 pauseClock.tick() #ticks the clock for the pauseClock while 1: event = pygame.event.wait() if event.type == KEYDOWN: if event.key == K_p: pygame.mixer.unpause() break if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.key == K_ESCAPE: pygame.quit() sys.exit() pauseClock.tick() #ticks it again # use the arrow keys to move the snake #THIS IS FOR PLAYER 1 if event.type == KEYDOWN: if event.key == K_RIGHT: snake.change_direction(right) elif event.key == K_LEFT: snake.change_direction(left) elif event.key == K_UP: snake.change_direction(up) elif event.key == K_DOWN: snake.change_direction(down) # change the bgColor to rainbow colors while score.score >= 1000 or score2.score >= 1000: int1 = random.randrange(0, 255) int2 = random.randrange(0, 255) int3 = random.randrange(0, 255) bgColor = int1, int2, int3 break # if the player dies if not snake.move(food, food2, score): game = False #game ends and goes to the gameOver screen break #breaks the game loop # if the ai dies if not snake2.move(food, food2, score2): snk2Dead = True screen.fill(bgColor) #fills the background pause = pauseClock.get_time() #finds how long the game #was paused for if pCount == 1: #works everytime the game is paused timer = (timer - clock.get_time()) + pause pCount = 0 else: timer -= clock.get_time() if timer <= 0: #what happens when the time runs out pygame.time.delay(1000) game = False break if snk2Dead == False: #when the AI is not dead snake2.update() #updates the AI's snake food2.update() #updates the food for the AI snake.update() #updates the snake for the player food.update() #updates the food for the player score2.update(color) #updates the scores score.update(color) #BLITS THE SPEED STATUS OF THE SNAKES if food.delay == 80: speedPic = pygame.image.load( 'images/normalSpeed.bmp').convert() screen.blit(speedPic, (550, 3)) elif food.delay == 40: speedPic = pygame.image.load('images/fastSpeed.bmp').convert() screen.blit(speedPic, (550, 5)) elif food.delay == 120: speedPic = pygame.image.load('images/slowSpeed.bmp').convert() screen.blit(speedPic, (550, 5)) #draws a line that seperates the statusbar from the game pygame.draw.line(screen, color, (0, 40), (1000, 40)) #defines the time variables t = (timer / 1000) / 60.0 timeText = font.render("Time:", True, color) time = font.render(str("%.2f" % t), True, color) #blits the time text and the time screen.blit(timeText, (250, 10)) screen.blit(time, (310, 10)) pygame.display.update() #updates the display pygame.time.delay(food.delay) #changes the speed of the snakes #IF THE GAME HAS ENDED while game == False: music.stop() #shows the gameOver screen gameOver.scoresListMulti(font2, score.score, score2.score, music_play, True) pygame.display.update()
from ai import ai n, m = 10, 10 f = open("test.txt", "r") t = [[0 for x in range(n)] for y in range(m)] for i in range(1, n): for j in range(1, m): t[i][j] = int(f.readline()) f.close() e = 1 for i in range(1, n): for j in range(1, m): #print type(t[i][j]) #print type(ai(i, j)) t[i][j] = ai(i * 10, j * 2) print str(e) + ' = ' + str(t[i][j]) e += 1 f = open("test.txt", "w") f.write(n) f.write(m) for i in range(1, n): for j in range(1, m): f.write(t[i][j]) f.close()
if __name__=='__main__': # Set this to 0 for ai vs ai games human = 1 ai2 = set_up_ai(human) #Tracks if any player has won the game winner = False currentplayer = 1 #initalize a player 1 ai if no human if human == 0: ai1 = ai.ai(1) #ai1.set_SELF_SCORE(10) #initalize player 2 ai #ai2 = ai.ai(2) #ai2.set_OPPONENT_SCORE(10) #while no winner and there are still moves available while winner == False and len(connect4.open_columns()) > 0: connect4.print_board() #Human move
test.py 状态评分函数 ai.py 算法主程序 gui.py 可视化(使用json文件中介) gif/xx.gif 图像文件(用于可视化) 2048.pptx 课堂展示ppt ''' start_time = datetime.datetime.now() lse = [] l2 = [] a = 0 times = 100 # 运行的次数 for i in range(times): me, se, ae, meo = ai.ai() lse.append(se) l2.append(se**2) a += ae with open('m.json', 'w', encoding="utf8") as fi: json.dump(meo, fi, ensure_ascii=False, indent=4) print( lse, sum(lse) / len(lse), max(lse), a, ) e = sum(lse) / len(lse) for i in lse: print(i, end='\t') if (lse.index(i) + 1) % 10 == 0:
def play_with_one(self): playerOne = human.human() playerOneName = playerOne.give_name("PlayerOne") playerTwo = ai.ai() playerTwoName = playerTwo.generate_name() self.keep_score(playerOneName,playerTwoName,playerOne,playerTwo)
from ai import ai server_url = 'http://codekata-snake.herokuapp.com/' key = 'Reir1eez' snake = ai(key, server_url) snake.run()
import numpy as np from ai import ai from TicTacToe import TicTacToe import time uses = np.load('uses.npy').flatten() wins = np.load('wins.npy').flatten() AI_x = ai(uses, wins, 0) AI_o = ai(uses, wins, 0) # game.run() for i in range(10): state = [0] * 9 t = 0 game = TicTacToe() while game.end_code < 0: if (t+1)%2 == 0: move = AI_x.get_action(state, t) state[t] = move game.fill_pos(move) t += 1 game.update() game.progress = False if game.end_code <0: while game.progress == False: game.update() time.sleep(0.0167) t += 1
def data(): query = request.args.get('q') id = request.args.get('id') resp ={} #alchemyapi resp['alchemy_result'] = categorize.categorize(query) if(int(id)>0): if(resp['alchemy_result']): mylist = [query,resp['alchemy_result']] with open(directory + id +'.csv','a') as myfile: wr = csv.writer(myfile,lineterminator='\n') wr.writerow(mylist) resp['recommend'] = recDict(id) start = time.time() correction = Bing.spellingsuggestions(query) if correction: resp['correction'] = correction query = correction else: resp['correction'] = None ''' p1 = Process(target = bing(query)) p1.start() p2 = Process(target = wolf.wolfaramalpha(query)) p2.start() #p1.join() #p2.join() ''' #wolframAlpha #resp['wolf_result'] = wolf.wolfaramalpha(query) #bing #bing(query) imagekeys = ["image" , "img" , "photo" , "wallpaper"] videokeys = ["video" , "youtube" , "dailymotion"] newskeys = ["news" , "updates"] tokens = query.split() image_result = video_result = news_result = None if any(x in query for x in imagekeys): image_result = Bing.image(query,20) elif any(x in query for x in videokeys): video_result = Bing.video(query,10) elif any(x in query for x in newskeys): news_result = Bing.news(query,15) resp['web_result'] = Bing.web(query) resp['rs_result'] = Bing.relatedsearch(query) #resp['image_result'] = image_result #resp['video_result'] = video_result #resp['news_result'] = news_result #ai resp['ai_result'] = ai.ai(query) #DistMatrix #resp['distMatrix'] = distance(query) #knowledgegraph resp['kg_result'] = knowledgegraph.knowledgegraph(query) #Places #resp['places_result'] = Places.Places(query) #print (resp) json_object = json.dumps(resp) return json_object
from grab import maain from ai import ai from coundown import count count() ai(maain())
def __init__(self, user_name, server_ip, my_chessboard_type, my_font, manual_hook, usecolor, opponent, difficulty): super().__init__() self.chessboard_type = my_chessboard_type self.username = user_name self.usecolor = usecolor self.opponent = opponent # init ai name self.difficulty = difficulty self.ai = ai(self.chessboard_type, self.difficulty, self.usecolor) if self.opponent == 1: # guest self.ifAI = 0 if usecolor == 1: self.username_b = self.username self.username_w = "Guest" elif usecolor == 2: self.username_b = "Guest" self.username_w = self.username elif self.opponent == 2: # AI self.ifAI = 1 if usecolor == 1: self.username_b = self.username self.username_w = "AlphaGomoku" elif usecolor == 2: self.username_b = "AlphaGomoku" self.username_w = self.username else: self.username_b = self.username_w = None print('opponent error') #init ai turn if self.ifAI: if self.usecolor == 1: # use black self.usrturn = 1 elif self.usecolor == 2: # use white self.usrturn = 0 else: self.usrturn = 0 print('usecolor error') current_path = ':/' # sys.path[0] + '/' print(current_path) self.manual_hook = manual_hook self.server_ip = server_ip self.my_font = my_font self.chooseboard = QPixmap(current_path + 'chessboard/chessboard14.png') self.width_chessboard = 715 self.height_chessboard = 689 self.bgmusic = musicplayer() self.muted = False # 9*9 if self.chessboard_type == 9: self.chooseboard = QPixmap(current_path + 'chessboard/chessboard8.png') self.width_chessboard = 443 self.height_chessboard = 443 self.margin = 28 self.cbnum = 8 # 15*15 elif self.chessboard_type == 15: self.chooseboard = QPixmap(current_path + 'chessboard/chessboard14.png') self.width_chessboard = 715 self.height_chessboard = 689 self.margin = 20 self.cbnum = 14 else: print('error cbnum!') # other self.d_piece = 36 self.r_piece = self.d_piece / 2 self.grid_w = (self.width_chessboard - (self.margin * 2)) / self.cbnum self.grid_h = (self.height_chessboard - (self.margin * 2)) / self.cbnum self.restart()
def game(music_play): import gameOver pygame.init() pygame.display.set_caption('Ultimate Snake') screen = pygame.display.set_mode(size, pygame.FULLSCREEN) game = True while game == True: #plays the music if its not off if music_play != "off": music.play(-1) #defines the bgColor, color and the speed of the snake bgColor = 0, 0, 0 color = 255, 255, 255 snake2 = aiClasses.Snake(screen, 320, 280, "images/green.bmp") snake = aiClasses.Snake(screen, 320, 240, "images/part.bmp") score2 = aiClasses.Score(screen, True) score = aiClasses.Score(screen) food = aiClasses.Food(screen, snake, snake2) food2 = aiClasses.Food(screen, snake, snake2, True) snk2Dead = False font = pygame.font.SysFont("Helvetica", 25) font2 = pygame.font.SysFont("Helvetica", 40) came_from = "R" came_from2 = "" pCount = 0 clock.tick_busy_loop() timer = 180000 #sets the time of the game to 3min #game will end in 3min pause = 0 while True: clock.tick_busy_loop() pos_xy = [] #defines a list with x,y position of each part #of the snake #appends the positions to pos_xy for each in snake2.parts[3:]: pos_xy.append((each.position.x, each.position.y)) #finds the difference in positions between the AI snake and #and the food1 and food2 position foodPos = math.fabs(snake2.head.position.x - food.position[0]) food2Pos = math.fabs(snake2.head.position.x - food2.position[0]) #decides which food is closer and goes for that food if foodPos >= food2Pos: goFood = 2 else: goFood = 1 if snk2Dead == False: #tells the AI to move, calls the ai function ai.py if goFood == 2: came_from, came_from2= ai.ai(food2, snake2, came_from, came_from2, pos_xy) elif goFood == 1: came_from, came_from2= ai.ai(food, snake2, came_from, came_from2, pos_xy) goFood = 0 #if the escape key is pressed then the game will quit for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() sys.exit() #press 'p' to pause and unpause the game #it goes into a infinite loop when "p" is pressed if event.type == KEYDOWN: if event.key == K_p: pygame.mixer.pause() pCount = 1 pauseClock.tick() #ticks the clock for the pauseClock while 1: event = pygame.event.wait() if event.type == KEYDOWN: if event.key == K_p: pygame.mixer.unpause() break if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.key == K_ESCAPE: pygame.quit() sys.exit() pauseClock.tick() #ticks it again # use the arrow keys to move the snake #THIS IS FOR PLAYER 1 if event.type == KEYDOWN: if event.key == K_RIGHT: snake.change_direction(right) elif event.key == K_LEFT: snake.change_direction(left) elif event.key == K_UP: snake.change_direction(up) elif event.key == K_DOWN: snake.change_direction(down) # change the bgColor to rainbow colors while score.score >= 1000 or score2.score >= 1000: int1 = random.randrange(0, 255) int2 = random.randrange(0, 255) int3 = random.randrange(0, 255) bgColor = int1, int2, int3 break # if the player dies if not snake.move(food, food2, score): game = False #game ends and goes to the gameOver screen break #breaks the game loop # if the ai dies if not snake2.move(food, food2, score2): snk2Dead = True screen.fill(bgColor) #fills the background pause = pauseClock.get_time() #finds how long the game #was paused for if pCount == 1: #works everytime the game is paused timer = (timer - clock.get_time()) + pause pCount = 0 else: timer -= clock.get_time() if timer <= 0: #what happens when the time runs out pygame.time.delay(1000) game = False break if snk2Dead == False: #when the AI is not dead snake2.update() #updates the AI's snake food2.update() #updates the food for the AI snake.update() #updates the snake for the player food.update() #updates the food for the player score2.update(color) #updates the scores score.update(color) #BLITS THE SPEED STATUS OF THE SNAKES if food.delay == 80: speedPic = pygame.image.load('images/normalSpeed.bmp').convert() screen.blit(speedPic, (550, 3)) elif food.delay == 40: speedPic = pygame.image.load('images/fastSpeed.bmp').convert() screen.blit(speedPic, (550, 5)) elif food.delay == 120: speedPic = pygame.image.load('images/slowSpeed.bmp').convert() screen.blit(speedPic, (550, 5)) #draws a line that seperates the statusbar from the game pygame.draw.line(screen, color, (0, 40), (1000, 40)) #defines the time variables t = (timer/1000)/60.0 timeText = font.render("Time:", True, color) time = font.render(str("%.2f" % t), True, color) #blits the time text and the time screen.blit(timeText, (250, 10)) screen.blit(time, (310, 10)) pygame.display.update() #updates the display pygame.time.delay(food.delay) #changes the speed of the snakes #IF THE GAME HAS ENDED while game == False: music.stop() #shows the gameOver screen gameOver.scoresListMulti(font2, score.score, score2.score, music_play, True) pygame.display.update()
import ai as uct import state, numpy THINK_TIME = 3 ai = uct.ai(THINK_TIME, 'weights_1600.h5') num_games = int(input('how many games do you want to play?')) for episode in range(num_games): my_turn = int(input('which player do you want to play? (1 or -1)')) turn = 1 game_over = False game = state.state() while not game_over: if turn == my_turn: print(game.get_raw_board().swapaxes(0, 1)) move = int(input('make your move.')) else: move = ai.get_move(game) game = game.move(move) eval = ai.model.predict_on_batch( numpy.array([game.get_processed_board()])) * game.turn print('Current ANN-only evaluation = %.5f' % eval) print('Current full evaluation = %.5f' % ai.get_eval(game)) game_over = game.check_game() turn *= -1 ai.flush_data(game.get_winner()) if game.get_winner() == my_turn: print("you win!") elif game.get_winner() == -my_turn: print("you lose!")
def efirst(): s.scanner() ai.ai() pc.playerchoice()
def main(): do_you_want_to_play = True while do_you_want_to_play: clear() # Get user input print('Welcome to Noughts and Crosses.\n\ A simple text-based version of a classic.\n\n\ Can you beat the computer in a grid-based battle?\n') player_token = input('Choose a character to represent you on the board: ') ai_token = input('Choose a character to represent the computer: ') # Set up the game game = OXs(player_token.upper()[0], ai_token.upper()[0]) ai_player = ai() clear() print('\n\nHOW TO PLAY\n\ Enter a number from 1 to 9 to place your token \ on the board.') game.print_board_template() input("Press ENTER to continue...") # Let's play! print('\nLet\'s play!') sleep(1.5) clear() game.print_board() while game.game_over() == 'not_over': if game._current_marker == game._player_marker: # Begin player turn try: # TODO: Create reusable input function pos = int(input('Enter a number [1-9] to take your turn: ')) except: # TODO: Implement proper error handling print('Invalid input. Enter an inter from 1 to 9.') pos = int(input('Enter a number [1-9] to take your turn: ')) # Play turn while not game.play_turn(pos): print(f'Try again {pos} is not a valid position.') pos = int(input('Enter a number [1-9] to take your turn: ')) print(f'You chose position {pos}.') else: # Begin AI turn # clear() print('AI: It\'s my turn... ', flush=True, end='') ai_pos = ai_player.pick_a_spot(game) sleep(2) # Play AI turn game.play_turn(ai_pos) print(f'I pick position {ai_pos}') sleep(1) # Print board again print('\n') clear() game.print_board() sleep(0.5) # Game over print(game.game_over()) print('\n') input('Press ENTER to play again...')
import ai as uct import state THINK_TIME = 0.5 START_EPISODE = 1600 EPISODES = 400 SAVE_INTERVAL = 100 ai = uct.ai(THINK_TIME, 'weights_{}.h5'.format(START_EPISODE)) if START_EPISODE else uct.ai(THINK_TIME) for episode in range(START_EPISODE, START_EPISODE + EPISODES): game_over = False game = state.state() moves = [] while game_over == False: #print game.get_raw_board() move = ai.get_move(game) moves.append(move) game = game.move(move) game_over = game.check_game() print(moves) ai.flush_data(game.get_winner()) ai.train() #raw_input('press enter to continue...') if (episode+1) % SAVE_INTERVAL == 0: ai.save_weights('weights_%d.h5' % (episode+1))
def play_with_one(self): playerOne = human.human() playerOneName = playerOne.give_name("PlayerOne") playerTwo = ai.ai() playerTwoName = playerTwo.generate_name() self.keep_score(playerOneName, playerTwoName, playerOne, playerTwo)
def __init__(self, id_number, name, actor_type, owner, owner_type): self.id_number = id_number #name: name of actor #actor_type: 'dog, 'cat', etc... #owner: name of player #owner_type: 'human', 'computer' self.name = name self.actor_type = actor_type self.owner = owner self.owner_type = owner_type #position on map self.position = None #how far actor can see self.sight_distance = 5 ######### # stats # ######### self.stats = {} #4 base stats: #offense #health #whatever the f**k agility does (crit?) #defense self.stats['power'] = 1000 self.stats['agility'] = 10 self.stats['vitality'] = 10 self.stats['toughness'] = 10 self.stats['health'] = 70 self.stats['mana'] = 30 #lucky stats self.stats['evasion'] = 0 self.stats['crit'] = 0 #speed is how often actor moves self.speed = 100 self.speed_time = None self.current_health = self.stats['health'] ############ # statuses # ############ self.statuses = {} ######### # items # ######### self.inventory = [] self.gold = 0 #keep equipment simple self.equipment = {} self.equipment['left_hand'] = None self.equipment['right_hand'] = None self.equipment['head'] = None self.equipment['chest'] = None self.equipment['legs'] = None self.equipment['hands'] = None self.equipment['feet'] = None self.equipment['neck'] = None ############# # abilities # ############# self.abilities = {} for i in xrange(1, 10): self.abilities[i] = None ###### # ai # ###### #for humans, ai is only a storage structure. #if the player is berserk, it can't use complex attacks (only direct attacks). #if the player is scared, it can't attack. self.ai = ai.ai() ########################## # view/sprite attributes # ########################## self.destination = None #the path the actor will take to get to the destination self.current_path = [] #chains hold frames #an entry is like so: #image_chains[act] = [image, ] self.image_chains = None self.rect = None #inherited from Sprite, position on screen self.image = None #inherited from Sprite #holds absolute decimal location of actor self.true_decimal_rect = [0, 0] #holds decimals that pygame's rect destroys self.decimal_rect = [0, 0] #self.visible = False #this is for the view displaying something walking self.walking_speed = 200 #value in pixels self.walking_destination = (0, 0) self.walking_vector = (0, 0) #starting direction self.facing_direction = 5 #tuple of (True, False). True = positive direction, False = negative self.walking_direction_boolean = None