Used for playing a single game.

        For parallel play, use initialize_move, select_leaf,
        incorporate_results, and pick_move
420748
def suggest_move(self, position):
        
        start = time.time()

        if self.timed_match:
            while time.time() - start < self.seconds_per_move:
                self.tree_search()
        else:
            current_readouts = self.root.N
            while self.root.N < current_readouts + self.num_readouts:
                self.tree_search()
            if self.verbosity > 0:
                dbg("%d: Searched %d times in %.2f seconds\n\n" % (
                    position.n, self.num_readouts, time.time() - start))

        # print some stats on moves considered.
        if self.verbosity > 2:
            dbg(self.root.describe())
            dbg('\n\n')
        if self.verbosity > 3:
            dbg(self.root.position)

        return self.pick_move()
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
265617
def accept_subgame(self, visitor: "BaseVisitor[ResultT]") -> ResultT:
        
        if visitor.begin_game() is not SKIP:
            game = self.root()
            board = self.board()

            dummy_game = Game.without_tag_roster()
            dummy_game.setup(board)

            visitor.begin_headers()

            for tagname, tagvalue in game.headers.items():
                if tagname not in dummy_game.headers:
                    visitor.visit_header(tagname, tagvalue)
            for tagname, tagvalue in dummy_game.headers.items():
                visitor.visit_header(tagname, tagvalue)

            if visitor.end_headers() is not SKIP:
                visitor.visit_board(board)

                if self.variations:
                    self.variations[0].accept(visitor, _parent_board=board)

                visitor.visit_result(game.headers.get("Result", "*"))

        visitor.end_game()
        return visitor.result()
553482
def play_match(black_model, white_model, games, sgf_dir):
    
    with utils.logged_timer("Loading weights"):
        black_net = dual_net.DualNetwork(black_model)
        white_net = dual_net.DualNetwork(white_model)

    readouts = FLAGS.num_readouts

    black = MCTSPlayer(black_net, two_player_mode=True)
    white = MCTSPlayer(white_net, two_player_mode=True)

    black_name = os.path.basename(black_net.save_file)
    white_name = os.path.basename(white_net.save_file)

    for i in range(games):
        num_move = 0  # The move number of the current game

        for player in [black, white]:
            player.initialize_game()
            first_node = player.root.select_leaf()
            prob, val = player.network.run(first_node.position)
            first_node.incorporate_results(prob, val, first_node)

        while True:
            start = time.time()
            active = white if num_move % 2 else black
            inactive = black if num_move % 2 else white

            current_readouts = active.root.N
            while active.root.N < current_readouts + readouts:
                active.tree_search()

            # print some stats on the search
            if FLAGS.verbose >= 3:
                print(active.root.position)

            # First, check the roots for hopeless games.
            if active.should_resign():  # Force resign
                active.set_result(-1 *
                                  active.root.position.to_play, was_resign=True)
                inactive.set_result(
                    active.root.position.to_play, was_resign=True)

            if active.is_done():
                fname = "{:d}-{:s}-vs-{:s}-{:d}.sgf".format(int(time.time()),
                                                            white_name, black_name, i)
                active.set_result(active.root.position.result(), was_resign=False)
                with gfile.GFile(os.path.join(sgf_dir, fname), 'w') as _file:
                    sgfstr = sgf_wrapper.make_sgf(active.position.recent,
                                                  active.result_string, black_name=black_name,
                                                  white_name=white_name)
                    _file.write(sgfstr)
                print("Finished game", i, active.result_string)
                break

            move = active.pick_move()
            active.play_move(move)
            inactive.play_move(move)

            dur = time.time() - start
            num_move += 1

            if (FLAGS.verbose > 1) or (FLAGS.verbose == 1 and num_move % 10 == 9):
                timeper = (dur / readouts) * 100.0
                print(active.root.position)
                print("%d: %d readouts, %.3f s/100. (%.2f sec)" % (num_move,
                                                                   readouts,
                                                                   timeper,
                                                                   dur))
127498
def add_play(self, choice, count=1):
        """"""
        self.redis.hincrby(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "%s:plays" % choice, count)
        self._choices = None
270090
function Swipe(game, model) {
  var self = this;

  self.DIRECTION_UP = 1;
  self.DIRECTION_DOWN = 2;
  self.DIRECTION_LEFT = 4;
  self.DIRECTION_RIGHT = 8;
  self.DIRECTION_UP_RIGHT = 16;
  self.DIRECTION_UP_LEFT = 32;
  self.DIRECTION_DOWN_RIGHT = 64;
  self.DIRECTION_DOWN_LEFT = 128;

  self.game = game;
  self.model = model !== undefined ? model : null;
  self.dragLength = 100;
  self.diagonalDelta = 50;
  self.swiping = false;
  self.direction = null;
  self.tmpDirection = null;
  self.tmpCallback = null;
  self.diagonalDisabled = false;

  this.game.input.onDown.add(function () {
    self.swiping = true;
  });
  this.game.input.onUp.add(function () {
    self.swiping = false;
  })

  this.setupKeyboard();
}
469218
def _setup_exercise(game_interface: GameInterface, ex: Exercise, seed: int) -> Optional[Result]:
    
    rng = random.Random()
    rng.seed(seed)
    try:
        game_state = ex.setup(rng)
    except Exception as e:
        return Result(ex, seed, FailDueToExerciseException(e, traceback.format_exc()))
    game_interface.set_game_state(game_state)
637281
def make_chunk_for(output_dir=LOCAL_DIR,
                   local_dir=LOCAL_DIR,
                   game_dir=None,
                   model_num=1,
                   positions=EXAMPLES_PER_GENERATION,
                   threads=8,
                   sampling_frac=0.02):
    
    game_dir = game_dir or fsdb.selfplay_dir()
    ensure_dir_exists(output_dir)
    models = [model for model in fsdb.get_models() if model[0] < model_num]
    buf = ExampleBuffer(positions, sampling_frac=sampling_frac)
    files = []
    for _, model in sorted(models, reverse=True):
        local_model_dir = os.path.join(local_dir, model)
        if not tf.gfile.Exists(local_model_dir):
            print("Rsyncing", model)
            _rsync_dir(os.path.join(game_dir, model), local_model_dir)
        files.extend(tf.gfile.Glob(os.path.join(local_model_dir, '*.zz')))
        print("{}: {} games".format(model, len(files)))
        if len(files) * 200 * sampling_frac > positions:
            break

    print("Filling from {} files".format(len(files)))

    buf.parallel_fill(files, threads=threads)
    print(buf)
    output = os.path.join(output_dir, str(model_num) + '.tfrecord.zz')
    print("Writing to", output)
    buf.flush(output)
1220497
public function actionPlay()
	{
		static $levels=array(
			'10'=>'Easy game; you are allowed 10 misses.',
			'5'=>'Medium game; you are allowed 5 misses.',
			'3'=>'Hard game; you are allowed 3 misses.',
		);

		// if a difficulty level is correctly chosen
		if(isset($_POST['level']) && isset($levels[$_POST['level']]))
		{
			$this->word=$this->generateWord();
			$this->guessWord=str_repeat('_',strlen($this->word));
			$this->level=$_POST['level'];
			$this->misses=0;
			$this->setPageState('guessed',null);
			// show the guess page
			$this->render('guess');
		}
		else
		{
			$params=array(
				'levels'=>$levels,
				// if this is a POST request, it means the level is not chosen
				'error'=>Yii::app()->request->isPostRequest,
			);
			// show the difficulty level page
			$this->render('play',$params);
		}
	}
1103030
def result(self, *, claim_draw: bool = False) -> str:
        
        # Chess variant support.
        if self.is_variant_loss():
            return "0-1" if self.turn == WHITE else "1-0"
        elif self.is_variant_win():
            return "1-0" if self.turn == WHITE else "0-1"
        elif self.is_variant_draw():
            return "1/2-1/2"

        # Checkmate.
        if self.is_checkmate():
            return "0-1" if self.turn == WHITE else "1-0"

        # Draw claimed.
        if claim_draw and self.can_claim_draw():
            return "1/2-1/2"

        # Seventyfive-move rule or fivefold repetition.
        if self.is_seventyfive_moves() or self.is_fivefold_repetition():
            return "1/2-1/2"

        # Insufficient material.
        if self.is_insufficient_material():
            return "1/2-1/2"

        # Stalemate.
        if not any(self.generate_legal_moves()):
            return "1/2-1/2"

        # Undetermined.
        return "*"
205147
async def selfplay(state, flagfile='selfplay'):
  

  output_dir = os.path.join(fsdb.selfplay_dir(), state.output_model_name)
  holdout_dir = os.path.join(fsdb.holdout_dir(), state.output_model_name)

  lines = await run(
      'bazel-bin/cc/selfplay',
      '--flagfile={}.flags'.format(os.path.join(FLAGS.flags_dir, flagfile)),
      '--model={}'.format(state.best_model_path),
      '--output_dir={}'.format(output_dir),
      '--holdout_dir={}'.format(holdout_dir),
      '--seed={}'.format(state.seed))
  result = '\n'.join(lines[-6:])
  logging.info(result)
  stats = parse_win_stats_table(result, 1)[0]
  num_games = stats.total_wins
  logging.info('Black won %0.3f, white won %0.3f',
               stats.black_wins.total / num_games,
               stats.white_wins.total / num_games)

  # Write examples to a single record.
  pattern = os.path.join(output_dir, '*', '*.zz')
  random.seed(state.seed)
  tf.set_random_seed(state.seed)
  np.random.seed(state.seed)
  # TODO(tommadams): This method of generating one golden chunk per generation
  # is sub-optimal because each chunk gets reused multiple times for training,
  # introducing bias. Instead, a fresh dataset should be uniformly sampled out
  # of *all* games in the training window before the start of each training run.
  buffer = example_buffer.ExampleBuffer(sampling_frac=1.0)

  # TODO(tommadams): parallel_fill is currently non-deterministic. Make it not
  # so.
  logging.info('Writing golden chunk from "{}"'.format(pattern))
  buffer.parallel_fill(tf.gfile.Glob(pattern))
  buffer.flush(os.path.join(fsdb.golden_chunk_dir(),
                            state.output_model_name + '.tfrecord.zz'))
1309527
def play
      index = 0
      hist = Array.new(3, "")

      loop do
        puts "\e[H\e[2J"
        puts self.positions[index].inspect
        hist[0..2] = (hist[1..2] << STDIN.getch)

        case hist.join
        when LEFT
          index -= 1 if index > 0
        when RIGHT
          index += 1 if index < self.moves.length
        when EXIT
          break
        end
      end
    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);
    }
1024261
def black_move(self):
        
        move = self.player_black.generate_move(self.position)
        move = make_legal(move, self.position)
        self.position.update(move)
19198
function (hands, table, dead) {
		// Preprocesses the input data.
		table = table ? _.map(table, getCode) : [];
		dead = dead ? _.map(dead, getCode) : [];
		hands = _.map(hands, function (hand) {
			return _.map(hand, getCode);
		});
		var res = deckSize + 1;
		for (var c = 0; c < table.length; c++)
			res = evaluator[res + table[c]];
		var deck = _.chain(_.range(1, deckSize + 1)).difference(table)
				.difference(_.flatten(hands)).difference(dead).value();
		var player = _.map(hands, function (hand) {
			return evaluator[evaluator[res + hand[0]] + hand[1]];
		});
		var combinations = function (n, k, res, callback) {
			if (k <= 0) {
				callback(res);
			} else {
				while (n < deck.length) {
					var parcial = evaluator[res + deck[n++]];
					combinations(n, k - 1, parcial, callback);
				}
			}
		};
		
		// Calculates the outcome of each play.
		var remaining = 5 - table.length;
		var plays = deck.length / remaining;
		for (var c = 1; c < remaining; c++)
			plays *= (deck.length - c) / c;
		var values = new Array(hands.length);
		for (var p = 0; p < hands.length; p++) {
			var s = 0;
			values[p] = new Int32Array(plays);
			combinations(0, remaining, player[p], function (res) {
				values[p][s++] = res;
			});
		}
		
		// Determines the results.
		var wins = new Int32Array(hands.length);
		var splits = new Int32Array(hands.length);
		for (var s = 0; s < plays; s++) {
			var winner = [0];
			for (var p = 1; p < hands.length; p++) {
				if (values[p][s] > values[winner[0]][s])
					winner = [p];
				else if (values[p][s] == values[winner[0]][s])
					winner.push(p);
			}
			if (winner.length == 1) {
				wins[winner[0]]++;
			} else {
				for (var p = 0; p < winner.length; p++)
					splits[winner[p]]++;
			}
		}
		
		// Formats odds output.
		var odds = [];
		for (var p = 0; p < hands.length; p++)
			odds[p] = {win: wins[p] / plays, split: splits[p] / plays};
		return odds;
	}
1192421
function Game(node) {

        this.node = node;

        // This updates are never published.
        this.setStateLevel(constants.stateLevels.UNINITIALIZED, 'S');
        this.setStageLevel(constants.stageLevels.UNINITIALIZED, 'S');

        // ## Properties

        /**
         * ### Game.metadata
         *
         * The game's metadata
         *
         * This object is normally filled-in automatically with data
         * from the file `package.json` inside the game folder.
         *
         * Contains at least the following properties:
         *
         *  - name,
         *  - description,
         *  - version
         */
        this.metadata = {
            name:        'A nodeGame game',
            description: 'No description',
            version:     '0.0.1'
        };

        /**
         * ### Game.settings
         *
         * The game's settings
         *
         * This object is normally filled-in automatically with the settings
         * contained in the game folder: `game/game.settings`,
         * depending also on the chosen treatment.
         */
        this.settings = {};

        /**
         * ### Game.pl | playerList
         *
         * The list of players connected to the game
         *
         * The list may be empty, depending on the server settings.
         *
         * Two players with the same id, or any player with id equal to
         * `node.player.id` is not allowed, and it will throw an error.
         */
        this.playerList = this.pl = new PlayerList({
            log: this.node.log,
            logCtx: this.node,
            name: 'pl_' + this.node.nodename
        });

        this.pl.on('insert', function(p) {
            if (p.id === node.player.id) {
                throw new Error('node.game.pl.on.insert: cannot add player ' +
                                'with id equal to node.player.id.');
            }
        });

        /**
         * ### Game.ml | monitorList
         *
         * The list of monitor clients connected to the game
         *
         * The list may be empty, depending on the server settings
         */
        this.monitorList = this.ml = new PlayerList({
            log: this.node.log,
            logCtx: this.node,
            name: 'ml_' + this.node.nodename
        });

        /**
         * ### Game.memory
         *
         * A storage database for the game
         *
         * In the server logic the content of SET messages are
         * automatically inserted in this object
         *
         * @see NodeGameClient.set
         */
        this.memory = new GameDB({
            log: this.node.log,
            logCtx: this.node,
            shared: { node: this.node }
        });

        /**
         * ### Game.plot
         *
         * The Game plot
         *
         * @see GamePlot
         */
        this.plot = new GamePlot(this.node, new Stager());

// TODO: check if we need this.
//        // Overriding stdout for game plot and stager.
//        this.plot.setDefaultLog(function() {
//            // Must use apply, else will be executed in the wrong context.
//            node.log.apply(node, arguments);
//        });

        /**
         * ### Game.role
         *
         * The "role" currently held in this game (if any)
         *
         * @see Game.gotoStep
         * @see Game.setRole
         * @see processGotoStepOptions
         */
        this.role = null;

        /**
         * ### Game.partner
         *
         * The id or alias of the "partner" in this game (if any)
         *
         * Some games are played in pairs, this variable holds the id
         * of the partner player.
         *
         * @see Game.setPartner
         * @see processGotoStepOptions
         */
        this.partner = null;

        /**
         * ### Game.matcher
         *
         * Handles assigning matching tasks
         *
         * Assigns roles to players, players to players, etc.
         *
         * @see Game.gotoStep
         */
        this.matcher = MatcherManager ? new MatcherManager(this.node) : null;

        /**
         * ### Game.timer
         *
         * Default game timer synced with stager 'timer' property
         *
         * @see GameTimer
         * @see GameTimer.syncWithStager
         */
        this.timer = this.node.timer.createTimer({
            name: 'game_timer',
            stagerSync: true
        });



        // Setting to stage 0.0.0 and starting.
        this.setCurrentGameStage(new GameStage(), 'S');
        this.setStateLevel(constants.stateLevels.STARTING, 'S');

        /**
         * ### Game.paused
         *
         * TRUE, if the game is paused
         *
         * @see Game.pause
         * @see Game.resume
         */
        this.paused = false;

        /**
         * ### Game.pauseCounter
         *
         * Counts the number of times the game was paused
         *
         * @see Game.pause
         * @see Game.resume
         */
        this.pauseCounter = 0;

        /**
         * ### Game.willBeDone
         *
         * TRUE, if DONE was emitted and evaluated successfully
         *
         * If TRUE, when PLAYING is emitted `node.done` is called
         * immediately, and the game tries to step forward.
         *
         * @see NodeGameClient.done
         */
        this.willBeDone = false;

        /**
         * ### Game.globals
         *
         * Object pointing to the current step _globals_ properties
         *
         * Whenever a new step is executed the _globals_ properties of
         * the step are copied here. The _globals_ properties of the previous
         * stage are deleted.
         *
         * @see GamePlot
         * @see Stager
         */
        this.globals = {};

        /**
         * ### Game._steppedSteps
         *
         * Array of steps previously played
         *
         * @see Game.step
         */
        this._steppedSteps = [ new GameStage() ];

        /**
         * ### Game._breakStage
         *
         * Flags to break current stage at next node.done call
         *
         * @see Game.breakStage
         */
        this._breakStage = false;

        /** ### Game.pushManager
         *
         * Handles pushing client to advance to next step
         *
         * @see PushManager
         */
        this.pushManager = new PushManager(this.node);

        /** ### Game.sizeManager
         *
         * Handles changes in the number of connected players
         *
         * @see SizeManager
         */
        this.sizeManager = new SizeManager(this.node);
    }
162842
public function initGame()
    {
        $this->board = array();
        $this->last_player = null;

        for ($x=0; $x<$this->size; $x++) {
            $row = array();

            for ($y=0; $y<$this->size; $y++) {
                $row[] = null;
            }

            $this->board[] = $row;
        }

        $this->display();
    }