def __init__(self, width, height): super().__init__(width, height) self.background = arcade.load_texture("images/bgni.jpg") self.world = World(SCREEN_WIDTH, SCREEN_HEIGHT) self.dot_sprite = ModelSprite('images/player.png', model=self.world.player) self.monster_sprite = MonsterSprite(model=self.world.monster) self.coin_sprite = [ CoinSprite(model=self.world.coin[0]), CoinSprite(model=self.world.coin[1]), CoinSprite(model=self.world.coin[2]), CoinSprite(model=self.world.coin[3]), CoinSprite(model=self.world.coin[4]) ] self.bomb_sprite = [ BombSprite(model=self.world.bomb[0]), BombSprite(model=self.world.bomb[1]), BombSprite(model=self.world.bomb[2]) ] self.hp = [ arcade.load_texture("images/pills.png"), arcade.load_texture("images/pills.png"), arcade.load_texture("images/pills.png") ] self.num_hp = 2 self.menus = { 'gameover': arcade.load_texture("images/gameover.png"), 'play': arcade.load_texture("images/play.png") } self.count = 0 self.temp_player = 1
class SnakeWindow(arcade.Window): def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.BLACK) self.world = World(SCREEN_WIDTH, SCREEN_HEIGHT) self.snake_sprite = ModelSprite('images/block.png', model=self.world.snake) self.snake_sprite = SnakeSprite(self.world.snake) self.heart_sprite = HeartSprite(self.world.heart) def update(self, delta): self.world.update(delta) def on_key_press(self, key, key_modifiers): self.world.on_key_press(key, key_modifiers) def on_draw(self): arcade.start_render() self.snake_sprite.draw() self.heart_sprite.draw()
class GameWindow(arcade.Window): def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.BLACK) self.world = World(width, height) self.endgame = arcade.Sprite('images/black.png', scale=2) self.hunter_sprite = ModelSprite('images/hunter.png', scale=0.4, model=self.world.hunter) self.bullet_sprite = [] self.pigs_sprites = [] for pig in self.world.pigs: self.pigs_sprites.append( ModelSprite('images/pig.png', scale=0.18, model=pig)) self.foxs_sprites = [] for fox in self.world.foxs: self.foxs_sprites.append( ModelSprite('images/fox.png', scale=0.36, model=fox)) def on_key_press(self, key, key_modifiers): self.world.on_key_press(key, key_modifiers) def on_draw(self): self.bullet_sprite.clear() for i in range(len(self.world.bullets)): if self.world.status_bullet[i] == 1: self.bullet_sprite.append( ModelSprite("images/bullet.png", scale=0.02, model=self.world.bullets[i])) arcade.start_render() i = 0 for sprite in self.pigs_sprites: if self.world.status_pig[i] == 1: sprite.draw() i += 1 j = 0 for sprite in self.foxs_sprites: if self.world.status_fox[j] == 1: sprite.draw() j += 1 self.hunter_sprite.draw() for sprite in self.bullet_sprite: sprite.draw() arcade.draw_text(str(self.world.score), self.width - 50, self.height - 30, arcade.color.WHITE, 20) if self.world.heart == 0: self.endgame.draw() arcade.draw_text("END GAME", 200, 300, arcade.color.WHITE, 50) def animate(self, delta): if self.world.heart != 0: self.world.animate(delta)
class SpaceGameWindow(arcade.Window): def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.BLACK) self.world = World(width, height) self.gold_sprite = ModelSprite('images/Gold.png', model=self.world.gold) self.ship_sprite = ModelSprite('images/ship.png', model=self.world.ship) def on_draw(self): arcade.start_render() self.gold_sprite.draw() self.ship_sprite.draw() arcade.draw_text(str(self.world.score), self.width - 30, self.height - 30, arcade.color.WHITE, 20) def update(self, delta): self.world.update(delta) def on_key_press(self, key, key_modifiers): self.world.on_key_press(key, key_modifiers)
def main(): # constants specific to statistic collection of simulations NUM_SIMULATIONS = 2 parser = argparse.ArgumentParser(description="Visualization controls") parser.add_argument("--visualize", action="store_true", help="whether to visualize on browser") args = parser.parse_args() if args.visualize: server.launch() else: coops = np.arange(0.0, 1.1, 0.1) ## TESTING ## # coops = [0.5] ############# e_prob = 0.5 for coop in coops: print("Simulating with cooperation level %.2f" % (coop)) f_name = "logs/log_%d" % (coop * 100) with open(f_name, 'w+') as f: for _ in range(NUM_SIMULATIONS): model = World(100, coop, e_prob) while model.schedule.time < 3000 and len( model.schedule.agents) != 0: # simulate till there are agents in the world model.step() # explorer mean age mean_explorer_age = np.mean( [model.ages[i] for i in model.ages if "explorer" in i]) # exploiter mean age mean_exploiter_age = np.mean([ model.ages[i] for i in model.ages if "exploiter" in i ]) # entire population mean age mean_age = np.mean([model.ages[i] for i in model.ages]) # mean expected age based on initial values expected_age = np.mean(model.expected_ages) ages = ', '.join([str(model.ages[i]) for i in model.ages]) memoryLens = ', '.join( [str(model.memoryLens[i]) for i in model.memoryLens]) total_energy = ', '.join( [str(i) for i in model.energy_tracker]) num_explorers = ', '.join( [str(i[0]) for i in model.member_tracker]) num_exploiters = ', '.join( [str(i[1]) for i in model.member_tracker]) f.write("ages, " + ages + "\n") f.write("memoryLens, " + memoryLens + "\n") f.write("total_energy, " + total_energy + "\n") f.write("num_explorers, " + num_explorers + "\n") f.write("num_exploiters, " + num_exploiters + "\n") f.write("%.5f, %.5f, %.5f, %.5f\n" % (mean_explorer_age, mean_exploiter_age, mean_age, expected_age))
def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.BLACK) self.world = World(width, height) self.gold_sprite = ModelSprite('images/Gold.png', model=self.world.gold) self.ship_sprite = ModelSprite('images/ship.png', model=self.world.ship)
def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.BLACK) self.world = World(SCREEN_WIDTH, SCREEN_HEIGHT) self.snake_sprite = ModelSprite('images/block.png', model=self.world.snake) self.snake_sprite = SnakeSprite(self.world.snake) self.heart_sprite = HeartSprite(self.world.heart)
def __init__(self, population, initial_infection_rate, closeness, dimensions, speed, frequency, turns, no_doctors, length_of_immunity, train_new_doctor_frequency): self.my_world = World(population, initial_infection_rate, closeness, dimensions, speed, frequency, turns, no_doctors, length_of_immunity) self.my_world.populate_world(population, initial_infection_rate, closeness) self.infectedCount = [] self.healthyCount = [] self.count = 0 self.frequency = frequency self.train_new_doctor_frequency = train_new_doctor_frequency
def __init__(self, width, height): super().__init__(width, height) self.current_state = INSTRUCTION_PAGE self.score = 0 self.background = arcade.load_texture('images/background.png') self.world = World(width, height) self.player_sprite = ModelSprite('images/soilder.png', model=self.world.player) self.zombie_sprite = ModelSprite('images/zombie.png', model=self.world.zombie) self.laser_sprite = ModelSprite('images/laser1.png', model=self.world.player.bullet)
def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.BLACK) self.world = World(width, height) self.endgame = arcade.Sprite('images/black.png', scale=2) self.hunter_sprite = ModelSprite('images/hunter.png', scale=0.4, model=self.world.hunter) self.bullet_sprite = [] self.pigs_sprites = [] for pig in self.world.pigs: self.pigs_sprites.append( ModelSprite('images/pig.png', scale=0.18, model=pig)) self.foxs_sprites = [] for fox in self.world.foxs: self.foxs_sprites.append( ModelSprite('images/fox.png', scale=0.36, model=fox))
def create_test_world(): world = add(World(name='Test World')) portal = add(Location(name='Portal', world=world)) plaza = add(Location(name='Plaza', world=world)) hotel = add(Location(name='Old Grand Hotel', world=world)) basement = add(Location(name='Hotel Basement', world=world)) add( Path( start=portal, destination=hotel, description= "YOU ARE IN THE HOTEL. THERE'S A DOOR TO THE BASEMENT IN FRONT OF YOU." )) add( Path( start=plaza, destination=hotel, description= "YOU ARE IN THE HOTEL. THERE'S A DOOR TO THE BASEMENT IN FRONT OF YOU." )) add( Path(start=hotel, destination=plaza, description="YOU ARE IN THE PLAZA, FACING THE HOTEL.")) add( Path( start=hotel, destination=basement, description= "YOU ARE IN THE BASEMENT. THERE ARE STAIRS UP TO THE HOTEL LOBBY BEHIND YOU." )) add( Path( start=basement, destination=hotel, description= "YOU ARE IN THE HOTEL LOBBY. THERE'S AN EXIT TO THE PLAZA IN FRONT OF YOU." )) add( Session(code='TestSession1', active=True, current_location=hotel, previous_location=portal)) db.session.commit()
def do(): population = int(e1.get()) initial_infection_rate = float(e2.get()) closeness = int(e3.get()) dimensions = int(e4.get()) speed = int(e5.get()) frequency = int(e6.get()) turns = int(e7.get()) no_doctors = int(e8.get()) train_new_doctor_frequency = int(e9.get()) length_of_immunity = int(e10.get()) widget_list = all_children(master) for item in widget_list: item.pack_forget() myworld = World(population, initial_infection_rate, closeness, dimensions, speed, frequency, turns, no_doctors, length_of_immunity) myworld.populate_world(population, initial_infection_rate, closeness) w = Canvas(master, width=canvas_width, height=canvas_height) w.pack(expand=YES, fill=BOTH) for i in range(turns): update(i, w, myworld) if i % train_new_doctor_frequency == 0: myworld.train_doctor() time.sleep(0.05) mainloop()
class Controller: def __init__(self, sim_rate, fps): self.world = World(self, 1.0/sim_rate) self.view = View(sim_rate = sim_rate, fps = fps, sound = True) self.input_accept = ["human", "ai"] self.callbacks = [] def mainloop(self): self.running = True while (self.running): self.view.handle_events(self, self.world) def input(self, player, action): if (player in self.input_accept): switch = {"shoot": self.world.get_spaceship().shoot, "hyperspace": self.world.get_spaceship().hyperspace, "accelerate": self.world.get_spaceship().accelerate, "turn_left": (self.world.get_spaceship().turn, 1), "turn_right": (self.world.get_spaceship().turn, -1)} try: if (type(switch[action])==tuple): func = switch[action][0] args = switch[action][1:] else: func = switch[action] args = [] func(*args) return True except KeyError: return False else: return True def callback_model_step(self): for c in self.callbacks: c(self, self.world) self.world.collision_detection() self.world.integrate() def gameover(self, score): self.quit() def quit(self): self.running = False
############################## # set up data structure ############################## column_names = ['trial', 'noise', 'A_whether'] df = pd.DataFrame(0.0, index=np.arange(len(trials)), columns=column_names) df['trial'] = trials df['noise'] = noise ############################## # run simulations ############################## w = World() for idx, trial in enumerate(trials): df.loc[idx, 'A_whether'] = w.whether_cause(experiment=experiment, noise=noise, w=w, trial=trial, cause='A', df=df, n_simulations=n_simulations, animate=animate) df['trial'] = df['trial'] + 1 df = df * 1 #logical to integer if record_data:
def __init__(self, sim_rate, fps): self.world = World(self, 1.0/sim_rate) self.view = View(sim_rate = sim_rate, fps = fps, sound = True) self.input_accept = ["human", "ai"] self.callbacks = []
class KurbyWindow(arcade.Window): DELAY = 5 temp_list = [] def __init__(self, width, height): super().__init__(width, height) self.background = arcade.load_texture("images/bgni.jpg") self.world = World(SCREEN_WIDTH, SCREEN_HEIGHT) self.dot_sprite = ModelSprite('images/player.png', model=self.world.player) self.monster_sprite = MonsterSprite(model=self.world.monster) self.coin_sprite = [ CoinSprite(model=self.world.coin[0]), CoinSprite(model=self.world.coin[1]), CoinSprite(model=self.world.coin[2]), CoinSprite(model=self.world.coin[3]), CoinSprite(model=self.world.coin[4]) ] self.bomb_sprite = [ BombSprite(model=self.world.bomb[0]), BombSprite(model=self.world.bomb[1]), BombSprite(model=self.world.bomb[2]) ] self.hp = [ arcade.load_texture("images/pills.png"), arcade.load_texture("images/pills.png"), arcade.load_texture("images/pills.png") ] self.num_hp = 2 self.menus = { 'gameover': arcade.load_texture("images/gameover.png"), 'play': arcade.load_texture("images/play.png") } self.count = 0 self.temp_player = 1 def setup(self): self.background = arcade.load_texture("images/bgni.jpg") self.hp = [ arcade.load_texture("images/pills.png"), arcade.load_texture("images/pills.png"), arcade.load_texture("images/pills.png") ] self.num_hp = 2 self.world.level = 0 self.world.score = 0 self.world.hp = 2 self.world.level_bomb = 5 self.world.level_monster = 2 self.monster_sprite.monster_sprite = arcade.Sprite( 'images/monster.png') self.dot_sprite = ModelSprite('images/player.png', model=self.world.player) def on_key_press(self, key, key_modifiers): if not self.world.is_start(): self.world.start() self.world.on_key_press(key, key_modifiers) if self.world.level >= 3: if self.temp_player == 2: self.temp_player = 1 elif self.temp_player >= 1: self.temp_player = 2 self.dot_sprite = ModelSprite('images/kur' + str(self.temp_player) + '.png', model=self.world.player) def night_back(self): if self.world.level >= 10: self.background = arcade.load_texture("images/bg.jpg") self.monster_sprite.monster_sprite = arcade.Sprite( 'images/monster2.png') def update(self, delta): self.world.update(delta) self.world.limit_screen(SCREEN_WIDTH) self.night_back() def draw_background(self): arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, SCREEN_WIDTH, SCREEN_HEIGHT, self.background) def draw_detail(self): if self.world.level < 10: color = arcade.color.BLACK else: color = arcade.color.WHITE arcade.draw_text( 'Score : ' + str(self.world.score), self.width - 80, self.height - 30, color, 12, ) arcade.draw_text( 'Level : ' + str(self.world.level), self.width - 400, self.height - 30, color, 12, ) arcade.draw_text( 'HP : ', self.width - 400, self.height - 60, color, 12, ) temp = 0 if self.world.hp != self.num_hp: self.hp.pop() self.num_hp = self.world.hp for i in self.hp: arcade.draw_texture_rectangle(self.width - 360 + temp, self.height - 53, 10, 12, i) temp += 15 def draw_high_score(self): arcade.draw_text( ' High Score : ' + str(self.world.high_score_coin), 125, 400, arcade.color.BLACK, 20, ) def on_draw(self): arcade.start_render() self.draw_background() for i in self.coin_sprite: i.draw() self.dot_sprite.draw() self.draw_detail() for j in self.bomb_sprite: j.draw() self.monster_sprite.draw() if len(self.hp) == 0: self.world.die() texture = self.menus['gameover'] arcade.draw_texture_rectangle(self.width // 2, self.height // 2 + 50, texture.width, texture.height, texture, 0) self.draw_high_score() texture = self.menus['play'] arcade.draw_texture_rectangle(self.width // 2, self.height // 2 - 100, texture.width, texture.height, texture, 0) def on_mouse_press(self, x, y, button, modifiers): if len(self.hp) == 0: texture = self.menus['play'] h = self.height // 2 - 100 w = self.width // 2 if w - texture.width // 2 <= x <= w + texture.width // 2: if h - texture.height // 2 <= y <= h + texture.height // 2: self.world.st = True self.setup() self.world.start()
# A module for testing and building simulations without running them through causal inference from model import World import sys ############################## # parameters ############################## # trial = int(sys.argv[1]) # To play a single video make trial an int. To play a series of videos make trial a tuple with the range trial = (0, 19) # A string signifying the experiment file to draw from. The experiment name is the portion of the file string that comes before "_trials" # Make sure the trial numbers in trial correspond to the actual number of trials in the experiment file experiment = '2ball' animate = True ############################## # run simulations ############################## w = World() if isinstance(trial, int): w.simulate(experiment, animate, i) else: for i in range(trial[0], trial[1]): w.simulate(experiment, animate, i)
column_names = ['participant','trial','A_difference','A_how','A_whether','A_sufficient','A_robust','B_difference','B_how','B_whether','B_sufficient','B_robust'] df = pd.DataFrame(0.0, index=np.arange(len(trials)), columns=column_names) df['trial'] = trials df['noise'] = noise df['perturb'] = perturb_robust df['n_simulations'] = n_simulations df['n_simulations_difference'] = n_simulations_difference df['trial'] = df['trial']+1 ############################## # run simulations ############################## w = World() for participant in range(0,n_participants): for idx, trial in enumerate(trials): df.loc[idx, 'A_difference'] = w.difference_cause(w = w, experiment = experiment, noise = noise, trial = trial, cause = 'A', alternatives = ['B'], df = df, n_simulations = n_simulations_difference, animate = animate) if df.loc[idx, 'A_difference'] != 0: df.loc[idx, 'A_how'] = w.how_cause(w = w, experiment = experiment, noise = noise, trial = trial, cause = 'A', df = df, animate = animate) df.loc[idx, 'A_whether'] = w.whether_cause(w = w, experiment = experiment, noise = noise, trial = trial, cause = 'A', df = df, n_simulations = n_simulations, animate = animate) df.loc[idx, 'A_sufficient'] = w.sufficient_cause(w = w, experiment = experiment, noise = noise, trial = trial, cause = 'A', alternatives = ['B'], target = 'E', df = df, n_simulations = n_simulations, animate = animate) df.loc[idx, 'A_robust'] = w.robust_cause(w = w, experiment = experiment, noise = noise, perturb = perturb_robust, trial = trial, cause = 'A', alternatives = ['B'], target = 'E', df = df, n_simulations = n_simulations, animate = animate) df.loc[idx, 'B_difference'] = w.difference_cause(w = w, experiment = experiment, noise = noise, trial = trial, cause = 'B', alternatives = ['A'], df = df, n_simulations = n_simulations_difference, animate = animate) if df.loc[idx, 'B_difference'] != 0:
class Controller: def __init__(self, population, initial_infection_rate, closeness, dimensions, speed, frequency, turns, no_doctors, length_of_immunity, train_new_doctor_frequency): self.my_world = World(population, initial_infection_rate, closeness, dimensions, speed, frequency, turns, no_doctors, length_of_immunity) self.my_world.populate_world(population, initial_infection_rate, closeness) self.infectedCount = [] self.healthyCount = [] self.count = 0 self.frequency = frequency self.train_new_doctor_frequency = train_new_doctor_frequency def runTurn(self, count): self.my_world.update_world(count) if count % self.train_new_doctor_frequency == 0: self.my_world.train_doctor() infected, healthy, doctors = self.my_world.create_coord_list() self.my_world.plot(infected[2:], healthy[2:], doctors, count) plt.savefig('web/snapshots/{}.png'.format(count)) self.infectedCount.append(self.my_world.get_number_infected()) self.healthyCount.append(self.my_world.get_number_well()) return 'snapshots/{}.png'.format(count)
class SpaceGameWindow(arcade.Window): def __init__(self, width, height): super().__init__(width, height) self.current_state = INSTRUCTION_PAGE self.score = 0 self.background = arcade.load_texture('images/background.png') self.world = World(width, height) self.player_sprite = ModelSprite('images/soilder.png', model=self.world.player) self.zombie_sprite = ModelSprite('images/zombie.png', model=self.world.zombie) self.laser_sprite = ModelSprite('images/laser1.png', model=self.world.player.bullet) def on_key_press(self, key, key_modifiers): self.world.on_key_press(key, key_modifiers) if key == arcade.key.P and self.current_state == INSTRUCTION_PAGE: self.current_state = GAME_RUNNING self.world.setStart() elif key == arcade.key.R and self.current_state == GAME_END: self.current_state = GAME_RUNNING self.world.setStart() elif key == arcade.key.Q and self.current_state == GAME_END: exit() def update(self, delta): if self.current_state == GAME_RUNNING: self.score = self.world.player.score self.world.update(delta) if self.world.gameEnd == True: self.current_state = GAME_END def draw_instruction_page(self): arcade.set_background_color(arcade.color.BABY_BLUE) output = "1 MAN STAND" arcade.draw_text(output, 130, 400, arcade.color.WHITE, 70) output = "Press P To Play" arcade.draw_text(output, 310, 300, arcade.color.WHITE, 30) def draw_game(self): arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, SCREEN_WIDTH, SCREEN_HEIGHT, self.background) arcade.set_background_color(arcade.color.BABY_PINK) output = f"Score: {self.score}" arcade.draw_text(output, 730, 630, arcade.color.WHITE, 30) self.player_sprite.draw() self.zombie_sprite.draw() self.zombie_sprite.draw() self.laser_sprite.draw() def draw_game_over(self): arcade.set_background_color(arcade.color.GO_GREEN) output = "GAME OVER" arcade.draw_text(output, 165, 400, arcade.color.WHITE, 70) output = f"Your score is {self.score}" arcade.draw_text(output, 310, 300, arcade.color.WHITE, 30) output = "Press R to restart" arcade.draw_text(output, 205, 200, arcade.color.WHITE, 20) output = "Press Q to quit" arcade.draw_text(output, 515, 200, arcade.color.WHITE, 20) def on_draw(self): arcade.start_render() if self.current_state == INSTRUCTION_PAGE: self.draw_instruction_page() elif self.current_state == GAME_RUNNING: self.draw_game() elif self.current_state == GAME_END: self.draw_game_over()
from model import World import sys """ Takes in experiment and trial to generate a png of each video frame experiment = 'teleport' or '3ball' trial = trial index (remember 0 indexing) """ experiment = sys.argv[1] trial = int(sys.argv[2]) w = World() w.simulate(experiment=experiment, trial=trial, animate=True, save=True)