C# 在a<;列表>;
我正在制作一个在飞镖游戏中记录分数的程序,在这个程序中,你可以输入x个玩家,然后每个玩家按照他们输入名字的顺序投掷3支箭,这个过程会重复,直到有人得到501分,游戏结束。 玩家的C# 在a<;列表>;,c#,list,C#,List,我正在制作一个在飞镖游戏中记录分数的程序,在这个程序中,你可以输入x个玩家,然后每个玩家按照他们输入名字的顺序投掷3支箭,这个过程会重复,直到有人得到501分,游戏结束。 玩家的列表似乎运行得很好,但不知何故,我无法获得箭头/得分的列表。VisualStudio中没有错误,我可以很好地运行程序,但是如果我尝试使用foreach循环打印arrowslist中的值,则不会发生任何事情。据我所知,我做的箭头列表与我做的播放器列表完全一样,似乎工作正常,那么为什么箭头列表不工作呢 我为我的C#课程做这个
列表
似乎运行得很好,但不知何故,我无法获得箭头/得分的列表。VisualStudio中没有错误,我可以很好地运行程序,但是如果我尝试使用foreach
循环打印arrowslist
中的值,则不会发生任何事情。据我所知,我做的箭头列表
与我做的播放器
列表
完全一样,似乎工作正常,那么为什么箭头列表
不工作呢
我为我的C#课程做这个任务已经有一个星期了——我在这里发现了一些关于一个非常类似的任务的问题,但我仍然无法将这些建议用于我的代码(我不想只是复制和粘贴他们的整个程序,毕竟我是来学习的)。
我的整个程序的代码:
class Program
{
static void Main(string[] args)
{
Game game = new Game();
game.PlayGame();
}
}
class Game
{
public Game()
{
//default constructor that takes 0 arguments
}
int playernumber = 0;
List<Player> players = new List<Player>();
public void PlayGame()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = " Dartcounter 3000";
Console.WriteLine("Welcome to the Dartcounter 3000!");
NumberOfPlayers();
Console.WriteLine("");
foreach (var player in players)
{
if (player.ToString() == "Dator")
{
Console.WriteLine("Generating score for the NPC 'Dator'...");
Random random = new Random();
int randomThrow1 = random.Next(0, 60);
int randomThrow2 = random.Next(0, 60);
int randomThrow3 = random.Next(0, 60);
Arrows arrows = new Arrows(randomThrow1, randomThrow2, randomThrow3);
player.CalculatePoints();
}
else
{
Console.WriteLine("It's {0} turn to throw", player.ToString());
System.Threading.Thread.Sleep(500);
Console.WriteLine("Enter your score for the first arrow: ");
int arrowOne = int.Parse(Console.ReadLine());
Console.WriteLine("Your second arrow: ");
int arrowTwo = int.Parse(Console.ReadLine());
Console.WriteLine("Your third arrow: ");
int arrowThree = int.Parse(Console.ReadLine());
Arrows arrows = new Arrows(arrowOne, arrowTwo, arrowThree);
Console.WriteLine(arrows.ToString());
player.CalculatePoints();
}
}
Console.ReadLine();
}
// ------------ START of player methods in class Game ------------
public void NumberOfPlayers()
{
Console.WriteLine("Please enter the number of players: ");
start:
string playernumberinput = Console.ReadLine();
int value;
if (int.TryParse(playernumberinput, out value))
{
playernumber = int.Parse(playernumberinput);
AddPlayer();
}
else
{
Console.WriteLine("You did not input a number. Please try again: ");
goto start;
}
}
public void AddPlayer()
{
for (int i = 0; i < playernumber; i++)
{
Console.WriteLine("Enter name of player {0}:", i + 1);
players.Add(new Player(Console.ReadLine()));
}
}
// ------------ END of player methods in class Game ------------
}
class Arrows
{
public Arrows()
{
//default constructor that takes 0 arguements
}
public int roundScore;
public Arrows(int roundScore)
{
this.roundScore = roundScore;
}
public int arrowOne { get; set; }
public int arrowTwo { get; set; }
public int arrowThree { get; set; }
public Arrows(int Arrow1, int Arrow2, int Arrow3)
{
arrowOne = Arrow1;
arrowTwo = Arrow2;
arrowThree = Arrow3;
Player player = new Player();
player.AddArrows();
}
public int GetScore()
{
return arrowOne + arrowTwo + arrowThree;
}
public override string ToString()
{
return (string.Format("You got a total of {0} this round!", GetScore()));
}
}
class Player
{
public Player()
{
//default constructor that takes 0 arguments
}
public string Name;
public List<Arrows> arrowList = new List<Arrows>();
public Player(string Name)
{
this.Name = Name;
}
public void AddArrows()
{
Arrows arrows = new Arrows();
int roundScore = arrows.GetScore();
arrowList.Add(new Arrows(roundScore));
}
public void CalculatePoints()
{
foreach (var arrow in arrowList)
{
//Calculation to sum up the entry's in arrowList to see if someone has reached 501 points
}
}
public override string ToString()
{
return (string.Format("{0}", Name));
}
}
类程序
{
静态void Main(字符串[]参数)
{
游戏=新游戏();
游戏;
}
}
班级游戏
{
公共游戏()
{
//接受0个参数的默认构造函数
}
int playernumber=0;
列表玩家=新列表();
公共游戏
{
Console.ForegroundColor=ConsoleColor.Green;
Console.Title=“Dartcounter 3000”;
Console.WriteLine(“欢迎来到Dartcounter 3000!”);
玩家数量();
控制台。写线(“”);
foreach(玩家中的var玩家)
{
if(player.ToString()=“Dator”)
{
Console.WriteLine(“为NPC'Dator'生成分数…”);
随机=新随机();
int randomThrow1=随机。下一个(0,60);
int randomThrow2=随机。下一个(0,60);
int randomThrow3=random.Next(0,60);
箭头=新箭头(随机箭头1、随机箭头2、随机箭头3);
player.CalculatePoints();
}
其他的
{
WriteLine(“现在{0}该扔了”,player.ToString());
系统.线程.线程.睡眠(500);
WriteLine(“输入第一个箭头的分数:”);
int arrowOne=int.Parse(Console.ReadLine());
WriteLine(“你的第二支箭:”);
int arrowTwo=int.Parse(Console.ReadLine());
WriteLine(“你的第三支箭:”);
int arrowthore=int.Parse(Console.ReadLine());
箭头=新箭头(箭头一、箭头二、箭头三);
Console.WriteLine(arrows.ToString());
player.CalculatePoints();
}
}
Console.ReadLine();
}
//------课堂游戏中玩家方法的开始------------
公众人士
{
Console.WriteLine(“请输入玩家数量:”);
开始:
string PlayerNumber输入=Console.ReadLine();
int值;
if(int.TryParse(playerNumber输入,输出值))
{
playernumber=int.Parse(playernumber输入);
AddPlayer();
}
其他的
{
Console.WriteLine(“您没有输入数字。请重试:”;
转到开始;
}
}
public void AddPlayer()
{
对于(int i=0;i
代码需要。。。一些工作
不过,为了回答您的问题,您询问了为什么foreach
不打印任何内容。我假设你指的是这个:
foreach (var arrow in arrowList)
{
//Calculation to sum up the entry's in arrowList to see if someone has reached 501 points
}
唯一添加到该集合的是AddArrows
,这很奇怪,因为您使用默认构造函数创建箭头;调用GetScore
(它将始终返回0,因为您从未初始化箭头),然后使用该分数创建一个新的箭头
对象
不管怎样,调用该函数的唯一对象是Arrows
的重载构造函数,这更奇怪;特别是b
Player player = new Player();
player.AddArrows();
List<Player> players = GetPlayers();
Player winner = null;
int round = 0;
while (winner == null)
{
round++;
AnnounceRound(round);
foreach(Player p in players)
{
AnnouncePlayer(p);
p.GetDarts();
while (p.HasUnthrownDarts)
{
p.ThrowDart();
if (p.Score >= 501)
{
winner = p;
break;
}
}
if (winner != null) break;
}
}
Console.WriteLine("We have a winner! Congratulations, {0}!!", winner.Name);
Console.WriteLine("The final scores are:");
foreach(Player p in players.OrderByDescending(p => p.Score))
{
Console.WriteLine(" {0}: {1}", p.Name, p.Score);
}
public class Player { }
public static List<Player> GetPlayers()
{
var players = new List<Player>();
return players;
}
public static void AnnounceRound(int roundNumber)
{
Console.Clear();
var announcement = string.Format("Beginning Round #{0}", roundNumber);
Console.WriteLine(announcement);
// The next line writes out a list of dashes that is the
// exact length of the announcement (like an underline)
Console.WriteLine(new string('-', announcement.Length));
}
private static void AnnouncePlayer(Player player)
{
Console.WriteLine("{0}It's now {1}'s turn.{0}", Environment.NewLine, player.Name);
}
public class Player
{
public string Name { get; private set; }
public Player(string name)
{
Name = name;
}
}
public class Player
{
public string Name { get; private set; }
private int dartsInHand;
public void GrabDarts()
{
dartsInHand = 3;
}
}
public class Player
{
. . .
public bool HasUnthrownDarts { get { return dartsInHand > 0; } }
}
public class Player
{
. . .
public bool IsNpc { get; private set; }
public Player(string name, bool isNpc = false)
{
. . .
IsNPC = isNpc;
}
}
public int ThrowDart()
{
if (dartsInHand < 1)
{
throw new Exception(string.Format("Player {0} has no darts to throw.", Name));
}
int dartScore;
int thisDartNumber = (3 - dartsInHand) + 1;
if (IsNpc)
{
// Get a random score for non-player characters
dartScore = rnd.Next(0, 60);
Console.WriteLine("{0} threw dart #{1} for {2} point{3}",
Name, thisDartNumber, dartScore, dartScore == 1 ? "" : "s");
}
else
{
dartScore =
ConsoleHelper.GetIntFromUser(string.Format(
"{0}, please enter the score for dart #{1} (0-60): ",
Name, thisDartNumber), "<Invalid score>",
(i) => i >= 0 && i <= 60);
}
Score += dartScore;
dartsInHand--;
return dartScore;
}
public static class ConsoleHelper
{
/// <summary>
/// Gets an integer from the user
/// </summary>
/// <param name="prompt">A prompt to display to the user. Can be null.</param>
/// <param name="errorMessage">An error message to display if
/// the user enters an invalid integer. Can be null</param>
/// <param name="intValidator">A function to run which will validate
/// the integer. The integer will be passed to it, and it should
/// return true if the integer is valid. Can be null</param>
/// <returns>The integer entered by the user</returns>
public static int GetIntFromUser(string prompt, string errorMessage,
Func<int, bool> intValidator)
{
int intEntered;
while (true)
{
if (prompt != null) Console.Write(prompt);
var input = Console.ReadLine();
if (int.TryParse(input, out intEntered))
{
if (intValidator == null || intValidator(intEntered))
{
break;
}
}
if (errorMessage != null) Console.WriteLine(errorMessage);
}
return intEntered;
}
}
public class Player
{
. . .
private readonly Random rnd;
public Player(string name, bool isNpc = false)
{
. . .
rnd = new Random();
}
}
public class Player
{
. . .
public int Score { get; private set; }
}
. . .
var roundScore = 0;
while (p.HasUnthrownDarts)
{
roundScore += p.ThrowDart();
. . .
}
if (winner != null) break;
Console.WriteLine("{0} threw for {1} points this round.", p.Name, roundScore);
. . .
public class Player
{
. . .
public int MaxDarts { get; set; }
public Player(string name, bool isNpc = false)
{
. . .
MaxDarts = 3;
}
}
public void GrabDarts()
{
dartsInHand = MaxDarts;
}
public int ThrowDart()
{
. . .
int thisDartNumber = (MaxDarts - dartsInHand) + 1;
. . .
}
public static List<Player> GetPlayers()
{
var players = GetPlayers(false);
Console.WriteLine();
players.AddRange(GetPlayers(true));
return players;
}
private static List<Player> GetPlayers(bool npcPlayers)
{
var players = new List<Player>();
var playerType = npcPlayers ? "NPC" : "human";
int numberOfPlayers = ConsoleHelper.GetIntFromUser(
string.Format("How many {0} players will be playing? ", playerType),
"<Invalid number>", (x) => x >= 0);
for (int i = 1; i <= numberOfPlayers; i++)
{
string name;
if (npcPlayers)
{
// Generate computer player names
name = string.Format("ComputerPlayer{0}", i);
}
else
{
// Get human names from the user
Console.Write("Enter the name for player #{0}: ", i);
name = Console.ReadLine();
}
players.Add(new Player(name, npcPlayers));
}
return players;
}
public static void ShowScores(string message, List<Player> players)
{
if (message != null) Console.WriteLine(message);
foreach (var p in players.OrderByDescending(p => p.Score))
{
Console.WriteLine(" {0}: {1}", p.Name, p.Score);
}
}
private static void Main()
{
. . .
while (winner == null)
{
round++;
AnnounceRound(round);
ShowScores("The current standings are:", players);
. . .
}
Console.Clear();
Console.WriteLine("We have a winner! Congratulations, {0}!!", winner.Name);
ShowScores("The final scores are:", players);
. . .
}
public void Reset()
{
Score = 0;
dartsInHand = 0;
}
private static void Main()
{
Console.Write("Would you like to play a game of darts (y/n)? ");
var playGame = Console.ReadKey();
List<Player> players = null;
while (playGame.Key == ConsoleKey.Y)
{
Console.WriteLine(Environment.NewLine);
if (players == null)
{
players = GetPlayers();
}
else
{
players.ForEach(p => p.Reset());
}
. . .
Console.Write("{0}Would you like to play another game (y/n)? ",
Environment.NewLine);
playGame = Console.ReadKey();
}
Console.Write("{0}Thanks for playing! Press any key to quit...",
Environment.NewLine);
Console.ReadKey();
}