csa1 : players? initialboard? moves
177816
def parse_csa1
      s0 = @current_pos
      s1 = parse_players
      s1 = nil if s1 == :failed
      s2 = parse_initial_board
      s2 = nil if s2 == :failed
      s3 = parse_moves
      if s3 != :failed
        @reported_pos = s0
        s0 = -> (ply, ini, ms) do
          ret = { "header" => {}, "initial" => ini, "moves" => ms }
          if ply
            ret["header"]["先手"] = ply[0] if ply[0]
            ret["header"]["後手"] = ply[1] if ply[1]
          end
          ret
        end.call(s1, s2, s3)
      else
        @current_pos = s0
        s0 = :failed
      end
      s0
    end
1214347
function _Platform_initialize(flagDecoder, args, init, update, subscriptions, stepperBuilder)
{
	var result = A2(__Json_run, flagDecoder, __Json_wrap(args ? args['flags'] : undefined));
	__Result_isOk(result) || __Debug_crash(2 /**__DEBUG/, __Json_errorToString(result.a) /**/);
	var managers = {};
	result = init(result.a);
	var model = result.a;
	var stepper = stepperBuilder(sendToApp, model);
	var ports = _Platform_setupEffects(managers, sendToApp);

	function sendToApp(msg, viewMetadata)
	{
		result = A2(update, msg, model);
		stepper(model = result.a, viewMetadata);
		_Platform_dispatchEffects(managers, result.b, subscriptions(model));
	}

	_Platform_dispatchEffects(managers, result.b, subscriptions(model));

	return ports ? { ports: ports } : {};
}
1093078
def parse_moves
      s0 = @current_pos
      s1 = parse_firstboard
      if s1 != :failed
        parse_split
        s2 = []
        s3 = parse_move
        while s3 != :failed
          s2 << s3
          s3 = parse_move
        end
        parse_result
        @reported_pos = s0
        s0 = s2.unshift(s1)
      else
        @current_pos = s0
        s0 = :failed
      end
      s0
    end
280846
def participants(self):
        """"""
        ret = []
        for p in self.players:
            try:
                if     p.isComputer: ret.append(p)
                if not p.isObserver: ret.append(p) # could cause an exception if player isn't a PlayerPreGame
            except AttributeError: pass
        return ret
235309
def play(self):
        
        colors = [lambda: self.white_move(), lambda: self.black_move()]
        colors = itertools.cycle(colors)

        while True:
            color_fn = next(colors)
            if game_state.no_moves(self.position):
                if self.position.get_king(color.white).in_check(self.position):
                    return 1

                elif self.position.get_king(color.black).in_check(self.position):
                    return 0

                else:
                    return 0.5

            color_fn()
1029874
private void initComponents() {

        borderPanel = new javax.swing.JPanel();
        gamePanel = new javax.swing.JPanel();
        inputsPanel = new javax.swing.JPanel();
        buttonPanel = new javax.swing.JPanel();
        guessButton = new javax.swing.JButton();
        replayBtn = new javax.swing.JButton();
        guessText = new javax.swing.JTextField();
        remainingGuessesPanel = new javax.swing.JPanel();
        guessremainLabel = new javax.swing.JLabel();
        guessesLeftBar = new javax.swing.JProgressBar();
        mainMsgPanel = new javax.swing.JPanel();
        mainLabel = new javax.swing.JLabel();
        messageLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.CardLayout());

        borderPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
        borderPanel.setLayout(new java.awt.CardLayout());

        gamePanel.setLayout(new java.awt.BorderLayout(6, 6));

        inputsPanel.setLayout(new java.awt.BorderLayout(8, 8));

        buttonPanel.setLayout(new java.awt.CardLayout());

        guessButton.setText("Guess");
        guessButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guessButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(guessButton, "card2");

        replayBtn.setText("Replay!");
        replayBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                replayBtnActionPerformed(evt);
            }
        });
        buttonPanel.add(replayBtn, "card3");

        inputsPanel.add(buttonPanel, java.awt.BorderLayout.LINE_END);
        inputsPanel.add(guessText, java.awt.BorderLayout.CENTER);

        gamePanel.add(inputsPanel, java.awt.BorderLayout.CENTER);

        remainingGuessesPanel.setLayout(new java.awt.BorderLayout(8, 8));

        guessremainLabel.setText("Guesses remaining:  ");
        remainingGuessesPanel.add(guessremainLabel, java.awt.BorderLayout.LINE_START);

        guessesLeftBar.setMaximum(Game.MAX_NUM_GUESSES);
        guessesLeftBar.setValue(Game.MAX_NUM_GUESSES);
        guessesLeftBar.setPreferredSize(new java.awt.Dimension(10, 14));
        remainingGuessesPanel.add(guessesLeftBar, java.awt.BorderLayout.CENTER);

        gamePanel.add(remainingGuessesPanel, java.awt.BorderLayout.PAGE_END);

        mainMsgPanel.setLayout(new java.awt.GridLayout(2, 1, 6, 6));

        mainLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        mainLabel.setText(msgGenerator.getChallengeMessage());
        mainMsgPanel.add(mainLabel);

        messageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        messageLabel.setText(msgGenerator.getResultMessage());
        mainMsgPanel.add(messageLabel);

        gamePanel.add(mainMsgPanel, java.awt.BorderLayout.PAGE_START);

        borderPanel.add(gamePanel, "card2");

        getContentPane().add(borderPanel, "card2");

        pack();
    }
515488
def imperative_move
      # if we can win *this turn*, then take it because
      # it rates winning next turn the same as winning in 3 turns
      game.available_moves.each do |move|
        new_game = game.pristine_mark move
        return move if new_game.over? && new_game.winner == player_number
      end
      
      # if we can block the opponent from winning *this turn*, then take it, because
      # it rates losing this turn the same as losing in 3 turns
      if moves_by_rating.all? { |move, rating, game| rating == -1 }
        Game.winning_states do |position1, position2, position3|
          a, b, c = board[position1-1, 1].to_i, board[position2-1, 1].to_i, board[position3-1, 1].to_i
          if a + b + c == opponent_number * 2
            return a.zero? ? position1 : b.zero? ? position2 : position3
          end
        end
      end
    end
227366
def setup(self, board: Union[chess.Board, str]) -> None:
        
        try:
            fen = board.fen()
        except AttributeError:
            board = chess.Board(board)
            board.chess960 = board.has_chess960_castling_rights()
            fen = board.fen()

        if fen == type(board).starting_fen:
            self.headers.pop("SetUp", None)
            self.headers.pop("FEN", None)
        else:
            self.headers["SetUp"] = "1"
            self.headers["FEN"] = fen

        if type(board).aliases[0] == "Standard" and board.chess960:
            self.headers["Variant"] = "Chess960"
        elif type(board).aliases[0] != "Standard":
            self.headers["Variant"] = type(board).aliases[0]
            self.headers["FEN"] = board.fen()
        else:
            self.headers.pop("Variant", None)
128815
function(action) {
            if(!this.gameOver){
                var result = this.player.update(action);
                if(result){

                    this.entityManager.update(this.player);
                    this.player.updateFov();

                    this.lighting.update();
                    this.renderer.setCenter(this.player.x, this.player.y);
                    this.renderer.draw();

                } else if(this.queueDraw){
                    this.renderer.draw();
                }
            }
            this.queueDraw = false;
        }
125352
def move_knight(p1)
      row = get_row_from_index(p1)
      col = get_col_from_index(p1)

      valid = []
      valid_moves_no_friendly_fire = []

      # Valid knight moves based on its board position
      valid << (p1 + 17) if row < 7 && col < 8
      valid << (p1 + 15) if row < 7 && col > 1
      valid << (p1 + 10) if row < 8 && col < 7
      valid << (p1 + 6)  if row < 8 && col > 2
      valid << (p1 - 6)  if row > 1 && col < 7
      valid << (p1 - 10) if row > 1 && col > 2
      valid << (p1 - 15) if row > 2 && col < 8
      valid << (p1 - 17) if row > 2 && col > 1

      # All possible moves for the knight based on board boundaries will added
      # This iterator filters for friendly fire, and removes indexes pointing to same color pices
      valid.each do |pos|
        valid_moves_no_friendly_fire << pos unless piece_color(pos) == Move.color
      end

      valid_moves_no_friendly_fire
    end
169844
protected function run()
    {
        $pack = $this->rec->getResourcePack();
        $this->version = $this->get(VersionAnalyzer::class);
        $version = $this->version;

        $players = $this->get(PlayerMetaAnalyzer::class);

        // The player number is used for chat messages.
        $playersByNumber = [];
        // The player index is used for game actions.
        $playersByIndex = [];
        foreach ($players as $player) {
            $playersByNumber[$player->number] = $player;
            $playersByIndex[$player->index] = $player;
        }

        $this->playersByNumber = $playersByNumber;

        $size = strlen($this->body);

        $this->position = 0;
        if ($version->isMgl) {
            $this->processGameStart();
        }

        while ($this->position < $size - 3) {
            $operationType = $this->readBody('l', 4);

            if ($operationType === self::OP_CHAT) {
                // AoC and up store the game start message with the same ID
                // as a CHAT message, but chat messages are prefixed with 0xFFFF_FFFF
                $syncChecksumInterval = $this->readBody('l', 4);
                if ($syncChecksumInterval === -1) {
                    $this->processChatMessage();
                } else {
                    $this->position -= 4;
                    $this->processGameStart();
                }
            } else if ($operationType === self::OP_SYNC) {
                $this->syncIndex++;
                // There are a lot of sync packets, so we get a significant
                // speedup just from doing this inline (and not in a separate
                // method), and by using `unpack` and manual position increments
                // instead of `readBody`.
                $data = unpack('l2', substr($this->body, $this->position, 8));
                $this->currentTime += $data[1]; // $this->readBody('l', 4);
                if ($this->syncIndex === $this->syncChecksumInterval) {
                    // no need to parse checksums
                    $this->position += 28;
                }
            } else if ($operationType === self::OP_VIEWLOCK) {
                // just skip for now
                $this->position += 12;
            } else if ($operationType === self::OP_COMMAND) {
                $length = $this->readBody('l', 4);
                $next = $this->position + $length;
                $command = ord($this->body[$this->position]);
                $this->position++;

                switch ($command) {
                    // player resign
                    case self::COMMAND_RESIGN:
                        $playerIndex = ord($this->body[$this->position]);
                        $playerNumber = ord($this->body[$this->position + 1]);
                        $disconnected = ord($this->body[$this->position + 2]);
                        $this->position += 3;
                        $player = $playersByIndex[$playerIndex];
                        if ($player && $player->resignTime === 0) {
                            $player->resignTime = $this->currentTime;
                            $message = sprintf('%s resigned', $player->name);
                            $this->chatMessages[] = new ChatMessage($this->currentTime, null, $message);
                        }
                        break;
                    // researches
                    case self::COMMAND_RESEARCH:
                        $this->position += 3;
                        $buildingId = $this->readBody('l', 4);
                        $playerId = $this->readBody('v', 2);
                        $researchId = $this->readBody('v', 2);
                        $player = $playersByIndex[$playerId];
                        if (!$player) {
                            break;
                        }

                        switch ($researchId) {
                            case self::RESEARCH_FEUDAL:
                                $researchDuration = 130000;
                                $player->feudalTime = $this->currentTime + $researchDuration;
                                break;
                            case self::RESEARCH_CASTLE:
                                // persians have faster research time
                                $researchDuration = 160000;
                                if ($player->civId === Civilization::PERSIANS) {
                                    $researchDuration /= 1.10;
                                }
                                $player->castleTime = $this->currentTime + round($researchDuration);
                                break;
                            case self::RESEARCH_IMPERIAL:
                                $researchDuration = 190000;
                                if ($player->civId === Civilization::PERSIANS) {
                                    $researchDuration /= 1.15;
                                }
                                $player->imperialTime = $this->currentTime + round($researchDuration);
                                break;
                        }
                        $player->addResearch($researchId, $this->currentTime);
                        break;
                    // training unit
                    case self::COMMAND_TRAIN:
                        $this->position += 3;
                        $buildingId = $this->readBody('l', 4);
                        $unitType = $this->readBody('v', 2);
                        $amount = $this->readBody('v', 2);

                        if (!isset($this->units[$unitType])) {
                            $this->units[$unitType] = $amount;
                        } else {
                            $this->units[$unitType] += $amount;
                        }
                        break;
                    // AI trains unit
                    case self::COMMAND_TRAIN_SINGLE:
                        $this->position += 9;
                        $unitType = $this->readBody('v', 2);
                        if (!isset($this->units[$unitType])) {
                            $this->units[$unitType] = 1;
                        } else {
                            $this->units[$unitType] += 1;
                        }
                        break;
                    // building
                    case self::COMMAND_BUILD:
                        $this->position += 1;
                        $playerId = $this->readBody('v', 2);
                        $this->position += 8;
                        $buildingType = $this->readBody('v', 2);

                        $buildingType = $pack->normalizeUnit($buildingType);

                        if (!isset($this->buildings[$playerId][$buildingType])) {
                            $this->buildings[$playerId][$buildingType] = 1;
                        } else {
                            $this->buildings[$playerId][$buildingType]++;
                        }
                        break;
                    // tributing
                    case self::COMMAND_TRIBUTE:
                        $playerIdFrom = ord($this->body[$this->position++]);
                        $playerIdTo = ord($this->body[$this->position++]);
                        $resourceId = ord($this->body[$this->position++]);

                        $playerFrom = $playersByIndex[$playerIdFrom];
                        $playerTo = $playersByIndex[$playerIdTo];

                        if ($playerFrom && $playerTo) {
                            $amount = $this->readBody('f', 4);
                            $marketFee = $this->readBody('f', 4);

                            $tribute = new Tribute();
                            $tribute->time = $this->currentTime;
                            $tribute->playerFrom = $playerFrom;
                            $tribute->playerTo = $playerTo;
                            $tribute->resourceId = $resourceId;
                            $tribute->amount = floor($amount);
                            $tribute->fee = $marketFee;
                            $this->tributes[] = $tribute;
                        } else {
                            $this->position += 8;
                        }
                        break;
                    // multiplayer postgame data in UP1.4 RC2+
                    case self::COMMAND_POSTGAME:
                        $this->postGameData = $this->read(PostgameDataAnalyzer::class);
                        break;
                    default:
                        break;
                }

                $this->position = $next;
            }
        }

        if (!empty($this->chatMessages)) {
            usort($this->chatMessages, function ($a, $b) {
                return $a->time - $b->time;
            });
        }

        if (!empty($this->buildings)) {
            ksort($this->buildings);
        }

        $analysis = new \StdClass;
        $analysis->duration = $this->currentTime;
        $analysis->tributes = $this->tributes;
        $analysis->chatMessages = $this->chatMessages;
        $analysis->units = $this->units;
        $analysis->buildings = $this->buildings;
        $analysis->postGameData = $this->postGameData;

        return $analysis;
    }
636822
function resetSeat(s) {
    const street = this.street
    const stage  = this.stage

    const preflop = street === 'preflop'
    const chipsName = 'chips' + street[0].toUpperCase() + street.slice(1)
    const p = script.players[s.playerIdx]
    const chips = p[chipsName]
    return Object.assign({}, seats[p.seatno], {
        chips       : chips
      , action      : null
      , amount      : 0
      , chipsInFront: preflop ? p.chipsInFront : 0
      , bet         : 0
      , investedBet : preflop && p.bb ? 1 : 0
      , _lastUpdate : stage
    })
  }
1241628
def parse_moves
      s0 = @current_pos
      s1 = parse_firstboard
      if s1 != :failed
        s2 = []
        s3 = parse_move
        while s3 != :failed
          s2 << s3
          s3 = parse_move
        end
        s3 = parse_result
        s3 = nil if s3 == :failed
        @reported_pos = s0
        s0 = -> (hd, tl, res) do
          tl.unshift(hd)
          tl << { "special" => res } if res && !tl[tl.length - 1]["special"]
          tl
        end.call(s1, s2, s3)
      else
        @current_pos = s0
        s0 = :failed
      end
      s0
    end
121247
function Game() {

        // un-populated instance of Array2d
        this.map = new RL.Map(this);
        this.entityManager = new RL.ObjectManager(this, RL.Entity);
        this.renderer = new RL.Renderer(this);
        this.console = new RL.Console(this);
        this.lighting = new RL.LightingROT(this);

        // player purposefully not added to entity manager (matter of preference)
        this.player = new RL.Player(this);

        // make sure "this" is this instance of Game when this.onKeyAction is called
        this.onKeyAction = this.onKeyAction.bind(this);
        this.onClick = this.onClick.bind(this);
        this.onHover = this.onHover.bind(this);

        this.input = new RL.Input(this.onKeyAction);
        this.mouse = new RL.Mouse(this.onClick, this.onHover);

        var el = this.renderer.canvas;
        this.mouse.startListening(el);
    }
216033
def move_pawn(p1)
      col = get_col_from_index(p1)
      valid = []

      # Piece color defines direction of travel. Enemy presence defines
      # the validity of diagonal movements
      if Move.color == :red
        valid << (p1 - 8) if unoccupied?(p1 - 8)
        valid << (p1 - 7) if piece_color(p1 - 7) == Move.enemy_color && col < 8
        valid << (p1 - 9) if piece_color(p1 - 9) == Move.enemy_color && col > 1
        # Only if the pieces is unmoved, can it move forward two rows
        valid << (p1 - 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 - 8) && unoccupied?(p1 - 16)

      elsif Move.color == :black

        valid << (p1 + 8) if unoccupied?(p1 + 8)
        valid << (p1 + 7) if piece_color(p1 + 7) == Move.enemy_color && col > 1
        valid << (p1 + 9) if piece_color(p1 + 9) == Move.enemy_color && col < 8
        valid << (p1 + 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 + 8) && unoccupied?(p1 + 16)
      end

      valid
    end
573233
def act( self ):
        ''''''
        if self.action_set == 'discrete_absolute':
            actions = ['movenorth 1', 'movesouth 1', 'movewest 1', 'moveeast 1']
        elif self.action_set == 'discrete_relative':
            actions = ['move 1', 'move -1', 'turn 1', 'turn -1']
        elif self.action_set == 'teleport':
            while True:
                dx = random.randint(-10,10)
                dz = random.randint(-10,10)
                if not dx == 0 or not dz == 0:
                    break
            self.expected_x = self.prev_x + dx
            self.expected_y = self.prev_y
            self.expected_z = self.prev_z + dz
            self.expected_yaw = self.prev_yaw
            self.require_move = True
            self.require_yaw_change = False
            actions = ['tp '+str(self.expected_x)+' '+str(self.expected_y)+' '+str(self.expected_z)]
        else:
            print('ERROR: Unsupported action set:',self.action_set)
            exit(1)
        i_action = random.randint(0,len(actions)-1)
        action = actions[ i_action ]
        print('Sending',action)
        self.agent_host.sendCommand( action )
        if self.action_set == 'discrete_absolute':
            self.expected_x = self.prev_x + [0,0,-1,1][i_action]
            self.expected_y = self.prev_y
            self.expected_z = self.prev_z + [-1,1,0,0][i_action]
            self.expected_yaw = self.prev_yaw
            self.require_move = True
            self.require_yaw_change = False
        elif self.action_set == 'discrete_relative':
            if i_action == 0 or i_action == 1:
                i_yaw = indexOfClosest( [0,90,180,270], self.prev_yaw )
                forward = [ (0,1), (-1,0), (0,-1), (1,0) ][ i_yaw ]
                if i_action == 0:
                    self.expected_x = self.prev_x + forward[0]
                    self.expected_z = self.prev_z + forward[1]
                else:
                    self.expected_x = self.prev_x - forward[0]
                    self.expected_z = self.prev_z - forward[1]
                self.expected_y = self.prev_y
                self.expected_yaw = self.prev_yaw
                self.require_move = True
                self.require_yaw_change = False
            else:
                self.expected_x = self.prev_x
                self.expected_y = self.prev_y
                self.expected_z = self.prev_z
                self.expected_yaw = math.fmod( 360 + self.prev_yaw + [90,-90][i_action-2], 360 )
                self.require_move = False
                self.require_yaw_change = True
        elif self.action_set == 'teleport':
            pass
        else:
            print('ERROR: Unsupported action set:',self.action_set)
            exit(1)
1249571
function() {

                    // beforeOpen callback
                    offsideSettings.beforeOpen();

                    // Turn on CSS transitions on first interaction with an Offside instance
                    if ( firstInteraction ) {
                        firstInteraction = false;
                        turnOnCssTransitions();
                    }

                    // If another Offside instance is already open,
                    // close it before going on
                    closeAll();

                    // Set global body active class for current Offside instance
                    addClass( body, offsideBodyOpenClass );
                    addClass( body, offsideBodyOpenSideClass );

                    // Add Offside instance open class
                    addClass( offside, offsideOpenClass );

                    // Update open Offside instances tracker
                    openOffsidesId.push( id );

                    // afterOpen callback
                    offsideSettings.afterOpen();
                }