예제 #1
0
def getLaunchConfig(options):
    player = PlayerPreGame(getPlayer(options.player),
                           selectedRace=options.race,
                           observe=options.observe)
    ret = Config(  # create game config
        expo=c.EXPO_SELECT[options.exp],
        version=options.version,
        ladder=getLadder(options.ladder),
        players=[player],
        whichPlayer=player.name,
        mode=c.types.GameModes(options.mode),
        themap=options.map,  # or selectMap(options.map),
        numObservers=options.obs,
        trust=True,
        #slaves      = [],
        fogDisabled=options.nofog,
        stepSize=options.step,
        opponents=options.opponents.split(',') if options.opponents else [],
        fullscreen=not options.windowed,
        raw=options.raw,
        score=options.score,
        feature=options.feature,
        render=options.rendered,
        #resolution
        #minimap
        #layerwidth
        #replay      = options.replay,
        #debug       = options.debug,
    )
    ret.connection  # force generation of IP address and ports attributes
    return ret
예제 #2
0
                                  metavar=" NAME")
    optionsCriteria = parser.add_argument_group('critiera used when --add')
    optionsCriteria.add_argument(
        'criteria',
        nargs='*',
        help="remaining arguments for the specified action.")
    options = parser.parse_args()
    if options.add:
        terms = [a.split('=') for a in options.criteria]
        kwargs = {}
        try:  # translate options.criteria into a dictionary
            for i, (k, v) in enumerate(terms):
                kwargs[
                    k] = v  # to ensure 'i' is available for a potential error message, don't use a generator
            if True: print(addLadder(kwargs))
        except ValueError:
            print(
                "ERROR: key '%s' must specify a value using '=' followed by a value (no whitespace)."
                % (terms[i][0]))
    elif options.get:
        print(getLadder(options.get))
    elif options.rm:
        print(delLadder(options.rm))
    else:
        for ladder in defs.values():
            print("object:", ladder)
            for k, v in ladder.attrs.items():
                print("%24s : %s" % (k, v))
        if defs: print("Found %d ladder definition(s)" % (len(defs)))
        else: print("No ladder definitions are available.")
예제 #3
0
def main(options=None):
    if options == None:  # if not provided, assume options are provided via command line
        parser = optionsParser()
        options = parser.parse_args()
        sys.argv = sys.argv[:
                            1]  # remove all arguments to avoid problems with absl FLAGS :(
    try:
        specifiedMap = selectMap(
            options.mapname,
            excludeName=options.exclude,
            closestMatch=True,  # force selection of at most one map
            **getSelectionParams(options))
    except Exception as e:
        print(e)
        return
    outTempName = specifiedMap.name + "_%d_%d." + c.SC2_REPLAY_EXT
    outTemplate = os.path.join(options.replaydir, outTempName)
    if options.editor:
        bankFile = getBankFilepath(specifiedMap.name)
        if os.path.isfile(bankFile):  # this map has saved previous scenarios
            bankName = re.sub("\..*?$", "", os.path.basename(bankFile))
            bankDir = os.path.dirname(bankFile)
            dirTime = re.sub("\.", "_", str(time.time()))
            tmpDir = os.path.join(bankDir, "%s_%s" % (bankName, dirTime))
            tmpXml = os.path.join(tmpDir, c.FILE_BANKLIST)
            tmpName = "%s.%s" % (bankName, c.SC2_MAP_EXT)
            tmpMapPath = os.path.join(tmpDir, tmpName)
            cfg = Config()
            dstMapDir = cfg.installedApp.mapsDir
            dstMapPath = os.path.join(dstMapDir, tmpName)
            if os.path.isdir(tmpDir):
                shutil.rmtree(tmpDir)
            try:
                os.makedirs(tmpDir)
                shutil.copyfile(
                    specifiedMap.path,
                    tmpMapPath)  # copy the original map file for modification
                with open(tmpXml, "w") as f:  # generate temporary xml data
                    f.write(c.BANK_DATA % bankName)
                if cfg.is64bit: mpqApp = c.PATH_MPQ_EDITOR_64BIT
                else: mpqApp = c.PATH_MPQ_EDITOR_32BIT
                cmd = c.MPQ_CMD % (mpqApp, tmpMapPath, tmpXml, c.FILE_BANKLIST)
                x = subprocess.call(
                    cmd)  # modify a temporary mapfile using the mpq editor
                print("Loaded previously defined %s scenarios." % (bankName))
                if os.path.isfile(
                        dstMapPath
                ):  # always ensure the destination mapfile is the modified version
                    os.remove(dstMapPath)
                shutil.copyfile(
                    tmpMapPath, dstMapPath
                )  # relocate the temporary map file into the maps folder
                tmpRecord = MapRecord(specifiedMap.name, dstMapPath, {})
                launchEditor(
                    tmpRecord
                )  # launch the editor using a temporary, modified map that includes the previously defined SC2Bank scenario data
            finally:
                time.sleep(
                    options.cleandelay
                )  # wait for the editor to launch before removing temporary files
                if os.path.isdir(
                        tmpDir
                ):  # always remove the temporary map and XML files
                    shutil.rmtree(tmpDir)
                while True:
                    try:
                        os.remove(dstMapPath
                                  )  # always remove the temporary map mpq file
                        break
                    except:
                        time.sleep(
                            2
                        )  # continue trying until the editor closes and the deletion is successful
        else:
            launchEditor(
                specifiedMap)  # run the editor using the game modification
    elif options.regression:
        batteries = options.test.split(",")
        raise NotImplementedError("TODO -- run each test battery")
    elif options.custom:
        playerNames = re.split("[,\s]+", options.players)
        if len(playerNames) != 2:  # must specify two players for 1v1
            if not options.players:
                playerNames = ""
            raise ValueError("must specify two players, but given %d: '%s'" %
                             (len(playerNames), playerNames))
        try:
            thisPlayer = getPlayer(
                playerNames[0]
            )  # player name stated first is expected to be this player
        except Exception:
            print("ERROR: player '%s' is not known" % playerNames[0])
            return
        if options.race == c.RANDOM:
            options.race = thisPlayer.raceDefault  # defer to a player's specified default race
        cfg = Config(
            themap=specifiedMap,
            ladder=getLadder("versentiedge"),
            players=[
                PlayerPreGame(thisPlayer,
                              selectedRace=c.types.SelectRaces(options.race))
            ],
            mode=c.types.GameModes(c.MODE_1V1),
            opponents=playerNames[1:],
            whichPlayer=thisPlayer.name,
            fogDisabled=
            True,  # disable fog to be able to see, set and remove enemy units
            **
            thisPlayer.initOptions,  # ensure desired data is sent in callback
        )
        cfg.raw = True  # required to be able to set up units using debug commands
        #cfg.display()
        scenarios = getSetup(specifiedMap, options, cfg)
        for scenario in scenarios:
            epoch = int(time.time(
            ))  # used for replay differentiation between each scenario
            failure = False
            for curLoop in range(
                    1, options.repeat + 1
            ):  # each loop of each scenario gets its own unique replay (count starting at one)
                outFile = outTemplate % (epoch, curLoop)
                launchOpts = defineLaunchOptions(scenario, outFile)
                failure = launcher.run(launchOpts, cfg=cfg)
                if failure: break
            if failure: break
    elif options.join:
        raise NotImplementedError("TODO -- implement remote play")
    else:
        parser.print_help()
        print("ERROR: must select a main option.")