c# - storing scores for several players in a - -



c# - storing scores for several players in a <list> -

i'm making programme keeping scores in dart game can input x number of players , each player gets throw 3 arrows in order input names , repeats until reaches 501 points ends game. list players seems working fine somehow can't list arrows/score work. no error in visual studio , can run programme fine, if seek print out values in arrowlist foreach loop nil happens. far can tell i've done arrowlist did players list seems work intended, why isn't arrowlist working??

i've been stuck on task c# course of study week - i've found several questions here regarding similar task still can't suggestions work code (and don't want copy&paste whole programs, after i'm here learn). code whole program:

class programme { static void main(string[] args) { game game = new game(); game.playgame(); } } class game { public game() { //default constructor 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 dartcounter 3000!"); numberofplayers(); console.writeline(""); foreach (var player in players) { if (player.tostring() == "dator") { console.writeline("generating score 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 throw", player.tostring()); system.threading.thread.sleep(500); console.writeline("enter score first arrow: "); int arrowone = int.parse(console.readline()); console.writeline("your sec arrow: "); int arrowtwo = int.parse(console.readline()); console.writeline("your 3rd 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 come in 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 number. please seek again: "); goto start; } } public void addplayer() { (int = 0; < playernumber; i++) { console.writeline("enter name of player {0}:", + 1); players.add(new player(console.readline())); } } // ------------ end of player methods in class game ------------ } class arrows { public arrows() { //default constructor 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() { homecoming arrowone + arrowtwo + arrowthree; } public override string tostring() { homecoming (string.format("you got total of {0} round!", getscore())); } } class player { public player() { //default constructor 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 sum entry's in arrowlist see if has reached 501 points } } public override string tostring() { homecoming (string.format("{0}", name)); } }

to follow on this, thought i'd walk through process utilize when developing , see if helps. plus, reason, seemed fun project.

first, copied/pasted pseudo-code previous reply new console project, in main() method. bunch of stuff undefined, started defining code compile.

the first thing undefined player, created empty player class:

public class player { }

next, getplayers() method undefined. method need players game , homecoming them in list, created bare-bones method returns list of players:

public static list<player> getplayers() { var players = new list<player>(); homecoming players; }

next, announceround method undefined. know announce new round starting, , decided clear console window @ start of each round well:

public static void announceround(int roundnumber) { console.clear(); var proclamation = string.format("beginning round #{0}", roundnumber); console.writeline(announcement); // next line writes out list of dashes // exact length of proclamation (like underline) console.writeline(new string('-', announcement.length)); }

next, announceplayer method undefined. allow know who's turn is:

private static void announceplayer(player player) { console.writeline("{0}it's {1}'s turn.{0}", environment.newline, player.name); }

but when wrote code way wanted utilize it, there problem: player class not have name property. player class. create property read (by making setter private), , take name parameter constructor. way not allow create player , alter name later (this how want it, it's not necessary. if later decide create read-write, can alter setter public):

public class player { public string name { get; private set; } public player(string name) { name = name; } }

the next thing needs definition getdarts method on player object. i've had day sleep on it, don't name. methods begin get typically homecoming object, , intention method represents player walking dart board , grabbing darts. internally imagine update counter represents how many darts player holding. rename in original pseudo-code , in implementation in 'player':

public class player { public string name { get; private set; } private int dartsinhand; public void grabdarts() { dartsinhand = 3; } }

the next thing implement 'hasunthrowndarts' property. bool represent whether player has darts in hand or not.

public class player { . . . public bool hasunthrowndarts { { homecoming dartsinhand > 0; } } }

next, have throwdart method. things little trickier. noticed in implementation, allow human players come in own score, , npc players have random-generated score. means few things:

i have have property (or other means) differentiate between human , npc players i have different things in method depending on property.

the simplest thing create bool property defines player type (and add together constructor default of false). if there going more 2 types of players, create enum define types , property on player object of type. now, do:

public class player { . . . public bool isnpc { get; private set; } public player(string name, bool isnpc = false) { . . . isnpc = isnpc; } }

now, implement throwdart method. method score between 0 , 60, add together player's score, , decrement number of darts in player's hand. after farther thought, might want homecoming score generated in method "round score" can tallied if necessary, , decided output dart number , points well. usual, wrote code wanted use, plan implement afterwards.

public int throwdart() { if (dartsinhand < 1) { throw new exception(string.format("player {0} has no darts throw.", name)); } int dartscore; int thisdartnumber = (3 - dartsinhand) + 1; if (isnpc) { // random score non-player characters dartscore = rnd.next(0, 60); console.writeline("{0} threw dart #{1} {2} point{3}", name, thisdartnumber, dartscore, dartscore == 1 ? "" : "s"); } else { dartscore = consolehelper.getintfromuser(string.format( "{0}, please come in score dart #{1} (0-60): ", name, thisdartnumber), "<invalid score>", (i) => >= 0 && <= 60); } score += dartscore; dartsinhand--; homecoming dartscore; }

as wrote this, realized needed integer user. sounds simple, requires bit of code validation. user come in non-integer string, in case i'd have inquire them again. come in number that's outside of our bounds (0-60), in case have inquire them again. because code semi-complex, , because have feeling may need other integers user (we may need inquire how many npc players want play against), decided create new class called consolehelper , add together method getintfromuser there. method string console, convert integer, apply custom validation (if necessary), , homecoming it. i've added comments help describe how works well:

public static class consolehelper { /// <summary> /// gets integer user /// </summary> /// <param name="prompt">a prompt display user. can null.</param> /// <param name="errormessage">an error message display if /// user enters invalid integer. can null</param> /// <param name="intvalidator">a function run validate /// integer. integer passed it, , should /// homecoming true if integer valid. can null</param> /// <returns>the integer entered 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); } homecoming intentered; } }

i realized need random numbers npc players. this, created private random property , set in constructor:

public class player { . . . private readonly random rnd; public player(string name, bool isnpc = false) { . . . rnd = new random(); } }

and updating imaginary score property in method, let's implement now, too:

public class player { . . . public int score { get; private set; } }

this seems time take advantage of fact throwdarts returns score dart number. each player, each round, can give them summary of how threw round:

. . . var roundscore = 0; while (p.hasunthrowndarts) { roundscore += p.throwdart(); . . . } if (winner != null) break; console.writeline("{0} threw {1} points round.", p.name, roundscore); . . .

another thing decided add together 'maxdarts' property player. allows me store number of darts in single place, rather have hard-coded '3's everywhere. added player class , updated hard-coded values.

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; . . . }

so, compiling, lastly thing left implement getplayers method. in order collect both human , computer player info user without writing duplicate code, created sec getplayers method takes in boolean says if should computer players or not. then, getplayers() method calls overload twice - 1 time false , 1 time true. here both methods:

public static list<player> getplayers() { var players = getplayers(false); console.writeline(); players.addrange(getplayers(true)); homecoming 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 playing? ", playertype), "<invalid number>", (x) => x >= 0); (int = 1; <= numberofplayers; i++) { string name; if (npcplayers) { // generate computer player names name = string.format("computerplayer{0}", i); } else { // human names user console.write("enter name player #{0}: ", i); name = console.readline(); } players.add(new player(name, npcplayers)); } homecoming players; }

one other thing decided is, @ origin of each round, display current standings. code re-create of code @ end of game (that shows final scores). because should never write duplicated code if possible, wrapped in method called showscores:

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); } }

then added code phone call method @ origin of each round, , @ end of game:

private static void main() { . . . while (winner == null) { round++; announceround(round); showscores("the current standings are:", players); . . . } console.clear(); console.writeline("we have winner! congratulations, {0}!!", winner.name); showscores("the final scores are:", players); . . . }

now we're getting there. decided wrap whole game within loop, in order allow users play more 1 game per session. enable this, did few things. first, added reset() method player class score go zero:

public void reset() { score = 0; dartsinhand = 0; }

then wrapped code in loop, , reset player's scores (if existed):

private static void main() { console.write("would play 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 play game (y/n)? ", environment.newline); playgame = console.readkey(); } console.write("{0}thanks playing! press key quit...", environment.newline); console.readkey(); }

hope trip through brain helped in way! :)

c# list

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -