当前位置: 面试刷题>> 飞行棋 (经典算法题500道)


题目描述

飞行棋游戏模拟

在飞行棋游戏中,四名玩家轮流掷骰子(通常是一个六面骰子,每面数字为1到6),并根据掷出的点数在棋盘上移动他们的棋子。棋盘通常是一个环形的,包括多个格子,每个格子可能包含特殊的奖励或惩罚效果(如:直接前进到某一点、后退几步、停留在原地等)。游戏的目标是第一个将所有棋子都移动到终点的玩家获胜。

为了简化问题,我们假设棋盘是一个线性的,包含40个格子(包括起点和终点),终点位于第40格。棋子在掷出6时可以额外掷一次骰子(即“连掷”),并且不考虑特殊格子效果。

请编写一个程序,该程序能够模拟四名玩家(玩家A、B、C、D)的飞行棋游戏过程,并输出第一个完成所有棋子到达终点的玩家名称。

示例代码

PHP 示例

<?php

class Dice {
    public function roll() {
        return rand(1, 6);
    }
}

class Game {
    private $players = ['A', 'B', 'C', 'D'];
    private $dice;
    private $boardSize = 40;

    public function __construct() {
        $this->dice = new Dice();
    }

    public function play() {
        $positions = array_fill(0, 4, [0, 0, 0, 0]); // 假设每个玩家有4个棋子
        $finished = [false, false, false, false];

        while (true) {
            foreach ($this->players as $index => $player) {
                if (!$finished[$index]) {
                    for ($i = 0; $i < 4; $i++) {
                        $roll = $this->dice->roll();
                        $positions[$index][$i] = ($positions[$index][$i] + $roll) % $this->boardSize;
                        if ($positions[$index][$i] == $this->boardSize - 1) {
                            // 棋子到达终点
                            if ($this->allReached($positions[$index])) {
                                echo "玩家 {$player} 获胜!\n";
                                return;
                            }
                            $positions[$index][$i] = 0; // 重置到起点准备下一轮
                        }
                        if ($roll == 6) {
                            // 连掷
                            $additionalRoll = $this->dice->roll();
                            $positions[$index][$i] = ($positions[$index][$i] + $additionalRoll) % $this->boardSize;
                            if ($positions[$index][$i] == $this->boardSize - 1) {
                                if ($this->allReached($positions[$index])) {
                                    echo "玩家 {$player} 获胜!\n";
                                    return;
                                }
                                $positions[$index][$i] = 0;
                            }
                        }
                    }
                }
            }
        }
    }

    private function allReached($playerPositions) {
        foreach ($playerPositions as $pos) {
            if ($pos != 0) {
                return false;
            }
        }
        return true;
    }
}

$game = new Game();
$game->play();
?>

Python 示例

import random

class Game:
    def __init__(self):
        self.players = ['A', 'B', 'C', 'D']
        self.board_size = 40

    def roll_dice(self):
        return random.randint(1, 6)

    def play(self):
        positions = [[0] * 4 for _ in range(4)]  # 4 players, each with 4 pieces
        finished = [False] * 4

        while True:
            for index, player in enumerate(self.players):
                if not finished[index]:
                    for i in range(4):
                        roll = self.roll_dice()
                        positions[index][i] = (positions[index][i] + roll) % self.board_size
                        if positions[index][i] == self.board_size - 1:
                            if all(pos == 0 for pos in positions[index]):
                                print(f"玩家 {player} 获胜!")
                                return
                            positions[index][i] = 0  # Reset to start for next round
                        if roll == 6:
                            additional_roll = self.roll_dice()
                            positions[index][i] = (positions[index][i] + additional_roll) % self.board_size
                            if positions[index][i] == self.board_size - 1:
                                if all(pos == 0 for pos in positions[index]):
                                    print(f"玩家 {player} 获胜!")
                                    return
                                positions[index][i] = 0

# Start the game
game = Game()
game.play()

JavaScript 示例

class Dice {
    roll() {
        return Math.floor(Math.random() * 6) + 1;
    }
}

class Game {
    constructor() {
        this.players = ['A', 'B', 'C', 'D'];
        this.dice = new Dice();
        this.boardSize = 40;
    }

    play() {
        const positions = Array.from({ length: 4 }, () => Array(4).fill(0));
        const finished = Array(4).fill(false);

        while (true) {
            for (let [index, player] of this.players.entries()) {
                if (!finished[index]) {
                    for (let i = 0; i < 4; i++) {
                        let roll = this.dice.roll();
                        positions[index][i] = (positions[index][i] + roll) % this.boardSize;
                        if (positions[index][i] === this.boardSize - 1) {
                            if (positions[index].every(pos => pos === 0)) {
                                console.log(`玩家 ${player} 获胜!`);
                                return;
                            }
                            positions[index][i] = 0;
                        }
                        if (roll === 6) {
                            let additionalRoll = this.dice.roll();
                            positions[index][i] = (positions[index][i] + additionalRoll) % this.boardSize;
                            if (positions[index][i] === this.boardSize - 1) {
                                if (positions[index].every(pos => pos === 0)) {
                                    console.log(`玩家 ${player} 获胜!`);
                                    return;
                                }
                                positions[index][i] = 0;
                            }
                        }
                    }
                }
            }
        }
    }
}

const game = new Game();
game.play();

以上代码均实现了飞行棋游戏的基本逻辑,但请注意,为了简化,这些示例没有考虑棋盘上的特殊格子效果,并且棋盘被简化为线性。在实际应用中,可以根据需求增加这些功能。

推荐面试题