def __init__(self,env, lr = 0.03,eps = 0.2,epsDiscount = 0.99,discount = 0.8,keepPlan = True,useTree = True, treeSearchLen = 50): self.env = env self.EnvCopy = copy(env) self.size = env.size self.env_shape = env.shape self.y_s,self.x_s = self.env_shape self.lr = lr self.eps = eps self.epsDisc = epsDiscount self.discount = discount self.a_count = env.a_count self.Q = self.qTable() self.KnownIdx = np.array([]) self.TrMem = self.transTable() self.gr = graphics.Graphics(env.grid,self) self.Tree = tree.Tree(self.EnvCopy,self) self.keepPlan = keepPlan self.useTree = useTree self.treeSearchLen = treeSearchLen
def init_display(): global g pygame.display.set_mode((1200, 800)) logo = pygame.image.load("./images/weapon_logo.png") pygame.display.set_caption("Platformer") pygame.display.set_icon(logo) screen = pygame.display.get_surface() g = graphics.Graphics(screen)
def __init__(self): getSmallestResolution() #g.SCREEN_WIDTH = pyglet.window.get_platform().get_default_display().get_default_screen().width #g.SCREEN_HEIGHT=pyglet.window.get_platform().get_default_display().get_default_screen().height #print pyglet.window.get_platform().get_default_display().get_default_screen().get_modes() g.SCREENSELECTED = pyglet.window.get_platform().get_default_display( ).get_default_screen()._handle cfg_parser.readCfg() if int(g.SCREENSELECTED) < len(pyglet.window.get_platform( ).get_default_display().get_screens()) and int(g.SCREENSELECTED) >= 0: defaultMonitor = pyglet.window.get_platform().get_default_display( ).get_screens()[int(g.SCREENSELECTED)] else: defaultMonitor = pyglet.window.get_platform().get_default_display( ).get_default_screen() g.screen = pyglet.window.Window( fullscreen=g.FULLSCREEN, vsync=g.VSYNC, width=g.SCREEN_WIDTH, height=g.SCREEN_HEIGHT, screen=defaultMonitor ) #,screen=pyglet.window.get_platform().get_default_display().get_screens()[1] g.SCREEN_WIDTH = g.screen.width g.SCREEN_HEIGHT = g.screen.height g.gameEngine = self g.screen.set_mouse_cursor(g.cursorUp) g.screen.set_caption(GAME_NAME) g.screen.set_icon(g.gameIcon) self.soundManager = pyglet.media.Player() self.soundManager.volume = g.MUSICVOLUME self.musicManager = pyglet.media.Player() self.musicManager.volume = g.MUSICVOLUME self.musicManager.eos_action = pyglet.media.Player.EOS_LOOP self.loginMenu = loginMenu(g.screen) self.fightStartAnimation = fightstartanimation.FightStartAnimation() self.fightScreen = FightScreen() self.resManager = resourcemanager.ResourceManager() self.graphics = graphics.Graphics(g.screen, self.resManager.tileSheets, self.resManager.spriteSheets, self.resManager.mouseSheets) self.checkPressed = [] self.fps = int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) g.screen.push_handlers(on_key_press=self.my_key_press, on_key_release=self.my_key_release, on_mouse_press=self.mouseClick, on_mouse_release=self.mouseRelease, on_mouse_motion=self.mouseMove) self.fpsTick = 0 self.lastTick = 0 self.fpsDisplay = pyglet.window.FPSDisplay(g.screen) self.screenshotting = False pyglet.gl.glClearColor(0, 0, 0, 255)
def run_game(): """ runs a single player in a four_in_a_row game , we can choose if the player gonna be us to play or the computer ,if we inserted the params in a wrong way the func' gonna print an error msg and return none """ if len(sys.argv) != SERVER_ARGS + 1 and len(sys.argv) != CLIENT_ARGS +1\ or not MIN_PORT <= int(sys.argv[PORT_INDEX]) <= MAX_PORT or \ sys.argv[IS_HUMAN_INDEX] != HUMAN_PLAYER and \ sys.argv[IS_HUMAN_INDEX] != AI_PLAYER : print(ERROR_MSG) return None parent = T.Tk() port = int(sys.argv[PORT_INDEX]) if len(sys.argv) == CLIENT_ARGS + 1: ip = sys.argv[IP_INDEX] graphics.Graphics(parent, port, sys.argv[IS_HUMAN_INDEX], ip) parent.title(CLIENT) else: graphics.Graphics(parent, port, sys.argv[IS_HUMAN_INDEX]) parent.title(SERVER) parent.mainloop()
def __init__(self, x, y, width, height, image_path): """ Constructor of the Item class which is responsible for getting the image of the object class from the sprite sheet. """ super(Item, self).__init__() self.graphic_obj = graphics.Graphics(image_path) self.image = self.graphic_obj.extract_graphic(x, y, width, height) self.rect = self.image.get_rect() self.__x_vector = 0 self.__y_vector = 0
def quicksort2(lst, pivot=None): # Base Case if len(lst) <= 1: return lst if pivot is None: pivot = lst[len(lst) // 2] # General case lst_lower = [] lst_upper = [] lst_lower_sum = 0 lst_upper_sum = 0 for n in range(len(lst)): AlgorithmicRun.operation_counter += 1 lst_active = lst_lower if lst[n] < pivot else lst_upper lst_active_sum = lst_lower_sum if lst[n] < pivot else lst_upper_sum if lst_active_sum == 0 or len(lst_active) == 0: lst_active_sum = lst[n] lst_active.append(lst[n]) else: if lst_active_sum / len(lst_active) > lst[n]: lst_active = [lst[n]] + lst_active # TODO: Change operators else: lst_active = lst_active + [lst[n]] lst_active_sum += lst[n] if lst[n] < pivot: lst_lower = lst_active lst_lower_sum = lst_active_sum else: lst_upper = lst_active lst_upper_sum = lst_active_sum if len(lst) == 1000: g = graphics.Graphics(0, 1000, 100, 100) print('Upper\n' + g.generate(lst_lower)) print('Lower\n' + g.generate(lst_upper)) # Concatenate the two quicksorts return quicksort2(lst_lower) + [pivot] + quicksort2(lst_upper)
def start_game(): map_file = "configs/mapdefault.txt" config = "configs/mapconfig.txt" images = "images" leaderboard = "configs/leaderboard.txt" animated = True speed = 5 graphics.Graphics(map_file=map_file, config=config, images=images, animated=animated, speed=speed, leaderboard=leaderboard)
def __init__(self): import datetime self.id = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.g = graphics.Graphics(53, 30) self.r = graphics.Renderer(self.g) self.s = screens.ScreenManager(self.r) self.c = command.CommandManager() self.a = animation.AnimationPlayer(self) self.variables = {} #state:(animation,location,intro) self.date = None self.player = None self.running = False
def __init__(self, args): ''' Initializes the game and creates objects of the classes we defined in other documents. ''' self.state = 0 self.board = board.Board(self) self.graphics = graphics.Graphics(self) self.playon = playon.PlayOn(self, args.ai_type, args.ai_strength) self.ai = ai.AI(self) self.graphics.initialize_game() self.board.initialize_board() print('\nGame initialized\n')
def __load_next_map(self): '''Cleans all information from previous map and loads new one''' self.player = player.Player() self.enemies = [] self.map_ = map.Map(self.player) self.map_.load(f'{self.map_path}\\map{str(self.current_map)}.map') self.__load_enemies() self.graphics = graphics.Graphics(self.player, self.enemies, self.map_, self.current_map, len(self.maps)) self.movement = player_movement.Movement(self.player, self.enemies, self.map_, self.graphics) self.event_handler = events.EventHandler(self.player, self.enemies, self.map_, self.graphics, self.movement)
def __init__(self): pygame.init() players = [game.Player((255, 0, 0))] resolution = pygame.display.Info() self.window_size = (resolution.current_w, resolution.current_h) self.map_ = map.Map((5, 5), 10, players, 4, 32, self.window_size) self.map_.create_map() self.gameplay = game.Gameplay(self.map_, 6, 2000, 8) self.graphics = graphics.Graphics(self.map_, self.gameplay, self.window_size) self.event_handler = events.EventHandler(self.map_, self.graphics, self.gameplay)
def __init__(self, replay_file, conf_options): self.__rf = open(replay_file, 'r') self.__map_id = None self.__num_hiders = None self.__num_seekers = None while True: token = self.__rf.readline().strip() if token == 'simulation:': break pre_token = token.split(':')[0] post_token = token.split(':')[1] if pre_token == 'map_id': self.__map_id = int(post_token) elif pre_token == 'num_hiders': self.__num_hiders = int(post_token) elif pre_token == 'num_seekers': self.__num_seekers = int(post_token) else: print('PARSING FAILED') print('map_id:', self.__map_id) print('num_hiders:', self.__num_hiders) print('num_seekers:', self.__num_seekers) self.__map = gamemap.PolygonMap(self.__map_id) window_width = self.__map.get_map_width() window_height = self.__map.get_map_height() self.__conf_options = conf_options self.__fps = self.__conf_options.get_fps() self.__velocity = self.__conf_options.get_velocity() self.__fixed_time_quanta = self.__conf_options.get_fixed_time_quanta() self.__inactive_hiders = [] self.__first_flag = { agent.AgentType.Hider: True, agent.AgentType.Seeker: True } # def __init__(self, window_width, window_height, num_hiders, num_seekers, polygon_map, conf_options): self.__window = graphics.Graphics(window_width, window_height, self.__num_hiders, self.__num_seekers, self.__map, self.__conf_options)
def __init__(self, src_dir): resource_mgr = resource.Resource() resource_mgr.load(src_dir) self._graphic_mgr = graphics.Graphics(resource_mgr) self._last_tick = 0 self._current_turn = 0 self._last_tile = None self._all_tiles = [] self._clock = pygame.time.Clock() self._players = [ players.HumanPlayer(self._graphic_mgr, players.Player.POSITION.SOUTH, u'南大'), players.AIPlayer(self._graphic_mgr, players.Player.POSITION.EAST, u'东大'), players.AIPlayer(self._graphic_mgr, players.Player.POSITION.NORTH, u'北大'), players.AIPlayer(self._graphic_mgr, players.Player.POSITION.WEST, u'西大') ] self._graphic_mgr.catch_players(self._players) self._graphic_mgr.clock = self._clock self._can_draw = False self._cache_text = None self.reset()
def branch(self, x, y): ''' Creates different game states which control what the turtle does. ''' x = int(x) y = int(y) # self.state = 1 if self.playon.no_input == False: if self.state == 0: self.playon.set_players(x, y) self.board.initialize_board() self.graphics.create_board() self.graphics.during_game() if self.playon.ai_play() == True: self.graphics.end_game() self.state = 2 else: self.state = 1 elif self.state == 1: if self.playon.human_play(x, y) == True: self.graphics.end_game() self.state = 2 else: if self.playon.ai_play() == True: self.graphics.end_game() self.state = 2 else: self.state = 0 self.board = board.Board(self) self.graphics = graphics.Graphics(self) self.playon = playon.PlayOn(self) self.ai = ai.AI(self) self.graphics.initialize_game() self.board.initialize_board() print('\nGame initialized\n')
def __init__(self): """Constructor for LadderBlock class """ super(LadderBlock, self).__init__() self.graphic_obj = graphics.Graphics('blocks.png') self.image = self.graphic_obj.extract_graphic(502, 71, 73, 74) self.rect = self.image.get_rect()
def __init__(self): self.__graphics = graphics.Graphics() self.__p = pyaudio.PyAudio() self.__values = list()
def __init__(self): """Constructor for Cage class """ super(Cage, self).__init__() self.graphic_obj = graphics.Graphics('chain.png') self.image = self.graphic_obj.extract_graphic(24, 1, 22, 68) self.rect = self.image.get_rect()
import sys import graphics from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import Qt if __name__ == '__main__': APP = QApplication(sys.argv) WINDOW = graphics.Graphics() WINDOW.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint) WINDOW.show() sys.exit(APP.exec_())
def on_enter_frame(self, scene, context): g = graphics.Graphics(context) rowcount, keys = len(self.keys), self.keys start_hour = 0 if self.start_time: start_hour = self.start_time end_hour = 24 * 60 if self.end_time: end_hour = self.end_time # push graph to the right, so it doesn't overlap legend_width = self.legend_width or self.longest_label(keys) self.graph_x = legend_width self.graph_x += 8 #add another 8 pixes of padding self.graph_width = self.width - self.graph_x # TODO - should handle the layout business in graphics self.layout = context.create_layout() default_font = pango.FontDescription(self.get_style().font_desc.to_string()) default_font.set_size(8 * pango.SCALE) self.layout.set_font_description(default_font) #on the botttom leave some space for label self.layout.set_text("1234567890:") label_w, label_h = self.layout.get_pixel_size() self.graph_y, self.graph_height = 0, self.height - label_h - 4 if not self.data: #if we have nothing, let's go home return positions = {} y = 0 bar_width = min(self.graph_height / float(len(self.keys)), self.max_bar_width) for i, key in enumerate(self.keys): positions[key] = (y + self.graph_y, round(bar_width - 1)) y = y + round(bar_width) bar_width = min(self.max_bar_width, (self.graph_height - y) / float(max(1, len(self.keys) - i - 1))) max_bar_size = self.graph_width - 15 # now for the text - we want reduced contrast for relaxed visuals fg_color = self.get_style().fg[gtk.STATE_NORMAL].to_string() label_color = self.colors.contrast(fg_color, 80) self.layout.set_alignment(pango.ALIGN_RIGHT) self.layout.set_ellipsize(pango.ELLIPSIZE_END) # bars and labels self.layout.set_width(legend_width * pango.SCALE) factor = max_bar_size / float(end_hour - start_hour) # determine bar color bg_color = self.get_style().bg[gtk.STATE_NORMAL].to_string() base_color = self.colors.contrast(bg_color, 30) for i, label in enumerate(keys): g.set_color(label_color) self.layout.set_text(label) label_w, label_h = self.layout.get_pixel_size() context.move_to(0, positions[label][0] + (positions[label][1] - label_h) / 2) context.show_layout(self.layout) if isinstance(self.data[i], list) == False: self.data[i] = [self.data[i]] for row in self.data[i]: bar_x = round((row[0]- start_hour) * factor) bar_size = round((row[1] - start_hour) * factor - bar_x) g.fill_area(round(self.graph_x + bar_x), positions[label][0], bar_size, positions[label][1], base_color) #white grid and scale values self.layout.set_width(-1) context.set_line_width(1) pace = ((end_hour - start_hour) / 3) / 60 * 60 last_position = positions[keys[-1]] grid_color = self.get_style().bg[gtk.STATE_NORMAL].to_string() for i in range(start_hour + 60, end_hour, pace): x = round((i - start_hour) * factor) minutes = i % (24 * 60) self.layout.set_markup(dt.time(minutes / 60, minutes % 60).strftime("%H<small><sup>%M</sup></small>")) label_w, label_h = self.layout.get_pixel_size() context.move_to(self.graph_x + x - label_w / 2, last_position[0] + last_position[1] + 4) g.set_color(label_color) context.show_layout(self.layout) g.set_color(grid_color) g.move_to(round(self.graph_x + x) + 0.5, self.graph_y) g.line_to(round(self.graph_x + x) + 0.5, last_position[0] + last_position[1]) context.stroke()
def set_values(self): self.ram = RAM.ram(4) self.V = [0] * 16 self.I = 0 self.pc = 512 self.graphics = graphics.Graphics() self.delay_timer = 60 self.sound_timer = 60 self.stack = [0] * 16 self.stack_pointer = 0 self.key = [0] * 16 self.key_list = [ "1", "2", "3", "4", "Q", "W", "E", "R", "A", "S", "D", "F", "Z", "X", "C", "V" ] self.draw_flag = True self.opcode_dict0 = { "0x00e0": self._00E0, "0x00ee": self._00EE, } self.opcode_dict1 = { "ea1": self._EXA1, "f07": self._FX07, "f0a": self._FX0A, "f15": self._FX15, "f18": self._FX18, "f1e": self._FX1E, "f29": self._FX29, "f33": self._FX33, "f55": self._FX55, "f65": self._FX65, } self.opcode_dict2 = { "50": self._5XY0, "80": self._8XY0, "81": self._8XY1, "82": self._8XY2, "83": self._8XY3, "84": self._8XY4, "85": self._8XY5, "86": self._8XY6, "87": self._8XY7, "8e": self._8XYE, "90": self._9XY0, "ee": self._EX9E } self.opcode_dict3 = { "0": self._0NNN, "1": self._1NNN, "2": self._2NNN, "3": self._3XNN, "4": self._4XNN, "6": self._6XNN, "7": self._7XNN, "a": self._ANNN, "b": self._BNNN, "c": self._CXNN, "d": self._DXYN }
def __init__(self): self.graphics = graphics.Graphics() self.titleScreen = self.graphics.loadImage("start.png") self.pauseScreen = self.graphics.loadImage("pause.png") self.winScreen = self.graphics.loadImage("win.png") self.loseScreen = self.graphics.loadImage("lose.png") self.world = world.World() self.state = GAMESTATE_TITLE #create human player self.human = player.Player(self.graphics, self.world, team=1) position = (0, 0) colony = mapobject.Colony(self.human, position, self.graphics) self.world.addObject(colony) self.human.addColony(colony) #create AI Player self.AIPlayer = aiplayer.AIPlayer(self.graphics, self.world, team=2) #ai does nothing yet #generate random position for AI colony randomAngle = random.randint(0, 360) randomDist = math.sqrt( random.random() * ((MAXAIDISTANCE - MINAIDISTANCE)**2) ) + MINAIDISTANCE #this ensures that the random targets are uniformly spread out over the sector position = (position[0] + randomDist * math.cos(randomAngle * math.pi / 180), position[1] + randomDist * math.sin(randomAngle * math.pi / 180)) colony = mapobject.Colony(self.AIPlayer, position, self.graphics, team=2) #print "AI position: " + str(position) self.world.addObject(colony) self.AIPlayer.addColony(colony) self.world.addLeaves(self.graphics) #add lots of random leaves self.input = Input() self.input.onClick(self.leftClick) self.input.onRightClick(self.rightClick) self.input.onDrag(self.drag) #make gui self.gui = graphics.ContainerWidget() self.gui.add(graphics.ResourceDisplay(self.human)) workerImage = self.graphics.loadImage('workerbutton.png') soldierImage = self.graphics.loadImage('soldierbutton.png') buildWidget = graphics.BuildWidget(pygame.Rect((0, 0), (116, 61)), (200, 200, 200)) buildWidget.add( graphics.Button(pygame.Rect((0, 0), (50, 50)), image=soldierImage, bgColor=(100, 100, 100), action=self.buySoldier)) buildWidget.add( graphics.Button(pygame.Rect((0, 0), (50, 50)), image=workerImage, bgColor=(100, 100, 100), action=self.buyWorker)) self.gui.add(buildWidget) position = self.graphics.normalizeScreenCoords((-150, -150)) rect = pygame.Rect(position, (150, 150)) minimap = graphics.Minimap(rect, self.world, self.graphics) self.gui.add(minimap) try: pygame.mixer.init() self.music = True except: self.music = False if self.music: try: self.titlemusic = pygame.mixer.Sound( data.filepath('titlemusic.ogg')) self.titlemusic.play(-1) except: self.music = False
"This will only work on windows due to the keyboard handling method") import renderer import keyboard import clock import graphics from time import perf_counter import math FPS = 60 SCREEN_WIDTH = 120 SCREEN_HEIGHT = 40 c = clock.Clock(FPS) r = renderer.Renderer(SCREEN_WIDTH, SCREEN_HEIGHT, FPS) gfx = graphics.Graphics(r) r.initScreen() quit = False then = perf_counter() now = perf_counter() playerX = 8 playerY = 8 playerA = 0 speed = 2 turnSpeed = 1.5 mapHeight = 16
print("Invalid token...") sys.exit(1) print("Logged in with {}".format(Api.token)) resp_u = input('Starting user: '******'Starting channel: ') Api.set_username(resp_u) username = resp_u channel = resp_c messages = Api.poll_messages() Gui = graphics.Graphics() ### repeater function needs to be defined here in order to have variable access (I think?) class Threader(threading.Thread): def run(self): while running: messages = Api.poll_messages() Gui.render(messages, channel, username) time.sleep(2) ### running = True Threader().start() ###
import stock import movingAverage import graphics if __name__ == "__main__": # Facebook (FB), Amazon (AMZN), Apple (AAPL),Netflix (NFLX) and Google (GOOG). # Define the stocks we want analyse. faang = ["FB", "AMZN", "AAPL", "NFLX", "GOOG"] #aapl = ["AAPL"] # We would like to see the data avaliable between this dates start_date = '2020-01-01' end_date = '2020-11-20' # Define the days average short_rolling = 20 long_rolling = 100 # Define the column we want analyse column = ["Close"] stock = stock.Stock(faang) stock_values = stock.returnPrices(start_date, end_date) movingAverage = movingAverage.MovingAverage( stock_values, start_date, end_date) shortMovingAverage_values = movingAverage.returnMovingAverage( short_rolling) longMovingAverage_values = movingAverage.returnMovingAverage(long_rolling) graphic = graphics.Graphics(stock_values) graphic.returnMovingAveragePlot( shortMovingAverage_values, longMovingAverage_values, column)
def __init__(self, mode_hiders, mode_seekers, num_hiders, num_seekers, map_id, input_file, output_file, conf_options, log_flag, vis_flag, total_step_times, sim_turn, max_steps=1000, window_width=640, window_height=360): assert (mode_hiders in Simulator.mode_type_hiders) assert (mode_seekers in Simulator.mode_type_seekers) self.__mode_hiders = mode_hiders self.__mode_seekers = mode_seekers self.__num_hiders = num_hiders self.__num_seekers = num_seekers self.__map_id = map_id self.__input_file = input_file self.__output_file = output_file self.__conf_options = conf_options self.__fps = self.__conf_options.get_fps() self.__velocity = self.__conf_options.get_velocity() self.__fixed_time_quanta = self.__conf_options.get_fixed_time_quanta() self.__verbose = self.__conf_options.get_verbose() self.__num_rays = self.__conf_options.get_num_rays() self.__visibility_angle = self.__conf_options.get_visibility_angle() self.__show_fellows = self.__conf_options.get_show_fellows() self.__show_opponent = self.__conf_options.get_show_opponent() self.__sim_turn = sim_turn self.__stats = statistic.Statistic(num_hiders, num_seekers, self.__map_id, self.__sim_turn) self.__max_steps = max_steps self.__steps = 0 self.__polygon_map = gamemap.PolygonMap(map_id) self.__log_flag = log_flag self.__vis_flag = vis_flag self.__replay_output_file = None self._total_step_times = total_step_times if log_flag: print('Logging initiated:', output_file) self.__replay_output_file = open(output_file, 'w') self.__replay_output_file.write('map_id:' + str(map_id) + '\n') self.__replay_output_file.write('num_hiders:' + str(num_hiders) + '\n') self.__replay_output_file.write('num_seekers:' + str(num_seekers) + '\n') self.__replay_output_file.write('simulation:' + '\n') hider_map_copy = gamemap.PolygonMap(map_id) seeker_map_copy = gamemap.PolygonMap(map_id) # AI setup if mode_hiders == 'random': self.__hider_team = team.RandomTeam(agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta) elif mode_hiders == 'bayesian': self.__hider_team = team.BayesianTeam(agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta) elif mode_hiders == 'sbandit': self.__hider_team = team.UCBPassiveTeam( agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle, False, False) elif mode_hiders == 'hm_sbandit': self.__hider_team = team.UCBPassiveTeam( agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle, True, False) elif mode_hiders == 'hv_sbandit': self.__hider_team = team.UCBPassiveTeam( agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle, False, True) elif mode_hiders == 'hmv_sbandit': self.__hider_team = team.UCBPassiveTeam( agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle, True, True) elif mode_hiders == 'human': self.__hider_team = team.HumanRandomTeam( agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta) elif mode_hiders == 'offset': self.__hider_team = team.OffsetTeam(agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta) if mode_seekers == 'random': self.__seeker_team = team.RandomTeam(agent.AgentType.Seeker, num_seekers, seeker_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta) elif mode_seekers == 'sbandit': self.__seeker_team = team.UCBAggressiveTeam( agent.AgentType.Seeker, num_seekers, seeker_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle) elif mode_seekers == 'coverage': self.__seeker_team = team.UCBCoverageTeam( agent.AgentType.Seeker, num_seekers, seeker_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle) elif mode_seekers == 'cc': self.__seeker_team = team.UCBCoverageCommunicationTeam( agent.AgentType.Seeker, num_seekers, seeker_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle) elif mode_seekers == 'human': self.__seeker_team = team.HumanRandomTeam( agent.AgentType.Seeker, num_seekers, seeker_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta) elif mode_seekers == 'wave': self.__seeker_team = team.WaveTeam(agent.AgentType.Seeker, num_seekers, seeker_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle) elif mode_seekers == 'trap': self.__seeker_team = team.TrapTeam(agent.AgentType.Seeker, num_seekers, seeker_map_copy, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle) # Graphics setup self.__window_width = self.__polygon_map.get_map_width() self.__window_height = self.__polygon_map.get_map_height() self.__texture_flag = self.__conf_options.get_texture_flag() dynamic_batching_flag = True show_hiders_flag = True show_seekers_flag = True if mode_hiders == 'human': dynamic_batching_flag = False show_seekers_flag = self.__show_opponent if mode_seekers == 'human': dynamic_batching_flag = False show_hiders_flag = self.__show_opponent if self.__vis_flag: self.__window = graphics.Graphics( self.__window_width, self.__window_height, num_hiders, num_seekers, self.__polygon_map, self.__conf_options, dynamic_batching_flag, show_hiders_flag, show_seekers_flag, self.__texture_flag) else: self.__window = None # Movers setup self.__hiders = [ Mover(self.__polygon_map, 0, 0, 0, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle) for i in range(num_hiders) ] self.__seekers = [ Mover(self.__polygon_map, 0, 0, 0, self.__fps, self.__velocity, self.__fixed_time_quanta, self.__num_rays, self.__visibility_angle) for i in range(num_seekers) ] # Mover active list self.__hiders_active = [True for i in range(num_hiders)] self.__seekers_active = [True for i in range(num_seekers)] # Mapping AI agents and Graphics players for interchange of percepts and # actions self.__hiders_agent2player = {} self.__hiders_player2agent = [None for i in range(self.__num_hiders)] counter = 0 for i in range(self.__hider_team.get_ranks()): for j in range(self.__hider_team.get_num_rankers(i)): rank, ai_idx = i, j graphics_idx = counter self.__hiders_agent2player[(rank, ai_idx)] = graphics_idx self.__hiders_player2agent[graphics_idx] = (rank, ai_idx) counter += 1 self.__seekers_agent2player = {} self.__seekers_player2agent = [None for i in range(self.__num_seekers)] counter = 0 for i in range(self.__seeker_team.get_ranks()): for j in range(self.__seeker_team.get_num_rankers(i)): rank, ai_idx = i, j graphics_idx = counter self.__seekers_agent2player[(rank, ai_idx)] = graphics_idx self.__seekers_player2agent[graphics_idx] = (rank, ai_idx) counter += 1 # Initializing the caught list by setting all hiders as NOT CAUGHT # self.__caught = [[False for j in range(self.__hider_team.get_num_rankers(i))] for i in range(self.__hider_team.get_ranks())] self.__num_caught = 0 self.__total_time = 0
def __init__(self): """ Constructor for Block class """ super(Block, self).__init__() self.graphic_obj = graphics.Graphics('blocks.png') self.image = self.graphic_obj.extract_graphic(506, 506, 68, 25) self.rect = self.image.get_rect()
def __init__(self): self.graphics = graphics.Graphics() self.tablero = tablero.Tablero() self.opciones()
def __init__(self): """Constructor for BrokenLadderBlock class """ super(BrokenLadderBlock, self).__init__() self.graphic_obj = graphics.Graphics('blocks.png') self.image = self.graphic_obj.extract_graphic(647, 80, 73, 64) self.rect = self.image.get_rect()
import graphics import functions from navigators import * # Graphics files import gobblersprite # Sound and graphics init for PyGame pygame.init() # Set up the screen. screen_size = (55 * 8, 61 * 8) screen = pygame.display.set_mode([screen_size[0], screen_size[1]]) pygame.display.set_caption("Gobbler") # System setup g = graphics.Graphics() f = functions.GameFunctions(g, None) # Tilesets Setup tmxdata = tmxdata.TmxData() maze = maze.Maze(tmxdata) pellets_template = pellets.Pellets(tmxdata) pellets = pellets.Pellets(tmxdata) pellets.reset(pellets_template) gobbler_paths = gobblerpaths.GobblerPaths(tmxdata) # Sprites Setup gobbler = gobblersprite.GobblerSprite(g, VoidNavigator()) # Game Loop setup fps = 60
def main(): num_i = 2 num_h = 5 num_o = 1 neural_network = nn.NeuralNetwork(num_i, num_h, num_o) start_time = time.time() plt.title("Training Data Improvement") plt.xlabel("Iterations") plt.ylabel("Guess") l1 = [] l2 = [] l3 = [] l4 = [] # Number of training iterations epoch = 10000 # Graphics object gr = g.Graphics(num_i, num_h, num_o) for i in range(epoch): file = open("training_data.txt", "r") arr = [] for j in range(4): str_ = file.readline() str_split = str_.split(" ") arr.append(str_split) random.shuffle(arr) for j in range(4): input_ = [int(arr[j][0]), int(arr[j][1])] target = [int(arr[j][2].strip())] neural_network.train(input_, target, gr) if i % (epoch / 100) == 0: l1.append(neural_network.feed_forward([0, 0])) l2.append(neural_network.feed_forward([1, 1])) l3.append(neural_network.feed_forward([0, 1])) l4.append(neural_network.feed_forward([1, 0])) file.close() # Print progress bar print_progress_bar(i + 1, epoch, prefix='Progress:', suffix='Complete', length=50) # Calculate and display training time display_time(start_time) # testing data for the network print("[0, 0]: " + str(round(neural_network.feed_forward([0, 0])[0]))) print("[1, 1]: " + str(round(neural_network.feed_forward([1, 1])[0]))) print("[0, 1]: " + str(round(neural_network.feed_forward([0, 1])[0]))) print("[1, 0]: " + str(round(neural_network.feed_forward([1, 0])[0]))) # Plot points and display graph x = [] for i in range(epoch): if i % (epoch / 100) == 0: x.append(i) plt.plot(x, l1, "black") plt.plot(x, l2, "black") plt.plot(x, l3, "black") plt.plot(x, l4, "black") plt.show()