绘制棋盘游戏“令牌”到棋盘格和数据网格视图

时间:2014-10-20 04:24:22

标签: c# datagrid

我正在为我的c#课练习。我在某个特定部分遇到了一些麻烦,非常感谢一些帮助。

我正在进行一项练习,其中我们获得了一个不完整的项目文件。该项目旨在创建一个棋盘游戏,最多可以让六个人玩(理论上相当简单)。我目前坚持的部分是在棋盘上显示玩家“代币”。

这是最终板的意思:enter image description here

正如您所看到的,在“0”(起始方块)上有6个圆圈(或标记),在右侧有一个数据网格视图,其中列显示相关信息(颜色,名称,金钱,赢家)。

这是我迄今为止所做的: enter image description here

如您所见,我能够显示玩家名称和金钱。虽然我无法将颜色显示在起始方块或数据网格视图中。相反,我得到了这个:

enter image description here

两个相关的课程如下:

Player.CS持有玩家对象代码(构造函数等)(提前抱歉文本墙,我不确定哪些部分可以省略)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;


namespace SharedGameClasses {
    /// <summary>
    /// Models a player who is currently located on a particular square 
    /// with a certain amount of money.
    /// </summary>
    public class Player {

        private const int INITIAL_AMOUNT = 100;

        // name of the player
        private string name;
        public string Name {
            get {
                return name;
            }
            set {
                name = value;
            }
        }

        // amount of money owned by player
        private int money;
        public int Money {
            get {
                return money;
            }
            set {
                money = value;
            }
        }

        // current square that player is on
        private Square location; 
        public Square Location {
            get {
                return location;
            }
            set {
                location = value;

            }
        }

        // whether the player is a winner, in the current game.
        private bool winner;
        public bool Winner {
            get {
                return winner;
            }
            set {
                winner = value;
            }
        }

        // PlayerTokenColour and PlayerTokenImage provide colours for the players' tokens (or "pieces"). 
        private Brush playerTokenColour;
        public Brush PlayerTokenColour {
            get {
                return playerTokenColour;
            }
            set {
                playerTokenColour = value;
                playerTokenImage = new Bitmap(1, 1);
                using (Graphics g = Graphics.FromImage(PlayerTokenImage)) {
                    g.FillRectangle(playerTokenColour, 0, 0, 1, 1);
                } 
            }
        }

        private Image playerTokenImage;
        public Image PlayerTokenImage {
            get {
                return playerTokenImage;
            }
        }

        /// <summary>
        /// Parameterless constructor.
        /// Do not want the generic default constructor to be used
        /// as there is no way to set the player's name.
        /// This replaces the compiler's generic default constructor.
        /// Pre:  none
        /// Post: ALWAYS throws an ArgumentException.
        /// </summary>
        /// <remarks>NOT TO BE USED!</remarks>
        public Player() {
            throw new ArgumentException("Parameterless constructor invalid.");
        } // end Player constructor

        /// <summary>
        /// Constructor with initialising parameters.
        /// Pre:  name to be used for this player.
        /// Post: this player object has all attributes initialised
        /// </summary>
        /// <param name="name">Name for this player</param>
        public Player(String name, Square initialLocation, Brush playerToken){

            Name = name;
            location = initialLocation;
            Money = INITIAL_AMOUNT;
            PlayerTokenColour = playerToken;


            //######################### Code needs to be added here ##########################################

        } // end Player constructor

        /// <summary>
        /// Rolls the two dice to determine 
        ///     the number of squares to move forward; and
        ///     moves the player's location along the board; and
        ///     obtains the effect of landing on their final square.
        /// Pre:  dice are initialised
        /// Post: the player is moved along the board and the effect
        ///     of the location the player landed on is applied.
        /// </summary>
        /// <param name="d1">first die</param>
        /// <param name="d2">second die</param>
        public void Play(Die d1, Die d2){

           var roll1 = d1.Roll();
           var roll2 = d2.Roll();

            int numofSquares = roll1 + roll2;

            Move(numofSquares);


            //######################### Code needs to be added here ##########################################

        } // end Play.

        /// <summary>
        /// Moves player the required number of squares forward
        /// Pre:  the number of squares to move forward
        /// Post: the player is moved along the board.
        /// NOTE: Refer to Square.cs regarding the NextSquare property.
        /// </summary>
        /// <param name="numberOfSquares">the number of squares to move</param>
        private void Move(int numberOfSquares) {



            //######################### Code needs to be added here ##########################################3

        } //end Move

        /// <summary>
        /// Increments the player's money by amount
        /// Pre:  amount > 0
        /// Post: the player's money amount is increased.
        /// </summary>
        /// <param name="amount">increment amount</param>
        public void Credit(int amount) {

            Money = Money + amount;

        } //end Credit


        /// <summary>
        /// Decreases the player's money by amount if 
        ///     the player can afford it; otherwise,
        ///     sets the player's money to 0.
        /// Pre:  amount > 0
        /// Post: player's money is decremented by amount if possible
        ///       but final amount is not below zero
        /// </summary>
        /// <param name="amount">decrement amount</param>
        public void Debit(int amount){

            const int loseamount = 25;

            if (Money >= 25){
                Money = Money - loseamount;
            } else if (Money < 25){
                Money = 0;
            }

            //######################### Code needs to be added here ##########################################3
        } //end Debit


    } //end class Player
}

和HareandTortoiseGame.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Drawing;

using System.ComponentModel;  // for BindingList.

namespace SharedGameClasses {
    /// <summary>
    /// Plays a game called Hare and the Tortoise
    /// </summary>
    public static class HareAndTortoiseGame {

    // Minimum and maximum players per game
    private const int MIN_PLAYERS = 2;
    public const int MAX_PLAYERS = 6;

    // The dice
    private static Die die1 = new Die(), die2 = new Die();

    // A BindingList is like an array that can grow and shrink. 
    // 
    // Using a BindingList will make it easier to implement the GUI with a DataGridView
    private static BindingList<Player> players = new BindingList<Player>();
    public static BindingList<Player> Players {
        get {
            return players;
        }
    }


    private static int numberOfPlayers = 6;  // The value 6 is purely to avoid compiler errors.

    public static int NumberOfPlayers {
        get {
            return numberOfPlayers;
        }
        set {
            numberOfPlayers = value;
        }
    }

    // Is the current game finished?
    private static bool finished = false;
    public static bool Finished {
        get {
            return finished;
        }
    }

    /// Some default player names.  
    /// 
    /// These are purely for testing purposes and when initialising the players at the start
    /// 
    /// These values are intended to be read-only.  I.e. the program code should never update this array.
    private static string[] defaultNames = { "One", "Two", "Three", "Four", "Five", "Six" };

    // Some colours for the players' tokens (or "pieces"). 
    private static Brush[] playerTokenColours = new Brush[MAX_PLAYERS] { Brushes.Black, Brushes.Red, 
                                                          Brushes.Gold, Brushes.GreenYellow, 
                                                          Brushes.Fuchsia, Brushes.White };



    /// <summary>
    /// Initialises each of the players and adds them to the players BindingList.
    /// This method is called only once, when the game first startsfrom HareAndTortoiseForm.
    ///
    /// Pre:  none.
    /// Post: all the game's players are initialised.
    /// </summary>
    public static void InitialiseAllThePlayers(){


        //Player Playerone = new Player(defaultNames[1], Board.Squares[0]);
        int i = 0;

        while (i < NumberOfPlayers){
            players.Add(new Player(defaultNames[i], Board.Squares[0], playerTokenColours[i]));
            i++;
        }







        //##################### Code needs to be added here. ############################################################

    } // end InitialiseAllThePlayers


    /// <summary>
    /// Puts all the players on the Start square.
    /// Pre:  none.
    /// Post: the game is reset as though it is being played for the first time.
    /// </summary>
    public static void SetPlayersAtTheStart() {


        //##################### Code needs to be added here. ############################################################


    } // end SetPlayersAtTheStart


    public static void PlayOneRound(){

        InitialiseAllThePlayers();

    }






} //end class HareAndTortoiseGame
}

任何帮助/提示将不胜感激,谢谢!如果您需要更多信息,请告诉我

编辑:另外,我相信来自另一个类(HareandTortoiseForm.cs)的这些方法是相关的

  /// <summary>
            /// Constructor with initialising parameters.
            /// Pre:  none.
            /// Post: the form is initialised, ready for the game to start.
            /// </summary>
            public HareAndTortoiseForm() {
                InitializeComponent();
                HareAndTortoiseGame.NumberOfPlayers = HareAndTortoiseGame.MAX_PLAYERS; // Max players, by default.
                HareAndTortoiseGame.InitialiseAllThePlayers();
                Board.SetUpBoard();
                SetupTheGui();
                ResetGame();
        }

还有ResetGame(),我觉得我错了(我想我需要添加代码)

 /// <summary>
        /// Resets the game, including putting all the players on the Start square.
        /// This requires updating what is displayed in the GUI, 
        /// as well as resetting the attrtibutes of HareAndTortoiseGame .
        /// This method is used by both the Reset button and 
        /// when a new value is chosen in the Number of Players ComboBox.
        /// Pre:  none.
        /// Post: the form displays the game in the same state as when the program first starts 
        ///       (except that any user names that the player has entered are not reset).
        /// </summary>
        private void ResetGame() {

            // ########################### Code needs to be written  ###############################################
        }

编辑2:

 /// <summary>
        /// Tells you which SquareControl object is associated with a given square number.
        /// Pre:  a valid squareNumber is specified; and
        ///       the boardTableLayoutPanel is properly constructed.
        /// Post: the SquareControl object associated with the square number is returned.
        /// </summary>
        /// <param name="squareNumber">The square number.</param>
        /// <returns>Returns the SquareControl object associated with the square number.</returns>
        private SquareControl SquareControlAt(int squareNumber) {
            int rowNumber;
            int columnNumber;
            MapSquareNumToScreenRowAndColumn(squareNumber, out rowNumber, out columnNumber);

            // Uncomment the following line once you've added the boardTableLayoutPanel to your form.
            return (SquareControl) boardTableLayoutPanel.GetControlFromPosition(columnNumber, rowNumber);

            // Delete the following line once you've added the boardTableLayoutPanel to your form.
           // return null;
        } //end SquareControlAt

2 个答案:

答案 0 :(得分:0)

我无法帮助您将代币放在DataGridView上,但我宁愿将整个代码转换为TableLayoutPanel。这样你就可以轻松地分别处理每个单元格,并且标记可以只是一些控件,这些控件设置为可见或不可用。

答案 1 :(得分:0)

只需将颜色分配给Cells的相关DataGridView即可显示颜色:

DGV.Rows[playerIndex].Cells[0].Style.BackColor = playerColor;

可能应该绘制代币

  • 在您Bitmap
  • 中显示的PictureBox
  • 或直接在其Panel事件中的Paint上。

两个选项都没问题。这个令牌区域在游戏中是否会发生变化? 项目中是否有迹象可以给你一个提示..?

在这两种情况下,您都需要Graphics.FillEllipse方法。