Test if a tic-tac-toe game has been won.
    
    Assumes that the board is in a legal state.
    Will test if the value 1 is in any winning combination.
555179
def isWon(state, who):
    
    for w in WINS:
        S = sum(1 if (w[k] == 1 and state[k] == who) else 0
                for k in range(ACTIONS))
        if S == 3:
            # We have a win
            return True
    # There were no wins so return False
    return False
799435
def in_check(self, position, location=None):
        
        location = location or self.location
        for piece in position:

            if piece is not None and piece.color != self.color:
                if not isinstance(piece, King):
                    for move in piece.possible_moves(position):

                        if move.end_loc == location:
                            return True
                else:
                    if self.loc_adjacent_to_opponent_king(piece.location, position):
                        return True

        return False
1347768
def gameValue(self):
        """"""
        allowed = type(self).ALLOWED_TYPES
        try:
            if isinstance(allowed, dict): # if ALLOWED_TYPES is not a dict, there is no-internal game value mapping defined
                return allowed.get(self.type.name)
        except: pass # None .type values are okay -- such result in a None gameValue() result
        return None
583673
def loop(self):
        
        pause_key = self.board.PAUSE
        margins = {'left': 4, 'top': 4, 'bottom': 4}

        atexit.register(self.showCursor)

        try:
            self.hideCursor()
            while True:
                self.clearScreen()
                print(self.__str__(margins=margins))
                if self.board.won() or not self.board.canMove():
                    break
                m = self.readMove()

                if m == pause_key:
                    self.saveBestScore()
                    if self.store():
                        print("Game successfully saved. "
                              "Resume it with `term2048 --resume`.")
                        return self.score

                    print("An error ocurred while saving your game.")
                    return None

                self.incScore(self.board.move(m))

        except KeyboardInterrupt:
            self.saveBestScore()
            return None

        self.saveBestScore()
        print('You won!' if self.board.won() else 'Game Over')
        return self.score
961917
function Tourney(np, inst) {
  this._inst = inst;
  this.matches = inst.matches; // proxy reference
  this.oldMatches = []; // stash matches from completed instances here
  this._stage = 1;
  this._oldRes = [];
  this.state = [];
  // for determining when we can expect Tourney API
  Object.defineProperty(this, 'hasStages', { value: true });
}
89852
@SuppressWarnings("WeakerAccess")
    public boolean isPlaying() {
        if (packetBytes.length >= 212) {
            return (packetBytes[STATUS_FLAGS] & PLAYING_FLAG) > 0;
        } else {
            final PlayState1 state = getPlayState1();
            return  state == PlayState1.PLAYING || state == PlayState1.LOOPING ||
                    (state == PlayState1.SEARCHING && getPlayState2() == PlayState2.MOVING);
        }
    }
670738
function (playerCards, dealerCard, handValue, handCount, dealerCheckedBlackjack, options) 
    {
        // If exactComposition isn't set, no override
        if (options.strategyComplexity != "exactComposition")
        {
            return null;
        }

        // Now look at strategies based on game options
        if ((options.numberOfDecks == 2) && (!options.hitSoft17)) 
        {
            return TwoDeckStandSoft17(playerCards, dealerCard, handValue, handCount, dealerCheckedBlackjack, options);
        }
    }
315302
private function determineOutcome()
    {
        $outcome = [];
        
        $players = $this->getPlayers();
        $opponents = $players;

        if ($players === false) {
            return false;
        }

        foreach ($players as $player) {
        
            foreach ($opponents as $opponent) {
    
                // dont play the player against themself
                if ($player->getId() === $opponent->getId())
                {
                    continue;
                }

                // move collection
                $player_move = $player->getLastMoveIndex();
                $opponent_move = $opponent->getLastMoveIndex();

                // verify moves have been set
                if (!is_array($player_move)) {
                    throw new RockPaperScissorsSpockLizardException($player->getName() . ' has not set a move!');
                }

                if (!is_array($opponent_move)) {
                    throw new RockPaperScissorsSpockLizardException($opponent->getName() . ' has not set a move!');
                }

                // move labels
                $player_move_label = ucfirst(key($player_move));
                $opponent_move_label = ucfirst(key($opponent_move));

                // map moves to an index
                $player_move_index = $this->getMoveIndex($player_move);
                $opponent_move_index = $this->getMoveIndex($opponent_move);

                // Exceptions
                if (!is_numeric($player_move_index)) {
                    throw new RockPaperScissorsSpockLizardException($player->getName() . ' made an illegal move!');
                }

                if (!is_numeric($opponent_move_index)) {
                    throw new RockPaperScissorsSpockLizardException($opponent->getName() . ' made an illegal move!');
                }

                if (current($player_move) === true) {
                    throw new RockPaperScissorsSpockLizardException($player->getName() . ' has already made this move!');
                }

                if (current($opponent_move) === true) {
                    throw new RockPaperScissorsSpockLizardException($opponent->getName() . ' has already made this move!');
                }

                // compare player with opponent
                if (isset($this->move_outcomes[$player_move_index][$opponent_move_index])) {
                    $outcome['winners'][] = [
                        'player' => $player,
                        'opponent' => $opponent,
                        'description' => $player_move_label . ' ' . $this->move_outcomes[$player_move_index][$opponent_move_index] . ' ' . $opponent_move_label
                    ];
                    $outcome['losers'][] = [
                        'player' => $opponent,
                        'opponent' => $player,
                        'description' => $player_move_label . ' ' . $this->move_outcomes[$player_move_index][$opponent_move_index] . ' ' . $opponent_move_label
                    ];
                } else if (isset($this->move_outcomes[$opponent_move_index][$player_move_index])) {
                    // dont do anything -- we just need to check this in order to determine whether a tie needs to be calculated
                } else {
                    // we just add the tie for the player since the opponent will be added to the ties on later iteration
                    $outcome['ties'][] = [
                        'player' => $player,
                        'opponent' => $opponent,
                        'description' => 'Both played ' . $player_move_label
                    ];
                }
            }
        }

        // mark last moves as played
        foreach ($players as $player) {
            $player->lastMoveIsPlayed();
        }
        
        $this->setOutcome($outcome);
        
        return $this->getRoundOutcome();
    }
1185320
def start_game(debug=False):
    
    args = parse_cli_args()

    if args['version']:
        print_version_and_exit()

    if args['rules']:
        print_rules_and_exit()

    game = Game(**args)
    if args['resume']:
        game.restore()

    if debug:
        return game

    return game.loop()
221086
def check_for_end_game(self):
		
		gameover = False
		for player in self.players:
			if player.playstate in (PlayState.CONCEDED, PlayState.DISCONNECTED):
				player.playstate = PlayState.LOSING
			if player.playstate == PlayState.LOSING:
				gameover = True

		if gameover:
			if self.players[0].playstate == self.players[1].playstate:
				for player in self.players:
					player.playstate = PlayState.TIED
			else:
				for player in self.players:
					if player.playstate == PlayState.LOSING:
						player.playstate = PlayState.LOST
					else:
						player.playstate = PlayState.WON
			self.state = State.COMPLETE
			self.manager.step(self.next_step, Step.FINAL_WRAPUP)
			self.manager.step(self.next_step, Step.FINAL_GAMEOVER)
			self.manager.step(self.next_step)
23985
def has_value(cls, value: int) -> bool:
        """"""
        return any(value == item.value for item in cls)
906028
def get_capture(self):
        """"""
        # game
        game_image = self._game_image_from_screen('capture')
        if game_image is None:
            return
        # board
        board = self._board_from_game_image(game_image)
        if board is None:
            return
        if board.is_empty():
            return
        return board
752653
def check_if_win(self):
        """"""
        self.flagcount = 0
        win = True
        for x in range(0, len(self.mine_matrix[0])):
            for y in range(0, len(self.mine_matrix)):
                if self.mine_matrix[y][x].state == 1:
                    self.flagcount += 1
                    if not self.mine_matrix[y][x].has_mine:
                        win = False
                elif self.mine_matrix[y][x].has_mine:
                    win = False
        self.lblMineCount.set_text("%s" % self.minecount)
        self.lblFlagCount.set_text("%s" % self.flagcount)
        if win:
            self.dialog = gui.GenericDialog(title='You Win!', message='Game done in %s seconds' % self.time_count)
            self.dialog.confirm_dialog.do(self.new_game)
            self.dialog.cancel_dialog.do(self.new_game)
            self.dialog.show(self)
809044
def IsAllSpent(self):
        
        for item in self.Items:
            if item == CoinState.Confirmed:
                return False
        return True
309723
def check_result(running, recurse=False, highstate=None):
    '''
    
    '''
    if not isinstance(running, dict):
        return False

    if not running:
        return False

    ret = True
    for state_id, state_result in six.iteritems(running):
        expected_type = dict
        # The __extend__ state is a list
        if "__extend__" == state_id:
            expected_type = list
        if not recurse and not isinstance(state_result, expected_type):
            ret = False
        if ret and isinstance(state_result, dict):
            result = state_result.get('result', _empty)
            if result is False:
                ret = False
            # only override return value if we are not already failed
            elif result is _empty and isinstance(state_result, dict) and ret:
                ret = check_result(
                    state_result, recurse=True, highstate=highstate)
        # if we detect a fail, check for onfail requisites
        if not ret:
            # ret can be None in case of no onfail reqs, recast it to bool
            ret = bool(check_onfail_requisites(state_id, state_result,
                                               running, highstate))
        # return as soon as we got a failure
        if not ret:
            break
    return ret
847335
function ShouldPlayerStand(playerCards, dealerCard, handValue, handCount, options)
{
    var shouldStand = false;

    if (handValue.soft)
    {
        // Don't stand until you hit 18
        if (handValue.total > 18)
        {
            shouldStand = true;
        }
        else if (handValue.total == 18)
        {
            // Stand against dealer 2-8, and against a dealer Ace in single deck if they dealer will stand on soft 17
            shouldStand = ((dealerCard >= 2) && (dealerCard <= 8)) ||
                        ((dealerCard == 1) && (options.numberOfDecks == 1) && !options.hitSoft17);
        }
    }
    else
    {
        // Stand on 17 or above
        if (handValue.total > 16)
        {
            shouldStand = true;
        }
        else if (handValue.total > 12)
        {
            // 13-16 you should stand against dealer 2-6
            shouldStand = (dealerCard >= 2) && (dealerCard <= 6);
        }
        else if (handValue.total == 12)
        {
            // Stand on dealer 4-6
            shouldStand = (dealerCard >= 4) && (dealerCard <= 6);
        }

        // Advanced option - in single deck a pair of 7s should stand against a dealer 10
        if ((options.strategyComplexity != "simple") && (handValue.total == 14) && (playerCards[0] == 7) && (dealerCard == 10) && (options.numberOfDecks == 1))
        {
            shouldStand = true;
        }
    }

    return shouldStand;    
}
1314996
def get_versus(self):
        
        # game
        game_image = self._game_image_from_screen('versus')
        if game_image is None:
            return None, None, None, None  # nothing else will work
        # board
        board = self._board_from_game_image(game_image)  # may be None
        # safety check. there should be no blanks in a versus board
        if board:
            for p, tile in board.positions_with_tile():
                if tile.is_blank():
                    board = None
        # actors
        player = self._actor_from_game_image('player', game_image)
        opponent = self._actor_from_game_image('opponent', game_image)
        # extra actions
        extra_actions = self._count_extra_actions(game_image)
        return board, player, opponent, extra_actions