我正在制作黑杰克游戏,我需要使用switch case语句将A转换为11,将T,Q,J和K转换为10,但是我不知道如何编写代码。有人会介意帮我解决这个问题吗?
到目前为止,我有:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Black Jack!\n");
Console.WriteLine("Pick two cards to add to your hand\n");
Console.WriteLine("Cards 2, 3, 4, 5, 6, 7, 8, 9 all are worth face value\n");
Console.WriteLine("Ace (A) is worth 11,Ten (T), Jack (J), Queen (Q), and King (K) are all worth 10 points\n");
Console.WriteLine("Whichever sum is higher, that player is declared the winner\n");
Console.WriteLine("What are player one's cards?");
Console.WriteLine("Enter card1 =?");
Console.WriteLine("Enter card2 =?");
double card1 = Double.Parse(Console.ReadLine());
double card2 = Double.Parse(Console.ReadLine());
Console.WriteLine("You entered: [" + card1, card2 + "]");
Console.WriteLine("What are player two's cards?");
Console.WriteLine("Enter card3 =?");
Console.WriteLine("Enter card4 =?");
double card3 = Double.Parse(Console.ReadLine());
double card4 = Double.Parse(Console.ReadLine());
Console.WriteLine("You entered: [" + card3, card4 + "]");
Console.ReadLine();
{
Console.WriteLine("Calculate player 1: [" + "card1 + card2" + "]");
Console.WriteLine("Calculate player 2: [" + "card3 + card4" + "]");
{
if (card1 + card2 > card3 + card4)
Console.WriteLine("Player One Wins!");
else if (card3 + card4 > card1 + card2)
Console.WriteLine("Player Two Wins!");
Console.ReadLine();
答案 0 :(得分:2)
我不确定为什么开关会冗长。
int parseCard(char card)
{
if ( card >= '2' && card <= '9' ) {
return card - '0';
}
switch ( card ) {
case 'T':
case 'J':
case 'Q':
case 'K':
return 10;
case 'A':
return 11;
default:
throw new ArgumentException("card not valid", "card");
}
}
答案 1 :(得分:1)
有很多方法可以做到这一点,但我可能不会在这里使用开关,因为它会很冗长。这是一种方法:
int parseCard(char card)
{
if (card >= '2' && card <= '9')
return card - '0';
if (card == 'T' || card == 'J' || card == 'Q' || card == 'K')
return 10;
if (card == 'A')
return 11;
throw new ArgumentException("card not valid", "card");
}
您可能更喜欢制作tryParseCard
版本,以避免在用户输入无效输入时出现异常。