Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Making the Game of Yahtzee in C# in an Afternoon?

0.00/5 (No votes)
10 Jun 2015 1  
A basic Game of Yahtzee

Introduction

This is a basic way to use the Stack Class for a Board or Coard Game. I came across the Stack Class as a way to solve the issue of generating a deck of cards for a card game. Creating random numbers on the fly lead to searching for an easy to use alternative. This is also an exercise in flow control, and using simple counters to make events happen or bring them to an end.

Background

I am learning the .NET languages and wanted to make a basic game that worked.

Using the Code

References to Use:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

The code consists of a form and a result class, and nothing more. I am new programmer, learning the Microsoft Products. So here it goes. This is my first go at a C# program, so excuse my lack of convention and etiquette.

The game is set up with 1 roll button 5 text boxes or Labels for the die's face value. There are 10 buttons to hold and unhold the respective dice. The choice of the outcomes is done by using 13 checkboxes with changed event handler and a counter attached to this. I have 2 result buttons, one for the 3 rolls which is pressed when the check box selection is excepted, the other when all the outcomes have a result.

Below is the list of the variables I used to control counts and the stack. The examples are shown.

The most important variable is the int Stack as it makes the 'dice a roll'.

// controls the roll count per turn
int begrollcount = 3;
// controls whether the die is held
int holdcount1 = new int();
// some counter for the bonus yahtzee
int yzbonuscount = 0;
int yzbonus = 0;   
// counter that is turned on when a scoring option is chosen and excepted
int threekcnt = 0;
Stack<int> frank = new Stack<int>();       

The first call is to make 195 dice rolls up front, so the stacks contents can be popped out.

 public Form1()
        {
            InitializeComponent();
            button13.Hide();
            //calling the function rolls to play randomize a stack of 195 rolls of the dice
            rolls();  
        }
        private void rolls()
        {
            //the stack is a global variable and is populated with in this function
            Stack<Int32> mcsc = new Stack<int>();
            //the random sorts out the one through 6
            Random mark = new Random();
            //the array of 195
            int[] rolls = new int[195];
            //running through the array to make 195 attempts
            for (int i = 0; i < 195; i++)
            {
               rolls[i] =mark.Next(1,7);
            }
          
            // filling the stack
        
            foreach(int element in rolls)
            {
               mcsc.push(elemnt);
            }
          }

After pre determining the Rolls value, we need to set up how to hold and roll of the buttons. The variable begrollcount will control that 3 rolls are applied to each turn.

            private void button1_Click(object sender, EventArgs e)
            {
            if (holdcount1 < 1)
            {
                int francis1 = frank.Pop();
                textBox1.Text = francis1.ToString();
             }
             // this will perform the roll of the die if there is not a hold, this repeated 5 times
             }
            
             private void button2_Click(object sender, EventArgs e)
             {
             {
              holdcount1 += 1;
              button11.Show();
              button2.Hide();
             }

             // this is a hold button that implements the count to hold the die, again this will be 
             // repeated 5 times
            }
              private void button11_Click(object sender, EventArgs e)
             {
               holdcount5 -= 1;
               button2.Show();
               button11.Hide();
             }
             // this is the unhold button and logic

Below, I create the methods and variables necessary to make the scores and check if the criteria is met for this score. I have done this by creating an int array which converts the text to an int. The array will be passed on to my results class to work out the scores by returning an integer value for the score based on those values meet the logic in the result class method. This all happens when a Check Box is checked, and a counter is moved forward. Upon this, the logic checks a value of 1, then run the below code when met. The code uses a counter to run the logic to generate the games scores and count the events to end the game and score accordingly.

        // forming the values to send to the result class to return a score 
        private void button12_Click(object sender, EventArgs e)
        {
            //create a 1d array to capture the results in and 5 single integers to fill these values
            int[] resultset = new int[5];
            int rs1 = new int();
            int rs2 = new int();
            int rs3 = new int();
            int rs4 = new int();
            int rs5 = new int(); 
         }
         // the integers are made from converting the textbox/ label text to an int. 
            resultset[0] = rs1;
            resultset[1] = rs2;
            resultset[2] = rs3;
            resultset[3] = rs4;
            resultset[4] = rs5;
       
         // this array is sent with the code below, 
         // I also add another function to check for a previous          
         // yahtzee. This happens for each time the check box for the result is clicked and accepted 
 
            if (threekcnt == 1)
              {
                 bonuscheck(rs1, rs2, rs3, rs4, rs5);
                ResultClass alfa = new ResultClass();
                int rolledscore = new int();
                rolledscore = alfa.threeofakind(resultset);
                label24.Text = rolledscore.ToString(); 
               }

         //below is how I handle the clicking of the checkbox 

          private void ThreeofAKind_CheckedChanged(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show
            ("Please Confirm you wish to Score or Use three of a kind", 
            "Confirm", MessageBoxButtons.YesNo);
            if (res == DialogResult.Yes)
            {       
                threekcnt += 1;
                button12_Click(sender, e);
                ThreeofAKind.Hide();
                eventscount += 1;
            }
            if (res == DialogResult.No)
            {
                MessageBox.Show("Please Choose another option");
                return;
            }
            
            if (eventscount <= 13)
            {
                begrollcount = 3;
                button1.Show();
                textBox1.Text = "";
                textBox2.Text = "";
                textBox3.Text = "";
                textBox4.Text = "";
                textBox5.Text = "";

                if (holdcount1 >= 1)
                    button11_Click(sender, e);
                if (holdcount2 >= 1)
                    button10_Click(sender, e);
                if (holdcount3 >= 1)
                    button9_Click(sender, e);
                if (holdcount4 >= 1)
                    button8_Click(sender, e);
                if (holdcount5 >= 1)
                    button7_Click(sender, e);
                label36.Text = threekcnt.ToString();
                threekcnt -= 1;
             //  this ends the game
            if (eventscount == 13)
            {
                button13_Click(sender, e);
            }

            }

            // bonus yahtzee check            
                
            private void bonuscheck(int r1, int r2, int r3, int r4, int r5)
            {
            int nopssthroughchk = 1;
            if(r1 == 1 && label13.Text == "0" || 
            r1 == 2 && label12.Text == "0" 
            ||r1 == 3 && label11.Text == "0" ||
            r1 == 4 && label10.Text == "0" ||
              r1 == 5 && label9.Text == "0" || 
              r1 == 6 && label8.Text == "0" )
            {
                nopssthroughchk -= 1;
            }
 
              if (yzbonuscount == 1 &&  r1 == r2 && r2 ==r3 && 
              r3 == r4 && r4 == r5 && nopssthroughchk 
                  == 1)
                  {
                     yzbonus += 100;                     
                  }
             }   

Result Class

using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yahtzeemk2
{
    class ResultClass
    {
        int total = new int();
        public int totalofdie(int[] numero)
        {
          for(int i = 0; i< 5; i++)
            {
                total += numero[i];
            }
            return total;
        }
        
        public int threeofakind(int[] numero) 
        {
            
             
             int result = new int();
             if (numero[0] == numero[1] && numero[1] == numero[2] || 
             numero[0] == numero[1] && numero[1]== numero[3] ||
             numero[0] == numero[1] && numero[1] == numero[4] || 
             numero[0] == numero[2] && numero[2] == numero[3] ||
                numero[0] == numero[2] && numero[2] == numero[4] || 
                numero[0] == numero[3] && numero[3] == numero[4] ||
                numero[1] == numero[2] && numero[2] == numero[3] || 
                numero[1] == numero[2] && numero[2] == numero[4] ||
                numero[2] == numero[3] && numero[3] == numero[4] || 
                numero[1] == numero[3] && numero[3] == numero[4])
            {
                result = totalofdie(numero);
            }

            else
            result = 0;
            return result;
          } 
       }

     //only including one method to save on space.  The rest of the logic to find the special scores is     
     //relatively similar.
}
     // the facevalue is listed below
     public int faceval(int[] numero, int denom)
        {
            int fvcount = 0;
            int result = new int();
 
            if (numero[0] == denom) 
            {
                fvcount +=1;
            }
            if (numero[1] == denom)
            {
                fvcount += 1;
            }
            if (numero[2] == denom)
            {
                fvcount += 1;
            }
            if (numero[3] == denom)
            {
                fvcount += 1;
            }
            if (numero[4] == denom)
            {
                fvcount += 1;
            }

            result = denom * fvcount;
            return result;
        } 

After this, the game is reset by setting all int variables to their original values and using the rolls function to make the stack.

Points of Interest

I had made a deck of cards using the same Stack Class in VB, but I wanted to try and make a game of yahtzee on a form. Yahtzee I felt was easier than Black Jack to code, but the flow of control was larger with yahtzee with 13 separate events. On yahtzee and Black Jack, I learnt that by getting the program to press a button, do not have any code you need run placed after that event, as it can disrupt the whole flow of the program.

History

  • 11th June, 2015: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here