def test_character_select(self): """ Start up the console and select our charcter then quit """ console = melee.Console(path=DOLPHIN_PATH, slippi_port=12345) controller = melee.Controller(console=console, port=1, type=melee.ControllerType.STANDARD) console.run(iso_path=ISO_PATH) self.assertTrue(console.connect()) self.assertTrue(controller.connect()) first_frame = True while True: gamestate = console.step() if first_frame: self.assertEqual(gamestate.frame, 0) first_frame = False if gamestate.menu_state == melee.enums.Menu.IN_GAME: pass else: melee.MenuHelper.menu_helper_simple(gamestate, controller, melee.Character.FOX, melee.Stage.BATTLEFIELD, "", costume=1, autostart=False, swag=False) if gamestate.menu_state == melee.enums.Menu.CHARACTER_SELECT and (gamestate.frame > 50): self.assertEqual(gamestate.players[1].character_selected, melee.Character.FOX) break console.stop()
def console_setup(self): # Game console self.console = melee.Console(path=SLIPPI_EXECUTABLE_PATH, slippi_address="127.0.0.1", slippi_port=51441, blocking_input=False, polling_mode=False) # Your / Our AI's controller self.ai_controller = melee.Controller( console=self.console, port=AI_PORT, type=melee.ControllerType.STANDARD) self.enemy_controller = melee.Controller( console=self.console, port=ENEMY_PORT, type=melee.ControllerType.STANDARD) signal.signal(signal.SIGINT, self.signal_handler) self.console.run(iso_path=MELEE_ISO) if not self.console.connect(): print("ERROR: Failed to connect to the console.") sys.exit(-1) if not self.ai_controller.connect(): print("ERROR: Failed to connect the controller.") sys.exit(-1) if not self.enemy_controller.connect(): print("ERROR: Failed to connect the controller.") sys.exit(-1) print("Controller connected")
def __init__(self, p, partner=False): self.port = p self.con = melee.Console(path=GAME_PATH) self.pad = melee.Controller(console=self.con, port=p) self.partner = partner if not partner: self.con.run(iso_path=ISO_PATH) print('console connect: {}'.format(self.con.connect())) self.pad.connect() print('test port: {}'.format(p))
def read_file(fname): try: console = melee.Console(is_dolphin=False, path=fname) console.connect() except Exception: return pd.DataFrame() state = console.step() ports = find_ports_for_char(state, CHARACTER) state_list = [] if ports is not [] and len(state.players) == 2: while state is not None: try: state_list += get_row(state, ports) except Exception: pass state = console.step() return pd.DataFrame(state_list)
def start(self): if sys.platform == "linux": dolphin_home_path = str(self.d.slippi_home)+"/" elif sys.platform == "win32": dolphin_home_path = None self.console = melee.Console( path=str(self.d.slippi_bin_path), dolphin_home_path=dolphin_home_path, blocking_input=self.blocking_input, tmp_home_directory=True) # print(self.console.dolphin_home_path) # add to logging later # Configure Dolphin for the correct controller setup, add controllers human_detected = False for i in range(len(self.players)): curr_player = self.players[i] if curr_player.agent_type == "HMN": self.d.set_controller_type(i+1, enums.ControllerType.GCN_ADAPTER) curr_player.controller = melee.Controller(console=self.console, port=i+1, type=melee.ControllerType.GCN_ADAPTER) curr_player.port = i+1 human_detected = True elif curr_player.agent_type in ["AI", "CPU"]: self.d.set_controller_type(i+1, enums.ControllerType.STANDARD) curr_player.controller = melee.Controller(console=self.console, port=i+1) self.menu_control_agent = i curr_player.port = i+1 else: # no player self.d.set_controller_type(i+1, enums.ControllerType.UNPLUGGED) if self.ai_starts_game and not human_detected: self.ai_press_start = True else: self.ai_press_start = False # don't let ai press start without the human player joining in. if self.ai_starts_game and self.ai_press_start: self.players[self.menu_control_agent].press_start = True self.console.run(iso_path=self.iso_path) self.console.connect() [player.controller.connect() for player in self.players if player is not None] self.gamestate = self.console.step()
def test_two_controllers_in_game(self): """ Two controllers, get into game then quit """ console = melee.Console(path=DOLPHIN_PATH, slippi_port=23456) controller_one = melee.Controller(console=console, port=1, type=melee.ControllerType.STANDARD) controller_two = melee.Controller(console=console, port=2, type=melee.ControllerType.STANDARD) console.run(iso_path=ISO_PATH) self.assertTrue(console.connect()) self.assertTrue(controller_one.connect()) self.assertTrue(controller_two.connect()) first_frame = True while True: gamestate = console.step() if first_frame: self.assertEqual(gamestate.frame, 0) first_frame = False if gamestate.menu_state == melee.enums.Menu.IN_GAME: self.assertEqual(gamestate.players[1].character, melee.Character.FOX) self.assertEqual(gamestate.players[2].character, melee.Character.MARTH) break else: melee.MenuHelper.menu_helper_simple(gamestate, controller_one, melee.Character.FOX, melee.Stage.BATTLEFIELD, "", costume=1, autostart=True, swag=False) melee.MenuHelper.menu_helper_simple(gamestate, controller_two, melee.Character.MARTH, melee.Stage.BATTLEFIELD, "", costume=1, autostart=False, swag=False) console.stop()
def read_gamestates(replay_path): print("Reading from ", replay_path) console = melee.Console(is_dolphin=False, allow_old_version=True, path=replay_path) console.connect() gamestate = console.step() port_map = dict(zip(gamestate.player.keys(), [1, 2])) def fix_state(s): s.player = {port_map[p]: v for p, v in s.player.items()} while gamestate: fix_state(gamestate) yield gamestate gamestate = console.step()
def test_read_file(self): """ Load and parse SLP file """ console = melee.Console(is_dolphin=False, allow_old_version=False, path="test_artifacts/test_game_1.slp") self.assertTrue(console.connect()) framecount = 0 while True: gamestate = console.step() framecount += 1 if gamestate is None: self.assertEqual(framecount, 1039) break if gamestate.frame == -123: self.assertEqual(console.slp_version, "3.6.1") self.assertEqual(gamestate.players[1].character.value, 1) self.assertEqual(gamestate.players[2].character.value, 1) if gamestate.frame == 297: self.assertEqual(gamestate.players[1].action.value, 0) self.assertEqual(gamestate.players[2].action.value, 27) self.assertEqual(gamestate.players[1].percent, 17) self.assertEqual(gamestate.players[2].percent, 0)
def test_read_old_file(self): """ Load and parse old SLP file """ console = melee.Console(is_dolphin=False, allow_old_version=True, path="test_artifacts/test_game_2.slp") self.assertTrue(console.connect()) framecount = 0 while True: gamestate = console.step() framecount += 1 if gamestate is None: self.assertEqual(framecount, 3840) break if gamestate.frame == -123: self.assertEqual(console.slp_version, "2.0.1") self.assertEqual(gamestate.players[2].character.value, 3) self.assertEqual(gamestate.players[3].character.value, 18) if gamestate.frame == 301: self.assertEqual(gamestate.players[2].action.value, 88) self.assertEqual(gamestate.players[3].action.value, 56) self.assertEqual(gamestate.players[2].percent, 25) self.assertEqual(gamestate.players[3].percent, 0)
# Effectively runs it twice per second tornado.ioloop.IOLoop.current().call_later(delay=1 / 2, callback=refresh_prediction) global gamestate gamestate = console.step() # Keep grabbing gamestates until it returns None. So we know it's the latest # We're using polling mode, so we need to while gamestate: new_gamestate = console.step() if new_gamestate is None: break gamestate = new_gamestate if __name__ == "__main__": console = melee.Console(path=args.dolphin_path, polling_mode=True) print("Connecting to console...") console.run() model = AdvantageBarModel() model.load() time.sleep(2) if not console.connect(): print("ERROR: Failed to connect to the console.") sys.exit(-1) print("Connected!") app = make_app()
plat_top[0], plat_top[1], plat_right[0], plat_right[1]] else: # player is on right side of the screen ordered = [plat_right[0], plat_right[1], plat_top[0], plat_top[1], plat_left[0], plat_left[1]] client.send( OSCMessage("/platforms", ordered) ) # print(ordered) # Port assignment playerPort = 2 enemyPort = 1 # Creates a console object that represents Slippi Online / Dolphin instance. console = melee.Console(path="C:/Users/Michael/Documents/_Spring 2021/Music and Tech 2/FM-Slippi-2.2.5-Win") # Note: File path must use forward slashes or double back slashes. # Single back slashes will result in unicode error. # Creates controller objects for the bot (port 1) and the human (port 2). controller_bot = melee.Controller(console=console, port=enemyPort) controller_human = melee.Controller(console=console, port=playerPort, type=melee.ControllerType.GCN_ADAPTER) # Runs the Dolphin instance and connects the program code to it. console.run() console.connect() # "Plugs in" the controllers for the bot and human. controller_bot.connect() controller_human.connect() ############################### ########## Main Loop ##########
def test_two_controllers_in_game(self): """ Two controllers, get into game """ console = melee.Console(path=DOLPHIN_PATH, slippi_port=23456) controller_one = melee.Controller(console=console, port=1, type=melee.ControllerType.STANDARD) controller_two = melee.Controller(console=console, port=2, type=melee.ControllerType.STANDARD) console.run(iso_path=ISO_PATH) self.assertTrue(console.connect()) self.assertTrue(controller_one.connect()) self.assertTrue(controller_two.connect()) first_frame = True while True: gamestate = console.step() if first_frame: self.assertEqual(gamestate.frame, 0) first_frame = False if gamestate.menu_state == melee.enums.Menu.IN_GAME: if gamestate.frame == -123: self.assertEqual(gamestate.players[1].character, melee.Character.FOX) self.assertEqual(gamestate.players[2].character, melee.Character.MARTH) self.assertEqual(gamestate.stage, melee.Stage.FINAL_DESTINATION) elif gamestate.frame == 20: # Do a shine controller_one.press_button(melee.Button.BUTTON_B) controller_one.tilt_analog(melee.Button.BUTTON_MAIN, 0.5, 0) # Dash forward (left) controller_two.tilt_analog(melee.Button.BUTTON_MAIN, 0, 0.5) elif gamestate.frame == 21: self.assertEqual(gamestate.players[1].action, melee.Action.DOWN_B_GROUND_START) self.assertEqual(gamestate.players[1].action_frame, 1) self.assertEqual(gamestate.players[2].action, melee.Action.DASHING) self.assertEqual(gamestate.players[2].action_frame, 1) self.assertTrue(gamestate.players[2].moonwalkwarning) controller_one.release_all() controller_two.tilt_analog(melee.Button.BUTTON_MAIN, 0.2, 0.5) elif gamestate.frame == 22: # self.assertAlmostEqual(gamestate.players[2].controller_state.main_stick[0], 0.018750011920928955) controller_one.release_all() controller_two.tilt_analog(melee.Button.BUTTON_MAIN, 0.5, 0.5) elif gamestate.frame == 23: controller_one.release_all() controller_two.tilt_analog(melee.Button.BUTTON_MAIN, 0.7, 0.5) elif gamestate.frame == 24: controller_one.release_all() controller_two.tilt_analog(melee.Button.BUTTON_MAIN, 1, 0.5) elif gamestate.frame == 25: controller_one.release_all() controller_two.tilt_analog(melee.Button.BUTTON_MAIN, 0, 0.5) elif gamestate.frame == 35: # Last frame of pivot turn self.assertEqual(gamestate.players[2].action, melee.Action.TURNING) controller_one.release_all() controller_two.release_all() elif gamestate.frame == 36: # This is the first frame of standing after the pivot turn self.assertEqual(gamestate.players[2].action, melee.Action.STANDING) controller_one.release_all() controller_two.press_shoulder(melee.Button.BUTTON_L, 1) elif gamestate.frame == 37: controller_one.release_all() controller_two.press_shoulder(melee.Button.BUTTON_L, 0.8) elif gamestate.frame == 38: controller_one.release_all() controller_two.press_shoulder(melee.Button.BUTTON_L, 0.3) else: controller_one.release_all() controller_two.release_all() if gamestate.frame == 60: break else: melee.MenuHelper.menu_helper_simple( gamestate, controller_one, melee.Character.FOX, melee.Stage.FINAL_DESTINATION, "", costume=1, autostart=True, swag=False) melee.MenuHelper.menu_helper_simple( gamestate, controller_two, melee.Character.MARTH, melee.Stage.FINAL_DESTINATION, "", costume=1, autostart=False, swag=False) console.stop()
#!/usr/bin/python3 import melee console = melee.Console(is_dolphin=False, allow_old_version=False, path="PATH_TO_SLP_FILE") console.connect() while True: gamestate = console.step() # step() returns None when the file ends if gamestate is None: break print("Frame " + str(gamestate.frame)) for _, player in gamestate.player.items(): print("\t", player.stock, player.percent)
f.write("%s\n" % bad_file.path) if args.delete: with open("bad_files.txt", "r") as ifile: for line in ifile: os.remove(line.strip()) print(line) if args.files: num_files = len([f for f in os.listdir(args.files)if os.path.isfile(os.path.join(args.files, f))]) bar = progressbar.ProgressBar(maxval=num_files) for entry in bar(os.scandir(args.files)): console = None try: console = melee.Console(is_dolphin=False, path=entry.path, allow_old_version=True) except Exception as ex: record_bad_file(entry) continue try: console.connect() except Exception as ex: record_bad_file(entry) continue ports = None percents = (0,0) damage = 0 try: # Iterate through each frame of the game frame_count = 0
from melee.enums import Action, Button import keyboard import math from melee import framedata from melee.framedata import FrameData from strategies.defensive import Defense from recovering.recovery import Recover from recovering.recovery import getEdgeDist from tech.chain_ws import ChainWaveShines from tech.waveshine import WaveShine from tech.multishine import MultiShine from tech.smashattack import SmashAttack from tech.intumble import InTumble from tech.dashdance import DashDance from config import slippilocation console = melee.Console(path=slippilocation) controller = melee.Controller(console=console, port=1, type=melee.ControllerType.STANDARD) console.run() console.connect() controller.connect() chainshine = ChainWaveShines() defense = Defense() tumbleCheck = InTumble() smashhh = SmashAttack() frmData = framedata.FrameData() dashDance = DashDance()
args = parser.parse_args() # This logger object is useful for retroactively debugging issues in your bot # You can write things to it each frame, and it will create a CSV file describing the match log = None if args.debug: log = melee.Logger() # Create our Console object. # This will be one of the primary objects that we will interface with. # The Console represents the virtual or hardware system Melee is playing on. # Through this object, we can get "GameState" objects per-frame so that your # bot can actually "see" what's happening in the game console = melee.Console(path=args.dolphin_executable_path, slippi_address=args.address, logger=log) # Create our Controller object # The controller is the second primary object your bot will interact with # Your controller is your way of sending button presses to the game, whether # virtual or physical. controller = melee.Controller(console=console, port=args.port, type=melee.ControllerType.STANDARD, verbose=args.verbose) controller_opponent = melee.Controller(console=console, port=args.opponent, type=melee.ControllerType.STANDARD, ai=True,
callback=refresh_prediction) global gamestate gamestate = console.step() # Keep grabbing gamestates until it returns None. So we know it's the latest # We're using polling mode, so we need to while gamestate: new_gamestate = console.step() if new_gamestate is None: break gamestate = new_gamestate if __name__ == "__main__": console = melee.Console(path=args.dolphin_path, slippi_address="127.0.0.1", slippi_port=51441, blocking_input=False, polling_mode=True, logger=None) print("Connecting to console...") console.run() model = AdvantageBarModel() model.load() time.sleep(2) if not console.connect(): print("ERROR: Failed to connect to the console.") sys.exit(-1) print("Connected!")
.tfrecord files located in tfrecords/ folder """ print("Building dataset...") directory = 'training_data/' num_files = len([ f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) ]) bar = progressbar.ProgressBar(maxval=num_files) for entry in bar(os.scandir(directory)): frames = [] if entry.path.endswith(".slp") and entry.is_file(): console = None try: console = melee.Console(is_dolphin=False, path=entry.path, allow_old_version=True) except Exception as ex: print("Got error, skipping file", ex) continue try: console.connect() except ubjson.decoder.DecoderException as ex: print("Got error, skipping file", ex) continue stocks = (4, 4) # Pick a game to be part of the evaluation set 20% of the time is_evaluation = random.random() > 0.8 # Temp holder of frames, until a stock is lost frames_temp = [] game_winner = -1
volume = int(split[1].strip()) if volume > 100: volume = 100 elif volume < 0: volume = 0 except valueError: input( 'There was an error parsing the volume in the config file! Should be "volume = [num]! Press enter to exit...' ) sys.exit(-1) elif var == "menu": menu = split[1].strip().lower()[0] in ["y", "t"] elif var == "iso_path": iso_path = os.path.normpath(split[1].strip()) console = melee.Console(path=path, slippi_port=port, volume=volume, menu=menu) # This isn't necessary, but makes it so that Dolphin will get killed when you ^C def signal_handler(sig, frame): console.stop() print("Shutting down cleanly...") sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Run the console if (path): console.run(iso_path=iso_path)
import melee import keyboard import math console = melee.Console(path=r"E:\Documents\3rdYear\Project\FM-Slippi") controller = melee.Controller(console=console, port=1, type=melee.ControllerType.STANDARD) console.run() console.connect() controller.connect() def atk_normal(controller, axis, dir): controller.press_button(melee.enums.Button.BUTTON_A) if (axis == "vert"): controller.tilt_analog(melee.enums.Button.BUTTON_MAIN, 0.5, dir) elif (axis == "hori"): controller.tilt_analog(melee.enums.Button.BUTTON_MAIN, dir, 0.5) else: controller.tilt_analog(melee.enums.Button.BUTTON_MAIN, 0.5, 0.5) def atk_special(controller, dir, strength): controller.press_button(melee.enums.Button.BUTTON_B) if (dir == "y"): controller.tilt_analog(melee.enums.Button.BUTTON_MAIN, 0.5, strength) elif (dir == "x"): controller.tilt_analog(melee.enums.Button.BUTTON_MAIN, strength, 0.5) else: controller.tilt_analog(melee.enums.Button.BUTTON_MAIN, 0.5, 0.5)
# "projectile5_x": [], # "projectile5_y": [], # "projectile5_x_speed": [], # "projectile5_y_speed": [], # "projectile5_owner": [], # "projectile5_subtype": [], "stage": [], "frame": [], "stock_winner": [], "game_winner": [] } if entry.path.endswith(".slp") and entry.is_file(): console = None try: console = melee.Console(is_dolphin=False, path=entry.path, allow_old_version=True) except Exception as ex: print("Got error, skipping file", ex) continue try: console.connect() except ubjson.decoder.DecoderException as ex: print("Got error, skipping file", ex) continue stocks = (4, 4) ports = None # Pick a game to be part of the evaluation set 20% of the time is_evaluation = random.random() > 0.8 game_winner = -1
def main(saved_model_path, dolphin_path, iso_path, _log): embed_game = embed.make_game_embedding() policy = tf.saved_model.load(saved_model_path) sample = lambda *structs: policy.sample(*tf.nest.flatten(structs)) hidden_state = policy.initial_state(1) console = melee.Console(path=dolphin_path) # This isn't necessary, but makes it so that Dolphin will get killed when you ^C def signal_handler(sig, frame): console.stop() print("Shutting down cleanly...") # sys.exit(0) signal.signal(signal.SIGINT, signal_handler) controller = melee.Controller(console=console, port=1, type=melee.ControllerType.STANDARD) cpu_controller = melee.Controller(console=console, port=2, type=melee.ControllerType.STANDARD) # Run the console console.run(iso_path=iso_path) # Connect to the console _log.info("Connecting to console...") if not console.connect(): _log.error("Failed to connect to the console.") return _log.info("Console connected") for c in [controller, cpu_controller]: print("Connecting controller to console...") if not c.connect(): print("ERROR: Failed to connect the controller.") sys.exit(-1) print("Controller connected") action_repeat = 0 repeats_left = 0 # Main loop while True: # "step" to the next frame gamestate = console.step() if gamestate is None: continue if gamestate.frame == -123: # initial frame controller.release_all() # The console object keeps track of how long your bot is taking to process frames # And can warn you if it's taking too long if console.processingtime * 1000 > 12: print("WARNING: Last frame took " + str(console.processingtime * 1000) + "ms to process.") # What menu are we in? if gamestate.menu_state in [ melee.Menu.IN_GAME, melee.Menu.SUDDEN_DEATH ]: if repeats_left > 0: repeats_left -= 1 continue embedded_game = embed_game.from_state(gamestate), action_repeat batched_game = tf.nest.map_structure( lambda a: np.expand_dims(a, 0), embedded_game) sampled_controller_with_repeat, hidden_state = sample( batched_game, hidden_state) sampled_controller_with_repeat = tf.nest.map_structure( lambda t: np.squeeze(t.numpy(), 0), sampled_controller_with_repeat) sampled_controller = sampled_controller_with_repeat['controller'] action_repeat = sampled_controller_with_repeat['action_repeat'] repeats_left = action_repeat for b in embed.LEGAL_BUTTONS: if sampled_controller['button'][b.value]: controller.press_button(b) else: controller.release_button(b) main_stick = sampled_controller["main_stick"] controller.tilt_analog(melee.Button.BUTTON_MAIN, *main_stick) c_stick = sampled_controller["c_stick"] controller.tilt_analog(melee.Button.BUTTON_C, *c_stick) controller.press_shoulder(melee.Button.BUTTON_L, sampled_controller["l_shoulder"]) controller.press_shoulder(melee.Button.BUTTON_R, sampled_controller["r_shoulder"]) else: melee.MenuHelper.menu_helper_simple(gamestate, controller, melee.Character.FOX, melee.Stage.YOSHIS_STORY, connect_code=None, autostart=False, swag=False) melee.MenuHelper.menu_helper_simple(gamestate, cpu_controller, melee.Character.FOX, melee.Stage.YOSHIS_STORY, connect_code=None, cpu_level=9, autostart=True, swag=False)
log = None if args.debug: log = melee.Logger() # This frame data object contains lots of helper functions and values for looking up # various Melee stats, hitboxes, and physics calculations framedata = melee.FrameData(args.framerecord) # Create our Console object. # This will be one of the primary objects that we will interface with. # The Console represents the virtual or hardware system Melee is playing on. # Through this object, we can get "GameState" objects per-frame so that your # bot can actually "see" what's happening in the game console = melee.Console(path=args.dolphin_executable_path, slippi_address=args.address, slippi_port=51441, blocking_input=False, logger=log) # Dolphin has an optional mode to not render the game's visuals # This is useful for BotvBot matches console.render = True # Create our Controller object # The controller is the second primary object your bot will interact with # Your controller is your way of sending button presses to the game, whether # virtual or physical. controller = melee.Controller(console=console, port=args.port, type=melee.ControllerType.STANDARD)
#!/usr/bin/python3 import melee console = melee.Console(is_dolphin=False, allow_old_version=False, path="/home/altf4/Slippi/Game_20200707T155649.slp" # path="/home/altf4/Code/smashbot_analysis/training_data/18_46_54 Fox + [OASI] Captain Falcon (BF).slp" ) console.connect() while True: gamestate = console.step() # step() returns None when the file ends if gamestate is None: break # print(gamestate.player) print(gamestate.frame, gamestate.player[1].stock, gamestate.player[2].stock)