def testAI(): allWords = init()[1] allTries = [] counts = dict() for word in allWords: winState = 0 guess, guesses, choices = nextGuess(None) tries = 1 while not winState: # Check current guess winState, cows, bulls = returnCowsAndBulls(guess, word) if winState: allTries.append(tries) # Get next guess guess, guesses, choices = nextGuess(( cows, bulls, ), guesses, choices) tries += 1 # Oops if guess == -1: print("AI doesn't work.") counts[tries] = counts.get(tries, 0) + 1 print(counts)
def main(): framecount = 0 exit = False nodes = [] tiles = load_tiles() tile_size = 16 pygame.init() pygame.display.set_caption("Monster AI Prototype") screen = pygame.display.set_mode( (len(tiles) * tile_size, len(tiles) * tile_size)) clock = pygame.time.Clock() background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((255, 255, 255)) util.init(background, tile_size, tiles) nodes = ai.init(len(tiles)) key_player = entity.Entity(tiles, 1, 1, (255, 0, 0)) mouse_player = entity.Entity(tiles, len(tiles) - 2, 1, (0, 255, 0)) monster = entity.Entity(tiles, int(len(tiles) / 2), int(len(tiles) / 2), (0, 0, 0)) while not exit: clock.tick(60) screen.blit(background, (0, 0)) draw_tiles(background, tiles, tile_size) key_player.draw() mouse_player.draw() monster.draw() for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): return elif event.type == KEYDOWN: if event.key == K_DOWN: key_player.add_pos(0, 1) elif event.key == K_UP: key_player.add_pos(0, -1) elif event.key == K_LEFT: key_player.add_pos(-1, 0) elif event.key == K_RIGHT: key_player.add_pos(1, 0) mx, my = pygame.mouse.get_pos() mouse_player.set_pos(mx / tile_size, my / tile_size) ai_move = ai.ai_step(framecount, nodes, monster, (mouse_player, )) framecount += 1 pygame.display.flip()
def init(showFrameRate = False, daemon = False): "Initializes various global components, like audio, lighting, and the clock. Should be called once at the beginning of the program." global renderLit global clock global renderObjects global renderEnvironment global log global reflectionBuffer global reflectionCamera global reflectionRenderTexture global defaultFov global enableShaders global enablePostProcessing global enableDistortionEffects global filters global isDaemon global mf global maps mf = None if not vfs.isDirectory("maps"): mf = Multifile() mf.openRead(ExecutionEnvironment.getEnvironmentVariable("PKG_ROOT") + "/pkg.mf") isDaemon = daemon if not daemon: base.setBackgroundColor(2.0/255.0, 28.0/255.0, 53.0/255.0) log = Logger() sys.excepthook = exceptHook clock = Clock() base.disableMouse() # Disable default mouse camera control if not daemon: base.camNode.setCameraMask(BitMask32.bit(1)) base.camLens.setFov(defaultFov) renderLit = render.attachNewNode("renderLit") renderObjects = renderLit.attachNewNode("renderObjects") renderEnvironment = renderLit.attachNewNode("renderEnvironment") controllers.init() ai.init() audio.init(dropOffFactor = 1.4, distanceFactor = 14, dopplerFactor = 0.0) numMaxDynamicLights = 0 if enableShaders and not daemon: numMaxDynamicLights = 2 for i in range(numMaxDynamicLights): light = PointLight("Light" + str(i)) light.setColor(Vec4(0, 0, 0, 1)) light.setAttenuation(Vec3(0, 0, 1)) lightNode = renderLit.attachNewNode(light) lightNode.setPos(0, 0, 0) renderLit.setLight(lightNode) lightNodes.append((light, lightNode)) if enableShaders and not daemon: shadersChanged() if enablePostProcessing and not daemon: postProcessingChanged() if not daemon: winprops = WindowProperties() props = FrameBufferProperties() props.setRgbColor(1) reflectionBuffer = base.graphicsEngine.makeOutput( base.pipe, "reflection-buffer", -2, props, winprops, GraphicsPipe.BFSizeTrackHost | GraphicsPipe.BFRefuseWindow, base.win.getGsg(), base.win) reflectionBuffer.setSort(-100) reflectionBuffer.setClearColor(Vec4(0, 0, 0, 0)) reflectionRenderTexture = Texture() reflectionBuffer.addRenderTexture(reflectionRenderTexture, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) reflectionCamera = base.makeCamera(reflectionBuffer, scene = render, lens = base.cam.node().getLens(), mask = BitMask32.bit(4)) reflectionCamera.reparentTo(render) reflectionCamera.node().setActive(False) particles.init() maps = [x.split("\t") for x in readFile("maps/maps.txt").splitlines()]
def play_game(): global player_side global ai_side_name global game_field global last_winner def __player_move(reinf = 0.0): #show_game_field() move_ok = False while(not move_ok): move = raw_input("Move (row,column) --> ").split(",") if (len(move) < 2): continue try: m_x = int(move[0]) m_y = int(move[1]) except: continue if ((m_x < 0) or (m_x >= game_field.shape[0]) or (m_y < 0) or (m_y >= game_field.shape[1])): continue if (game_field[m_x, m_y] != EMPTY): continue # make move if everything OK game_field[m_x, m_y] = player_side move_ok = True #show_game_field() def __print_avg_ranks(moves_ranks, moves_num): moves_ranks = moves_ranks / moves_num print "\n" + "="*60 + "\nAvg move RANK: %f vs %f\n" % \ (moves_ranks[0], moves_ranks[1]) print "="*60 + "\n" stop_game = False # choose side while (player_side == None): side = raw_input("Choose your side [O/X] --> ").lower() if (side == "o"): player_side = NOUGHT player_side_name = "nought" ai_side_name = "cross" elif (side == "x"): player_side = CROSS player_side_name = "cross" ai_side_name = "nought" ai.init(ai_side_name) mc_ai.init(ai_side_name) maximin_ai.init(player_side_name) #maximin_ai.init(ai_side_name) print "----------------------\n\n" # opponents in sequential order opponents_move_funcs = [None, None] side_names = [None, None] #opponents_move_funcs[int(player_side < ai.my_side)] = __player_move opponents_move_funcs[int(player_side < ai.my_side)] = \ partial(maximin_ai.make_move, game_field[:]) opponents_move_funcs[int(player_side > ai.my_side)] = \ partial(ai.make_move, game_field[:]) side_names[int(player_side < ai.my_side)] = player_side_name side_names[int(player_side > ai.my_side)] = ai_side_name game_no = 0 reinforcement = 0.0 score = np.zeros(2) draws = 0 # counts draws moves_ranks = np.zeros(2) moves_num = np.zeros(2) while (game_no < MAX_GAMES_NUM): print "\n ================= GAME #%d =================\n" % (game_no) game_field[:] = np.zeros((3, 3)) # main loop turn_iter = 0 while (not stop_game): show_game_field() res = check_win() if (res != None): if (last_winner == 2): reinforcement = 1.0 score[1] += 1 elif (last_winner == 1): reinforcement = -1.0 score[0] += 1 else: reinforcement = 1.0 # 0.5 #score += 1 draws += 1 last_winner = None print res break prev_game_field = game_field.copy() opponents_move_funcs[turn_iter % 2](reinforcement) move_rank = maximin_ai.rank_move( prev_game_field[:], game_field[:], side_names[turn_iter % 2] ) moves_ranks[turn_iter % 2] += move_rank moves_num[turn_iter % 2] += 1 #print "\n--\tMOVE RANK: %f\n--" % (move_rank) if (reinforcement != 0.0): reinforcement -= np.sign(reinforcement) * 0.5 if ((ai.SIDES_NOMINALS[side_names[turn_iter % 2]] == ai.my_side) and (move_rank > 0)): reinforcement += 1.0 turn_iter += 1 print "\n ================= END OF GAME =================\n" print "\t\tSCORE: %d VS %d\n\t\tDRAWS: %d\n" % (score[0], score[1], draws) __print_avg_ranks(moves_ranks, moves_num) game_no += 1
# import ai_module import ai kb = ai.init() # defining symbols used in rules ai.defsym("m") ai.defsym("k") ai.defsym("append") ai.defsym("testu") ai.defsym("unify") ai.defsym("member") ai.defsym("union") ai.defsym("appendt") ai.defsym("reverse") ai.defconcept("person") # use of ask & tell interface kb.tell((m, 1, 2)) kb.tell((m, 3, 4)) kb.tell((m, [1, 2], [3, 4])) kb.ask((m, X, Y)) # definition of rules: (k, X, Y) | IF | (m, Y, X) (unify, X, X) | IF | True (append, [], X, X) | IF | True
print("Input board size") g_board_size = int(input()) g_board_size = g_board_size // 2 * 2 # g_board_size = 4 base_game_init(g_board_size) print("Input maximum depth for minimax value") g_depth = int(input()) # g_depth = 12 print("Show Minimax AI steps/paths? (Y/N)") show_ai_steps = True if input() in ["Y", "YES", "y", "Yes"] else False # show_ai_steps = True print("Showing Minimax steps") if show_ai_steps else print("Not showing steps") ai.init(g_depth, show_ai_steps) # Print board state g_board = [[0 for i in range(g_board_size)] for j in range(g_board_size)] # Set middle pieces to black and white mid = g_board_size // 2 g_board[mid - 1][mid - 1] = BLACK g_board[mid - 1][mid] = WHITE g_board[mid][mid - 1] = WHITE g_board[mid][mid] = BLACK cur_color = WHITE g_move_num = 0 agent = {WHITE: "Player", BLACK: "Minimax"} # Naive, Player, Minimax # agent = {WHITE: "Minimax", BLACK: "Player"} # Naive, Player, Minimax othello_board.init(g_board)
from PIL import Image import os import time from .utils import * import ai ai.init() def read_image(): # if your OS is win os.system("../../dependency/platform-tools-windows/adb.exe shell screencap -p autojump.png") os.system("../../dependency/platform-tools-windows/adb.exe pull /sdcard/autojump.png .") ## if your OS is mac # os.system("../../dependency/platform-tools-macos/adb shell screencap -p autojump.png") # os.system("../../dependency/platform-tools-macos/adb pull /sdcard/autojump.png .") im = Image.open("autojump.png") return im def click_screen(press_time): # if your OS is win os.system("../../dependency/platform-tools-windows/adb.exe swipe 50 50 50 50 " + str(int(press_time))) ## is your OS is mac # os.system("../../dependency/platform-tools-macos/adb swipe 50 50 50 50 " + str(int(press_time)) def jumper(): #ai.init() # print(screenShot) distance = 0.0 screenShot = Image.open('./autojump.png')
def init(showFrameRate=False, daemon=False): "Initializes various global components, like audio, lighting, and the clock. Should be called once at the beginning of the program." global renderLit global clock global renderObjects global renderEnvironment global log global reflectionBuffer global reflectionCamera global reflectionRenderTexture global defaultFov global enableShaders global enablePostProcessing global enableDistortionEffects global filters global isDaemon global mf global maps mf = None if not vfs.isDirectory("maps"): mf = Multifile() mf.openRead( ExecutionEnvironment.getEnvironmentVariable("PKG_ROOT") + "/pkg.mf") isDaemon = daemon if not daemon: base.setBackgroundColor(2.0 / 255.0, 28.0 / 255.0, 53.0 / 255.0) log = Logger() sys.excepthook = exceptHook clock = Clock() base.disableMouse() # Disable default mouse camera control if not daemon: base.camNode.setCameraMask(BitMask32.bit(1)) base.camLens.setFov(defaultFov) renderLit = render.attachNewNode("renderLit") renderObjects = renderLit.attachNewNode("renderObjects") renderEnvironment = renderLit.attachNewNode("renderEnvironment") controllers.init() ai.init() audio.init(dropOffFactor=1.4, distanceFactor=14, dopplerFactor=0.0) numMaxDynamicLights = 0 if enableShaders and not daemon: numMaxDynamicLights = 2 for i in range(numMaxDynamicLights): light = PointLight("Light" + str(i)) light.setColor(Vec4(0, 0, 0, 1)) light.setAttenuation(Vec3(0, 0, 1)) lightNode = renderLit.attachNewNode(light) lightNode.setPos(0, 0, 0) renderLit.setLight(lightNode) lightNodes.append((light, lightNode)) if enableShaders and not daemon: shadersChanged() if enablePostProcessing and not daemon: postProcessingChanged() if not daemon: winprops = WindowProperties() props = FrameBufferProperties() props.setRgbColor(1) reflectionBuffer = base.graphicsEngine.makeOutput( base.pipe, "reflection-buffer", -2, props, winprops, GraphicsPipe.BFSizeTrackHost | GraphicsPipe.BFRefuseWindow, base.win.getGsg(), base.win) reflectionBuffer.setSort(-100) reflectionBuffer.setClearColor(Vec4(0, 0, 0, 0)) reflectionRenderTexture = Texture() reflectionBuffer.addRenderTexture(reflectionRenderTexture, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) reflectionCamera = base.makeCamera(reflectionBuffer, scene=render, lens=base.cam.node().getLens(), mask=BitMask32.bit(4)) reflectionCamera.reparentTo(render) reflectionCamera.node().setActive(False) particles.init() maps = [x.split("\t") for x in readFile("maps/maps.txt").split("\n")]
flags = pygame.DOUBLEBUF if root.settings["graphics"]["fullscreen"]: flags = flags | pygame.FULLSCREEN screen = sgc.surface.Screen(renderspace_size, flags, root.settings["graphics"]["color_depth"]) pygame.display.set_caption("[Loading...]") scrollingscreen = rotutil.ScrollingWorldManager(root, screen.image) root.screen = scrollingscreen serialize.init(root) ship.init(root) item.init(root) primitives.init(root) tasks.init(root) ai.init(root) ui_states.init(root) sectors.init(root) newgame.init(root) dialog.init(root) quests.init(root) eb.init_grufs(root) faction.init(root) lang.init() import music music.init() root.gfxcursor = gfxcursor.GfxCursor(root, root.screen.screen) root.particlemanager = particles.ParticleManager()