更新於 2024/10/12閱讀時間約 8 分鐘

系統開發-初始化撲克牌

    21點遊戲中需要撲克牌,四種花色,每種花色1-13張,分別為1,2,3,4,5,6,7,8,9,10,J,Q,K,共52張。


    我們先將一張撲克牌定義為Card物件,並定義其屬性為花色和點數。

    class Card
    {
    public string Suit { get; set; }
    public int Rank { get; set; }

    // Card建構函數
    public Card(string suit, int rank)
    {
    Suit = suit; //花色
    Rank = rank; //點數
    }

    // 覆寫ToString()方法來顯示撲克牌訊息
    public override string ToString()
    {
    string suitName = "";

    switch(Suit)
    {
    case "S":
    suitName = "黑桃";
    break;
    case "H":
    suitName = "紅心";
    break;
    case "D":
    suitName = "方塊";
    break;
    case "C":
    suitName = "梅花";
    break;
    }

    return $"{suitName}{Rank}";
    }
    }


    再建立一副牌共52張,並設定其花色與點數,再顯示到畫面上,以下為完整程式碼


    Default.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>
    </form>
    </body>
    </html>

    Default.aspx.cs

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    string[] suits = { "S" , "H" , "D" , "C"}; //"S黑桃" , "H紅心" , "D方塊" , "C梅花"

    Card[] cards = new Card[52]; //一副牌52張
    int index = 0;

    for(int i=0; i<suits.Length; i++) //四種花色
    {
    for(int j=1; j<=13; j++) //一種花色13張牌1-13
    {
    cards[index] = new Card(suits[i], j);
    index++;
    }
    }

    for(int i=0; i<cards.Length; i++)
    {
    if(i%13 == 0) //13張牌排成一行
    {
    Label1.Text += $"<br>{cards[i].ToString()}"; //換行
    }
    else
    {
    //Label1.Text += $",{cards[i].ToString()}"; //Card class預設顯示方式
    Label1.Text += $",{cards[i].Suit}{cards[i].Rank}"; //自訂顯示方式
    }
    }
    }
    }

    class Card
    {
    public string Suit { get; set; }
    public int Rank { get; set; }

    // Card建構函數
    public Card(string suit, int rank)
    {
    Suit = suit; //花色
    Rank = rank; //點數
    }

    // 覆寫ToString()方法來顯示撲克牌訊息
    public override string ToString()
    {
    string suitName = "";

    switch(Suit)
    {
    case "S":
    suitName = "黑桃";
    break;
    case "H":
    suitName = "紅心";
    break;
    case "D":
    suitName = "方塊";
    break;
    case "C":
    suitName = "梅花";
    break;
    }

    return $"{suitName}{Rank}";
    }
    }

    執行結果:


    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.