0

我正在尝试编写一个代码,当我上梯子时它会改变方向到目前为止我已经让它工作,当我降落在蛇上并下降时它会改变方向但是当我上梯子时它会走错路我还想知道如何制作一个函数,当我掷骰子时它落在 100 上,我赢了,但如果它滚动并超过 100,它会回到以前的位置,这是到目前为止的代码

namespace JokosenumiAkeem

public partial class MainPage : ContentPage
{

    const int START_ROW = 11;
    const int START_COL = 1;
    const int WIN_ROW = 1;
    const int WIN_COL = 1;
    const int EDGE_RIGHT = 10;
    const int EDGE_LEFT = 1;
    const int NUMBER_OF_SNAKES = 8;
    const int NUMBER_OF_PLAYERS = 3;
    const int NUMBER_OF_LADDERS = 8;

    Random _random;
    int _diceRoll;
    int _currentPlayer;
    int _currentEdgeCol;
    int _IsMovingLR;

    // use an array to store the variables for playing for each player separately
    // what do I need to store for each player
    // _IsMovingLR, _currentEdgeCol, 
    // int[2] { 1, EDGE_RIGHT }
    // int[2] { 1, EDGE_RIGHT }
    // int[2] { 1, EDGE_RIGHT }
    int[][] _Players;
    int[][] _Ladders;
    int[][] _Snakes;

    public MainPage()
    {
        InitializeComponent();
        SetupSnakes();
        SetUpLadders();
        SetupPlayers();
        // set up my game variables.
        _currentPlayer = 1;
        // from the player array, get the values
        _IsMovingLR = _Players[_currentPlayer - 1][0];
        _currentEdgeCol = _Players[_currentPlayer - 1][1];
        _random = new Random();
    }

    private void SetUpLadders()
    {
        _Ladders = new int[NUMBER_OF_LADDERS][]{
                                              new int[4] {3, 1, 1, 2},
                                              new int[4] {3, 9, 1, 10 },
                                              new int[4] {5, 10, 4, 7},
                                              new int[4] {8, 8, 2, 4 },
                                              new int[4] {8, 1, 5, 2 },
                                              new int[4] {10, 1, 7, 3 },
                                              new int[4] {10, 4, 9, 7 },
                                              new int[4] {10, 9, 7, 10 },
        };
    }

    private void SetupPlayers()
    {

        _Players = new int[NUMBER_OF_PLAYERS][]
        {
            // stores {_IsMovingLR, _currentEdgeCol }
            new int[2] { 1, EDGE_RIGHT },
            new int[2] { 1, EDGE_RIGHT },
            new int[2] { 1, EDGE_RIGHT }
        };
    }

    private void SetupSnakes()
    {
        // initialise the global variable for snakes here
        // this adds a single dimensional (simple) array for each snake.
        // Each snake is represented as int[4] { TopRow, TopCol, BottomRow, BottomCol }
        _Snakes = new int[NUMBER_OF_SNAKES][] {
                                                new int[4] {9, 4, 10, 7 },
                                                new int[4] {5, 7, 7, 7 },
                                                new int[4] {4, 2, 9, 2},
                                                new int[4] {4, 4, 5, 1 },
                                                new int[4] {2, 7, 7, 5 },
                                                new int[4] {1, 3, 3, 2 },
                                                new int[4] {1, 6, 3, 6 },
                                                new int[4] {1, 8, 3, 8}

        };
    }
    private async void btnDiceRoll_Clicked(object sender, EventArgs e)
    {
        // generate random number
        //_diceRoll = 4;
        _diceRoll = _random.Next(1, 7);
        // update the dice roll label
        lblDiceRoll.Text = _diceRoll.ToString();
        lblUpdates.Text = "P " + _currentPlayer;
        // move piece
        await MovePiece();

        // get the next player.
        _currentPlayer++;
        if (_currentPlayer == 4) { _currentPlayer = 1; }
        // from the player array, get the values
        _IsMovingLR = _Players[_currentPlayer - 1][0];
        _currentEdgeCol = _Players[_currentPlayer - 1][1];

    }

    #region PIECE MOVEMENT CODE
    private async Task MovePiece()  // async marks the MovePiece method as using an await call
    {
        // if it's the first move, put the row = 10
        // which piece am I moving - x:Name="bvP1"
        // FindByName - looks for x:Name properties in XAML
        string currPlayer = "bvP" + _currentPlayer.ToString();
        BoxView bvPlayer = (BoxView)GrdBoard.FindByName(currPlayer);
        int currPlayerCol = (int)bvPlayer.GetValue(Grid.ColumnProperty);

        // is this the first move.
        if (START_ROW == (int)bvPlayer.GetValue(Grid.RowProperty))
        {
            bvPlayer.SetValue(Grid.RowProperty, START_ROW - 1);
            bvPlayer.SetValue(Grid.ColumnProperty, START_COL);
            _diceRoll--;
            await MoveHorizontal(bvPlayer, _diceRoll);
            // CheckForLadders();
            return;
        }

        // if I get to here, then it's a later move
        // if edgeCol - player Col <= dice roll, then simple move from L -> R
        //if( _diceRoll <= Math.Abs(_currentEdgeCol - currPlayerCol) )
        if (_diceRoll <= Math.Abs(_currentEdgeCol - currPlayerCol))
        {
            // translate my player piece
            await MoveHorizontal(bvPlayer, _diceRoll);
        }
        else // move around a corner
        {
            // Left to Right movement of diff
            int diff = Math.Abs(_currentEdgeCol - currPlayerCol);
            await MoveHorizontal(bvPlayer, diff);
            _diceRoll -= diff;  // decrement diceroll by diff

            // move vertically
            await MoveVerticalOneRow(bvPlayer);
            _diceRoll--;

            // move R-L with what's left on the dice roll (subtract columns)
            await MoveHorizontal(bvPlayer, _diceRoll);
        }


        CheckForSnakes(bvPlayer);
        if( WIN_ROW ==(int)bvPlayer.GetValue(Grid.RowProperty))
        {
            CheckForWin(bvPlayer);
        }
        CheckForLadders(bvPlayer);
    }

    private void CheckForLadders(BoxView player)
    {
        int iCount = 0;
        int indexRTop = 0, indexCTop = 1;
        int indexRBottom = 2, indexCBottom = 3;
        int playerRow, playerCol;
        int deltaRows = 1;

        playerRow = (int)player.GetValue(Grid.RowProperty);
        playerCol = (int)player.GetValue(Grid.ColumnProperty);

        while (iCount < NUMBER_OF_LADDERS)
        {
            if((playerRow == _Ladders[iCount][indexRTop]) &&
               (playerCol == _Ladders[iCount][indexCTop]))
            {
                lblUpdates.Text = "You landed on a ladder";
                // if true the player will move to the top of the ladder
                player.SetValue(Grid.RowProperty, _Ladders[iCount][indexRBottom]);
                player.SetValue(Grid.ColumnProperty, _Ladders[iCount][indexCBottom]);
                deltaRows = _Ladders[iCount][indexRBottom] + _Ladders[iCount][indexRBottom];
            }
            iCount++;
        }
        // if move down an odd number of rows, change direction
        if (deltaRows % 2 == 1)
        {
            ChangeUp();
        }
    }

    private async Task MoveHorizontal(BoxView bvPlayer, int numSpaces)
    {
        int horizontalDistance = ((int)GrdBoard.Width / 12) * numSpaces * _IsMovingLR;
        uint timeValue = (uint)(Math.Abs(numSpaces) * 150);
        int currPlayerCol = (int)bvPlayer.GetValue(Grid.ColumnProperty);

        await bvPlayer.TranslateTo(horizontalDistance, 0, timeValue);   // takes time, so ask the system to wait for it to finish
        bvPlayer.TranslationX = 0;
        // set the Col to the curr + dice roll
        bvPlayer.SetValue(Grid.ColumnProperty, currPlayerCol + (numSpaces * _IsMovingLR));
        ChangeUp();
    }

    private async Task MoveVerticalOneRow(BoxView pieceToMove)
    {
        int verticalDistance = (int)GrdBoard.Width / 12;    // 1 square
        uint timeValue = (uint)150;
        await pieceToMove.TranslateTo(0, -1 * verticalDistance, timeValue);   // takes time, so ask the system to wait for it to finish
        pieceToMove.TranslationY = 0;
        pieceToMove.SetValue(Grid.RowProperty, (int)pieceToMove.GetValue(Grid.RowProperty) - 1);

        ChangeDirection();
    }

    private void ChangeUp()
    {
        _IsMovingLR *= +1;
        //                       if LR = -1
        //                          1           10
        _currentEdgeCol = Math.Max(EDGE_LEFT, EDGE_RIGHT * _IsMovingLR);
        // update the player array
        _Players[_currentPlayer + 1][0] = _IsMovingLR;
        _Players[_currentPlayer + 1][1] = _currentEdgeCol;
    }

    private void ChangeDirection()
    {
        _IsMovingLR *= -1;
        //                       if LR = -1
        //                          1           10
        _currentEdgeCol = Math.Max(EDGE_LEFT, EDGE_RIGHT * _IsMovingLR);
        // update the player array
        _Players[_currentPlayer - 1][0] = _IsMovingLR;
        _Players[_currentPlayer - 1][1] = _currentEdgeCol;
    }
    #endregion

    #region CHECK FOR SNAKES, LADDERS, WIN CONDITION
    /// <summary>
    /// checks if the player position is currently the head of a snake.
    /// </summary>
    private void CheckForSnakes(BoxView player)
    {
        int iCounter = 0;
        int indexRTop = 0, indexCTop = 1;
        int indexRBottom = 2, indexCBottom = 3;
        int playerRow, playerCol;
        int deltaRows = 0;

        playerRow = (int)player.GetValue(Grid.RowProperty);
        playerCol = (int)player.GetValue(Grid.ColumnProperty);

        // loop through the array of snakes to check if the Row and Col are equal

        while (iCounter < NUMBER_OF_SNAKES)
        {
            // playerRow == _Snakes[iCounter][indexRTop]
            if ((playerRow == _Snakes[iCounter][indexRTop]) &&
                (playerCol == _Snakes[iCounter][indexCTop]))
            {
                // at the top of a snake.-
                lblUpdates.Text = "You landed on a snake.";
                // if true - then player is moved back to the bottom of the snake.
                player.SetValue(Grid.RowProperty, _Snakes[iCounter][indexRBottom]);
                player.SetValue(Grid.ColumnProperty, _Snakes[iCounter][indexCBottom]);
                deltaRows = _Snakes[iCounter][indexRBottom] - _Snakes[iCounter][indexRTop];
            }
            iCounter++;
        }
        // if move down an odd number of rows, change direction
        if (deltaRows % 2 == 1)
        {
            ChangeDirection();
        }
        
    }

    private void CheckForWin(BoxView player)
    {
        // if the player is on row 1 -Winning Row
        // if the player is within dice roll of col 1 - winning col
    }
    #endregion
}

}

4

1 回答 1

0

这是我的自我游戏版本 - 控制台蛇和梯子

class Program
{
  public static void Main()
  {
     // Can create many new boards. This example is 2 players, 5 snakes and 2 ladders.
     var game = new SnakesAndLadders(2, 5, 2);
     game.PrintBoard();

     while (!game.IsFinished)
     {
        game.Play();
        game.PrintPlayers();
     }

     Console.WriteLine($"{game.WinnerName} - Won");
     Console.ReadLine();
  }
}

enum PropType
{
  Snake = 0,
  Ladder = 1
}

class SnakesAndLadders
{
  const int START = 1;
  const int END = 100;
  private Dictionary<int, Prop> _Props = new Dictionary<int, Prop>();
  private List<Player> _Players;
  private readonly Random _Randomizer = new Random();
  private Player _CurrentPlayer;
  public bool IsFinished { get; private set; }

  public string WinnerName
  {
     get => IsFinished ? _CurrentPlayer.Name : string.Empty;
  }

  public SnakesAndLadders(int players, int snakes, int ladders)
  {
     SetupPlayers(players);
     SetupSnakes(snakes);
     SetupLadders(ladders);
  }

  private void SetupPlayers(int playerCount)
  {
     _Players = new List<Player>(playerCount);

     for (int i = 0; i < playerCount; i++)
        _Players.Add(new Player(i + 1, $"Player{i + 1}", 1));

     for (int i = 0; i < playerCount; i++)
        _Players[i].Next = _Players[(i + 1) % playerCount];

     _CurrentPlayer = _Players.FirstOrDefault();
  }

  private void SetupSnakes(int snakeCount)
  {
     for (int i = 0; i < snakeCount;)
     {
        int start = _Randomizer.Next(100);
        int end = _Randomizer.Next(100);

        if (start < end || start == END || start == START)
           continue;

        if (_Props.TryGetValue(start, out var prop) == false)
        {
           _Props.Add(start, new Prop(PropType.Snake, start, end));
           i++;
        }
     }
  }

  private void SetupLadders(int ladderCount)
  {
     for (int i = 0; i < ladderCount;)
     {
        int start = _Randomizer.Next(100);
        int end = _Randomizer.Next(100);

        if (start > end || start == START)
           continue;

        if (_Props.TryGetValue(start, out var prop) == false)
        {
           _Props.Add(start, new Prop(PropType.Ladder, start, end));
           i++;
        }
     }
  }

  private int RollDice()
  {
     int chance = 0;
     int newMove = 0;
     do
     {
        chance = _Randomizer.Next(1, 7);
        Console.Write($"Dice Rolled: {chance} ");
        newMove += chance;
     } while (chance == 6);

     Console.WriteLine();
     return newMove < END ? newMove : END;
  }

  private int GetNewSpot(int spot, int move, string playerName)
  {
     if (_Props.TryGetValue(spot + move, out var prop))
     {
        Console.WriteLine($"{playerName} - {(prop.Type == PropType.Snake ? "Snake Bites" : "Climbs Ladder")}");
        return prop.End;
     }
     else
        return spot + move;
  }

  public void Play()
  {
     if (!IsFinished && _CurrentPlayer != null)
     {
        Console.Write($"{_CurrentPlayer.Name} - ");
        int moveValue = RollDice();
        // Check for Props
        moveValue = GetNewSpot(_CurrentPlayer.Spot, moveValue, _CurrentPlayer.Name);

        if (moveValue < END)
           _CurrentPlayer.Move(moveValue);
        else if (moveValue == END)
        {
           // Game Over Player Won
           _CurrentPlayer.Move(moveValue);
           IsFinished = true;
           return;
        }

        _CurrentPlayer = _CurrentPlayer.Next;
     }
  }

  public void PrintBoard()
  {
     var snakes = _Props.Values.Where(p => p.Type == PropType.Snake).ToList();
     Console.WriteLine($"Snakes[{snakes.Count}]: {string.Join(", ", snakes.Select(s => $"{s.Start}->{s.End}"))}");
     var ladders = _Props.Values.Where(p => p.Type == PropType.Ladder).ToList();
     Console.WriteLine($"Ladders[{ladders.Count}]: {string.Join(", ", ladders.Select(s => $"{s.Start}->{s.End}"))}");
  }

  public void PrintPlayers()
  {
     foreach (var player in _Players)
        Console.WriteLine($"{player.Id}-{player.Name} - At:{player.Spot}");
  }
}

class Prop
{
  public PropType Type { get; private set; }
  public int Start { get; private set; }
  public int End { get; private set; }

  public Prop(PropType pType, int start, int end)
  {
     Type = pType;
     Start = start;
     End = end;
  }
}

class Player
{
  public int Id { get; private set; }
  public string Name { get; private set; }
  public int Spot { get; private set; }
  public Player Next { get; set; }

  public Player(int id, string name, int spot)
  {
     Id = id;
     Name = name;
     Spot = spot;
  }

  public void Move(int newSpot)
  {
     Spot = newSpot;
  }
}
于 2020-11-19T09:24:17.390 回答