Solution - Challenge Simple Darts

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

Introduction

This is the solution for the challenge called ChallengeSimpleDarts, which was designed to test your knowledge of classes and methods. If you had trouble completing this challenge, read on as far as you need to solve the issue at hand. Fix it, and then attempt to finish the rest of the challenge on your own. Do as much as you can without help and remember, it's OK to struggle with this. Struggling is how you learn. With that said, read on for the provided solution.

Step 1: Create a Project and Class Library

Begin by creating a new ASP.NET Web Application, calling it ChallengeSimpleDarts. Add a Default.aspx page to it as we've done up until this series. Next, as per the requirements for this challenge, add a new Project to your solution. This will be a Class Library called Darts. Right-click on the Solution and select Add > New Project...


AddProject


From the resulting dialog box, select Class Library and name it Darts:


ClassLibrary


Press OK to add the Class Library to your existing solution. Right-click on the Class1.cs that was generated in the Darts Library and rename it to Dart.cs. A message from Visual Studio will appear asking if you'd like to rename all references to the class. Click yes to continue.

Step 2: Populating the Dart Class

One of the requirements of this challenge is to pass in an instance of the Random class each time a new Dart is created in memory. To do this, create a constructor for Dart within the Dart class, including a reference to an instance of System.Random. Above it, set a private property to an instance of Random called _random:


DartRandomReference


Within the constructor, set the _random instance equal to the constructor's random property:


RandomEqualRandom


Next, create a public int property called Score for the Dart class. Then, create a void method called Throw() that sets Score equal to a random value between 0 and 20:


ScoreRandom


Tip:

Notice that the maximum value passed in for the _random.Next is 21, not 20. This is because the property being assigned 21 is called the exclusive upper-bound. This means that it will not include the number passed in for the maximum. Think of mathematics, how <= 20 is different than <20. One is inclusive of the number 20, the other is exclusive or excludes the number.

The next requirement for the Dart class was to determine if the Dart landed on either the double or triple band of the board. Since this is simulation, there is a 5% chance of the Dart hitting a double band and a 5% chance of it hitting the triple band. We'll create two boolean properties for the Dart: IsDouble and IsTriple:


DartProperties


In order to determine if either of these cases are true, create an integer within Throw() called multiplier, setting it equal to a random number between 1 and 100. We'll take the result of that method and check if the number is between 91 and 95, or between 96 and 100, each representing a 5% chance. If either case is true, we'll set the appropriate property to true:


DartThrowMethod


Step 2: Create a Game and Player Class

The next requirement for this challenge requires the project to have a Game class, as well as a Player class or variable. We'll create a Class in order to access its properties and methods.

Before creating the classes, we'll first need to add a Default.aspx page. Once created, add an okButton and resultLabel to the page:


DefaultPage


Double-click the okButton in order to generate the okButton_Click EventHandler, where our methods will be called from later on. Before dealing with that, right-click on the ChallengeSimpleDarts Project in the Solution Explorer and select Add > Class... In the dialog box, name the class Game.cs. Repeat this process to create a Player.cs class.

Step 3: Creating Properties for the Classes

The Player class will be the simplest of our classes, with only to properties: Score and Name:


PlayerProperties


In the Game class, we'll need to create references to each of the two Players, like so:


GamePlayerReferences


Because the Player class has a property for the Player's name, we'll modify the constructor for the Game class to take in two string names. Inside the constructor, we'll initialize the two Players and assign their names:


GameConstructor


Step 4: Reference the Darts Project

Because our Dart class is located within a different Project (The Darts class library), we'll need to add it as a reference to the ChallengeSimpleDarts Project. To do this, right-click on 'References' for ChallengeSimpleDarts in the Solution Explorer and click 'Add Reference'. In the dialog box, check the box that says 'Darts':


DartsReference


In order to access the the Dart class' properties and methods, you'll need to reference it in your code. To do this, add a using statement for Darts at the top of the Game class:


UsingStatements


Step 5: Adding the First Methods

What we need to do now that all the classes and properties are in place is create methods to handle the logic behind the game. To begin, beneath the constructor in the Game class write the following code for a Play() method:


PlayMethod


This code continues to execute while the score of both players remains under 300. Notice that we've called a playRound() method that has not yet been created. Create a code snippet for this method by highlighting it and pressing Ctrl+ '.' Make sure to change the name of the Player input parameter to simply player since this method will be used for both players:


PlayRoundInitial


Each time this method is called, three instances of Dart need to be thrown, completing one turn for the Player that called it. To do this, create a for() loop that increments from 0 until it's no long less than 3:


PlayRoundForLoop


Next, create an instance of the Random class and call it _random. In the constructor for the Game class, initialize _random like so:


RandomGameConstructor


We'll then need to create an instance of the Dart class within the playRound() method, passing in _random. Then, call the Dart's Throw() method:


PlayRoundThrow


Step 6: Displaying the Game Results

Even though we haven't yet written the code to calculate the Players' scores, our Play() method is looking to return a string value back to its caller (eventually the okButton_Click). This string value will come from another method called displayResults(), called within the Play() method. After calling it, create a stub for the method:


displayResultsStub


This method will return a formatted string that displays _player1's Score and _player2's Score:


displayResults


Notice that this method does not yet return which player is the winner. In order to do this, we'll modify the line that returns the result. Instead, we'll add on to the result a string that holds the winning player's name based on the result of a ternary operator:


displayResultsTernary


This checks to see which player has the higher score, and returns the Name of that player.

Step 7: Calculating the Score

The requirements for this challenge require a new class called Score to be created in order to take the value from Dart.Throw() and determine the actual score based on that. Begin by adding a new class to your Project called Score.cs, and add a using statement for the Darts Project at the top. Inside this class, write the following code to create a ScoreDart() method:


ScoreDartInitial


This method takes in a Player and a Dart in order to call the Dart's Throw() method and access its properties, as well as modify the Player's score. To begin, initialize an integer called score, setting its value to 0. Then, perform conditional checks to determine if the IsTriple or IsDouble properties for the dart are true, and setting the score accordingly:


ScoreMultiplier


Notice that this does not yet account for a bullseye (when dart.Score = 0). There are two possibilities for the bullseye: 25 points, or 50 depending on if it landed in the red or green bullseye ring. The logic for setting the score will simply be to check if dart.Score == 0, and if it also landed in the inner bullseye (represented by IsTriple):


BullseyeCheck


Finally, at the bottom of this ScoreDart() method, increment player.Score by the score variable we created:


ScoreDartFinal


Step 8: Calling the Methods:

Now that the logic is in place for the entire game, we need to go through and make sure we call all of the individual methods we've created. The ScoreDart() method will be called in the Game.PlayRound(), passing in the player and dart:


PlayRoundFinals


Next, in the okButton_Click, we need create a reference to the Game class and call its Play() method:


okButtonClick


Note: There is no requirement for what the players' names should be. You can set them to whatever string value you want!

Now, save and run your project to see the results!


Winner!


Conclusion

This completes the solution for ChallengeSimpleDarts. Hopefully you were able to put all the pieces together, but it's alright if you weren't able to your first time. Try to reinforce the concepts related to classes, as well as referencing different class libraries in your Solution. If you didn't get it your first time, try again later. Keep trying until you understand all the concepts, and then move on with the rest of the course. Good job!


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment