Beispiel #1
0
 def __init__(self, parent=None):
     super(MainWindow, self).__init__(parent=parent)
     self.setupUi(self)
     self.buttonLoad.clicked.connect(self.load_replay)
     self.buttonRun.clicked.connect(self.extract_build_order)
     self.setWindowTitle(
         f"ElementTD 2 Build Order Extractor v{cfg.version_string}")
     self.pfn_replay = None
     self.replay = replay.Replay()
 def __init__(self, replay="last_game_replay"):
     """
     @param replay: replay path
     @type replay: str
     @rtype: None
     """
     if os.path.isfile(replay):
         self.replay = rp.Replay(path=replay)
         state_game.StateGame.__init__(self, self.replay.get_opts(), ["GAME_REPLAY", "MAIN_MENU"], self.replay.seed)
    def __init__(self):
        """
        @rtype: None
        """
        # generate a random seed
        seed = random.randrange(maxsize)

        state_game.StateGame.__init__(self, load_options(),
                                      ["GAME", "MAIN_MENU"], seed)

        self.replay = rp.Replay(seed=seed)
        self.replay.set_opts(self.current_opts)
Beispiel #4
0
def run_login_sync(test, params, env):
  """
  login synchronization
  using login_sync.st to replay keyboard event
  """
  timeout = params["running_timeout"]
  vms = env.get_all_vms()
  for vm in vms:
    vm.wait_for_running(int(timeout))
    sock = create_socket("140.115.53.42","5566")
    t = threading.Thread(target=open_socket, args = (sock,))
    t.start()
    replay.Replay(vm.name, "login_sync")
    t.join()
    result = check_queue()
    if not result:
      raise Exception("login not synchronization")
  return result
Beispiel #5
0
    def __init__(self,
                 config,
                 num_actions,
                 train_env,
                 train_stats,
                 eval_env,
                 eval_stats,
                 is_demo=False,
                 run_name=None):
        sess = tf.Session()

        self.network = self.create_network(config, num_actions, is_demo,
                                           run_name)
        self.train_env = train_env
        self.train_stats = train_stats
        self.eval_env = eval_env
        self.eval_stats = eval_stats

        self.replay = replay.Replay(sess, config['memory_capacity'],
                                    config['screen_dims'],
                                    config['history_length'],
                                    config['batch_size'], num_actions)

        sess.run(tf.global_variables_initializer())

        self.num_actions = num_actions
        self.history_length = config['history_length']
        self.initial_replay_size = config['initial_replay_size']
        self.training_freq = config['training_freq']
        self.eval_freq = config['eval_freq']
        self.num_eval_episodes = config['num_eval_episodes']
        self.max_steps_per_eval_episode = config['max_steps_per_eval_episode']
        self.eval_epsilon = config['eval_epsilon']
        self.epsilons = np.linspace(config['epsilon_start'],
                                    config['epsilon_end'],
                                    config['epsilon_decay_steps'])
        self.epsilon_decay_steps = config['epsilon_decay_steps']
        self.summary_freq = config['summary_freq']
        self.reward_processing = config['reward_processing']
Beispiel #6
0
def threadedAnalysis(path):
    with open(path, "rb") as game:
            print(path + ' starting...', end="")
            bin = replay.Replay(game.read()) 
            time = path[-26:-10].replace('h',':')
            time = time[:10] + ' ' + time[11:]
            meaningfulStates = []
            actualPlayers = {}
            startingGameTime = 0
            matchLengthInTicks = 0
            tickCounter = 0
            goals = []
            score = {
                'Red' : 0,
                'Blue': 0
            }

            if bin[1][0].gameTime is not None:
                score = {
                    'Red': bin[1][0].score[0],
                    'Blue': bin[1][0].score[1],
                }
                startingGameTime = bin[1][0].gameTime

            for tick in bin[1]:
                if tick.state.value >= 3:
                    for player in tick.players:
                        if player.id not in actualPlayers:
                            actualPlayers[player.id] = {'team': player.team.name, 'ticks': 0}
                        actualPlayers[player.id]['team'] = player.team.name
                        actualPlayers[player.id]['ticks'] = actualPlayers[player.id]['ticks'] + 1
                    matchLengthInTicks += 1
                    meaningfulStates.append(tick)
                
                if (tick.state.value == 4 and bin[1][tickCounter-1].state.value == 3 and tickCounter != 0):
                    if (bin[1][tickCounter-1].score[0] == tick.score[0] and bin[1][tickCounter-1].score[1] == tick.score[1]): 
                        tickCounter+=1
                        continue
                    goalScorerId = -1
                    goalShotTime = 0
                    # TODO: goalShotSpeed
                    goalSide = "Red"
                    if (bin[1][tickCounter-1].score[0] == tick.score[0]):
                        goalSide = "Blue"
                    for i in reversed(range(tickCounter-1)):
                        if goalScorerId != -1:
                            break
                        targetTick = bin[1][i]
                        for player in targetTick.players:
                            if player.team.name != goalSide:    
                                continue

                            distanceFromBall = calculateDistance(targetTick.ball.x, targetTick.ball.y, player.disc.x, player.disc.y)
                            if distanceFromBall < 30 and hasVectorChanged(targetTick.ball, bin[1][i+1].ball):
                                goalScorerId = player.id
                                goalShotTime = round(targetTick.gameTime, 3)
                                break
                        
                    goals.append({
                        "goalTime": round(tick.gameTime, 3),
                        "goalScorerName": bin[0][goalScorerId],
                        "goalShotTime": goalShotTime,
                        "goalSide": goalSide,
                        "goalSpeed": round(math.hypot(tick.ball.vy, tick.ball.vx),3),
                        "goalTravelTime": round(tick.gameTime - goalShotTime, 3)
                    })
                    if (goalSide == "Red"):
                        score['Red'] += 1
                    else:
                        score['Blue'] += 1

                tickCounter+=1
            if meaningfulStates.__len__() == 0:
                print(' empty')
                return

            lastState = meaningfulStates[-1:]
            rawPositions = ""
            teams = {'Red': [], 'Blue': []}
            for player in lastState[0].players:
                rawPositions += str(player.disc.x) + "-" + str(player.disc.y) + "|"

            for playerId in actualPlayers:
                if (actualPlayers[playerId]['ticks'] == 0):
                    continue
                for targetPlayerId in actualPlayers:
                    if playerId != targetPlayerId and bin[0][playerId] == bin[0][targetPlayerId]:
                        actualPlayers[playerId]['ticks'] += actualPlayers[targetPlayerId]['ticks']
                        actualPlayers[targetPlayerId]['ticks'] = 0
                if (actualPlayers[playerId]['ticks'] / matchLengthInTicks > 0.6):
                    teams[actualPlayers[playerId]['team']].append(bin[0][playerId])
                
            saveData = {
                'startingGameTime': round(startingGameTime,3),
                'gameTime': round(lastState[0].gameTime, 3),
                'time': time,
                'teams': teams,
                'goalsData': goals,
                'score': score,
                'rawPositionsAtEnd': rawPositions
            }

            print(' processed')
            s = json.dumps(saveData, default=lambda x: x.__dict__, sort_keys=True, indent=4)
            with open('../files/replayData/' + path[13:] + '.json', 'w+') as f:
                f.write(s)
Beispiel #7
0
    sock = create_socket("140.115.53.42","5566")
    t = threading.Thread(target=open_socket, args = (sock,))
    t.start()
    replay.Replay(vm.name, "login_sync")
    t.join()
    result = check_queue()
    if not result:
      raise Exception("login not synchronization")
  return result



if __name__ == '__main__':
  sock = create_socket("140.115.53.42","5566")
  print "test\n"
  t = threading.Thread(target=open_socket, args = (sock,))
  t.start()
  print "test1\n"
  #subprocess.call("virsh qemu-monitor-command --hmp FTtest sendkey 1", shell = True)
  #subprocess.call("virsh qemu-monitor-command --hmp FTtest sendkey 2", shell = True)
  #subprocess.call("virsh qemu-monitor-command --hmp FTtest sendkey 3", shell = True)
  #subprocess.call("virsh qemu-monitor-command --hmp FTtest sendkey kp_enter", shell = True)
  replay.Replay("FTtest","login_sync")
  print "thread :",t.is_alive(),"\n"
  t.join()
  print "thread :",t.is_alive(),"\n"
  while not msg_q.empty():
    print msg_q.get()+"\n"


Beispiel #8
0
#addons.py
import replay
addons = [
    replay.Replay(),
]
Beispiel #9
0
    def __init__(self, root):
        # start the game engine
        self.game = g_eng.GameEngine()

        # root frame of tkinter
        self.root = root

        # creates top menu
        self.create_menu()

        # score label
        self.score_str = StringVar()
        self.score_str.set("Score: 0")

        label = Label(self.root, textvariable=self.score_str)
        label.grid(row=0, column=0, columnspan=2)

        # game areas, first area is the perspective view,
        # the other two areas are the orthographic 2d projections of the game
        # the project flat class inverts the y axis, so that when pressing
        # wasd or ijkl the direction match the keyboard

        self.areas = []

        # area 0 - perspective
        proj = visu.ProjectCam()
        area4 = visu.VisuArea(root, proj, [500, 500])
        area4.fP.grid(row=1, column=0, columnspan=2)
        self.areas.append(area4)

        # area 1 - 2d projection of the yx axis
        proj = visu.ProjectFlat("yx")
        proj.zoom = 0.5
        area_xy = visu.VisuArea(root, proj, [250, 250], "YX")
        area_xy.fP.grid(row=2, column=0)
        self.areas.append(area_xy)

        # area 2 - 2d projection of the wz axis
        proj = visu.ProjectFlat("wz")
        proj.zoom = 0.5
        area_wz = visu.VisuArea(root, proj, [250, 250], "WZ")
        area_wz.fP.grid(row=2, column=1)
        self.areas.append(area_wz)

        # snake movements

        # moving keys pressed wasd, ijkl
        bind_key = ["w", "s", "a", "d", "i", "k", "j", "l"]
        for key in bind_key:
            self.root.bind(key, self.move)

        # scene rotations - both + and - roations are supported, pressing x
        # will rotate the scene in a direction and pressing X (shift+x) will
        # rotate backwards in respect to that direction
        # x, y, c: 3d rotations
        # v, b, n, m, t, z: 4d rotations
        self.rot3k_to_angle = self.set_rotation_keys("xyc")
        self.rot4k_to_angle = self.set_rotation_keys("vbnmtz")

        # the buffered key press
        self.key_buffer = keybuf.KeyBuffer()

        # pause function
        self.paused = True
        self.root.bind("p", self.toggle_pause)

        # new game function
        self.root.bind("<space>", self.new_game)

        # adds a central text to the first area for instructions
        self.areas[0].add_text("Press any key to play")

        # the scores, which are saved in score.txt
        self.score_board = score.ScoreBoard(self.root)
        
        # creates the replay settings
        self.replay = replay.Replay(self.game)