9 Replies - 5563 Views - Last Post: 06 November 2012 - 02:35 PM Rate Topic: -----

#1 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

c# random dice game

Posted 04 November 2012 - 01:46 PM

I'm trying to make a little dice game with 8 dices. The first time, a player needs to throw 8 dices and then he needs to choose which value he wants to take.

e.g Players throws: 1, 2, 4, 6, 5, 2, 3, 2 The player choose the value 2. The first time he threw 3 times 2 so the next time he only has 5 dices left. The result label shows: 6 (3 times 2)

The second time, the player throws 5 dices. e.g. 5, 1, 6, 2, 6 Because he allready picked value 2 this is not an option anymore. So this time he takes 6. 2 times 6 = 12. Result label 6 (3x2) + 12 (2x6) = 18. Now he has 3 dices left.

He keeps throwing untill he has no dices left or if the last time he threw he only has values left that allready had been taken.

e.g 3 dices left: 2, 2, 6. He allready picked these values so he's dead.

Is This A Good Question/Topic? 0
  • +

Replies To: c# random dice game

#2 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1012
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: c# random dice game

Posted 04 November 2012 - 01:48 PM

*
POPULAR

Cool, let us know how you are doing with it.
Was This Post Helpful? 5
  • +
  • -

#3 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5676
  • View blog
  • Posts: 12,194
  • Joined: 02-June 10

Re: c# random dice game

Posted 04 November 2012 - 02:12 PM

I agree with Momerath; its nice that you're telling us what you are up to. I'm not sure *why* you're announcing it to us. I mean you don't need to get our approval to take this on. But its always good to know others are sitting at their keyboards as well, I guess.
Was This Post Helpful? 0
  • +
  • -

#4 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: c# random dice game

Posted 05 November 2012 - 12:13 PM

<Button x:Name="btnThrowDice" Content="Throw Dices" HorizontalAlignment="Left" Margin="80,81,0,0" Grid.Row="2" VerticalAlignment="Top" Width="75" Click="Button_Click_1" Grid.Column="4"/>
            <Label Content="" Name="Dice1" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="0"/>
            <Label Content="" Name="Dice2" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="1"/>
            <Label Content="" Name="Dice3" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="2"/>
            <Label Content="" Name="Dice4" HorizontalAlignment="Left" Margin="19,11,0,0" VerticalAlignment="Top" Grid.Column="3"/>
            <Label Content="" Name="Dice5" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1"/>
            <Label Content="" Name="Dice6" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1"/>
            <Label Content="" Name="Dice7" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1" Grid.Column="2"/>
            <Label Content="" Name="Dice8" HorizontalAlignment="Left" Margin="19,10,0,0" VerticalAlignment="Top" Grid.Row="1" Grid.Column="3"/>
            <TextBox x:Name="DobbelWaarde" HorizontalAlignment="Left" Height="23" Margin="295,39,0,0" Grid.Row="2" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120" Grid.Column="4"/>
            <Button x:Name="btnCheck" Content="Check" HorizontalAlignment="Left" Margin="295,81,0,0" Grid.Row="2" VerticalAlignment="Top" Width="75" Click="btnCheck_Click" Grid.Column="4"/>
            <Label Content="0" Name="sumValues" HorizontalAlignment="Left" Margin="295,127,0,0" Grid.Row="2" VerticalAlignment="Top" Grid.Column="4"/>
            <Button Content="Pick a card" Grid.Column="4" HorizontalAlignment="Left" Margin="108,398,0,0" Grid.Row="2" VerticalAlignment="Top" Width="75" Click="Button_Click_2"/>
       


        private static readonly Random getrandom = new Random();
        List<int> list = new List<int>();
        bool throwSix = false;

        public MainWindow()
        {
            InitializeComponent();
        }

        public static int GetRandomNumber(int min, int max)
        {
                return getrandom.Next(min, max);       
        }
        
        //Button throw dices
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (Dice1.IsEnabled == true)
            {
                int a = GetRandomNumber(1, 7);
                Dice1.Content = a;
            }
            if (Dice2.IsEnabled == true)
            {
                int b = GetRandomNumber(1, 7);
                Dice2.Content = b;
            }
            if (Dice3.IsEnabled == true)
            {
                int c = GetRandomNumber(1, 7);
                Dice3.Content = c;
            }
            if (Dice4.IsEnabled == true)
            {
                int d = GetRandomNumber(1, 7);
                Dice4.Content = d;
            }
            if (Dice5.IsEnabled == true)
            {
                int ef = GetRandomNumber(1, 7);
                Dice5.Content = ef;
            }
            if (Dice6.IsEnabled == true)
            {
                int f = GetRandomNumber(1, 7);
                Dice6.Content = f;
            }
            if (Dice7.IsEnabled == true)
            {
                int g = GetRandomNumber(1, 7);
                Dice7.Content = g;
            }
            if (Dice8.IsEnabled == true)
            {
                int h = GetRandomNumber(1, 7);
                Dice8.Content = h;
            }
            btnThrowDice.IsEnabled = false;
        }

        private void btnCheck_Click(object sender, RoutedEventArgs e)
        {
            CheckIfAllreadyChoosen();
        }

        private void CheckValue()
        {
            int iValue = Convert.ToInt32(sumValues.Content);

            int iValue1 = Convert.ToInt32(Dice1.Content);
            int iValue2 = Convert.ToInt32(Dice2.Content);
            int iValue3 = Convert.ToInt32(Dice3.Content);
            int iValue4 = Convert.ToInt32(Dice4.Content);
            int iValue5 = Convert.ToInt32(Dice5.Content);
            int iValue6 = Convert.ToInt32(Dice6.Content);
            int iValue7 = Convert.ToInt32(Dice7.Content);
            int iValue8 = Convert.ToInt32(Dice8.Content);

            if (Dice1.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice1.IsEnabled = false;
                sumValues.Content = iValue1 + Convert.ToInt32(sumValues.Content);
            }
            if (Dice2.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice2.IsEnabled = false;
                sumValues.Content = iValue2 + Convert.ToInt32(sumValues.Content);
            }
            if (Dice3.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice3.IsEnabled = false;
                sumValues.Content = iValue3 + Convert.ToInt32(sumValues.Content);
            }
            if (Dice4.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice4.IsEnabled = false;
                sumValues.Content = iValue4 + Convert.ToInt32(sumValues.Content);
            }
            if (Dice5.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice5.IsEnabled = false;
                sumValues.Content = iValue5 + Convert.ToInt32(sumValues.Content);
            }
            if (Dice6.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice6.IsEnabled = false;
                sumValues.Content = iValue6 + Convert.ToInt32(sumValues.Content);
            }
            if (Dice7.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice7.IsEnabled = false;
                sumValues.Content = iValue7 + Convert.ToInt32(sumValues.Content);
            }
            if (Dice8.Content.ToString().Equals(DobbelWaarde.Text))
            {
                Dice8.IsEnabled = false;
                sumValues.Content = iValue8 + Convert.ToInt32(sumValues.Content);
            }
        }

        private void CheckIfAllreadyChoosen()
        {   
            if (Convert.ToInt32(DobbelWaarde.Text) == 1)
            {
                if (list.Contains(1))
                {
                    MessageBox.Show("1 is allready been chosen");
                }
                else
                {
                    list.Add(1);
                    CheckValue();
                    btnThrowDice.IsEnabled = true;
                }
            }

            if (Convert.ToInt32(DobbelWaarde.Text) == 2)
            {
                if (list.Contains(2))
                {
                    MessageBox.Show("2 is allready been chosen");
                }
                else
                {
                    list.Add(2);
                    CheckValue();
                    btnThrowDice.IsEnabled = true;
                }
            }

            if (Convert.ToInt32(DobbelWaarde.Text) == 3)
            {
                if (list.Contains(3))
                {
                    MessageBox.Show("3 is allready been chosen");
                }
                else
                {
                    list.Add(3);
                    CheckValue();
                    btnThrowDice.IsEnabled = true;
                }
            }

            if (Convert.ToInt32(DobbelWaarde.Text) == 4)
            {
                if (list.Contains(4))
                {
                    MessageBox.Show("4 is allready been chosen");
                }
                else
                {
                    list.Add(4);
                    CheckValue();
                    btnThrowDice.IsEnabled = true;
                }
            }

            if (Convert.ToInt32(DobbelWaarde.Text) == 5)
            {
                if (list.Contains(5))
                {
                    MessageBox.Show("5 is allready been chosen");
                }
                else
                {
                    list.Add(5);
                    CheckValue();
                    btnThrowDice.IsEnabled = true;
                }
            }

            if (Convert.ToInt32(DobbelWaarde.Text) == 6)
            {
                if (list.Contains(6))
                {
                    MessageBox.Show("6 is allready been chosen");
                }
                else
                {
                    list.Add(6);
                    throwSix = true;
                    CheckValue();
                    btnThrowDice.IsEnabled = true;
                }
            }
        }

        // Button pick a card
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (Convert.ToInt32(sumValues.Content) >= 21 && throwSix == true)
            {
                MessageBox.Show("Valid");
            }
            else
            {
                MessageBox.Show("You didn't threw a six or threw less than 21");
            }
        }
    }
}



This is the code I have so far. Anyone that can help me to make it shorter/better? :)
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5676
  • View blog
  • Posts: 12,194
  • Joined: 02-June 10

Re: c# random dice game

Posted 05 November 2012 - 02:01 PM

OMG! So many things, where to start?

Any time you have scores of identical variable like your iValue1-8... You can probably consider a List<int> or array[] or some other collection that you can iterate through using a loop.

That extends to all your buttons. If they were part of a collection/List<T> then you could loop through them instead of the massive change of if statements.

When then extends to all your logic... Massive amounts of code redundancy. Lines 123-205 should be about 8 lines of a loop. Same with 18-57.

Think 'scalability'. What if your boss said to you: "Its great. Now make it work for 50 dice." You'd crap yourself with how much brute force and duplication it would take.

"Button_Click_1"... Really? Use meaningful names for your controls. "btnSubmit" or "btnRollDice" for example

List<int> list = new List<int>();
Wow, a List named 'list'. That's not really helpful to anyone including yourself in 6 months. How about "UsedNumbers" or "EliminatedValues"?

Bind properties to your controls. You shouldn't have to set the values in a method like this:
048             if (Dice7.IsEnabled == true)  
049             {  
050                 int g = GetRandomNumber(1, 7);  
051                 Dice7.Content = g;  
052             } 

If the GUI control hand it's .Content bound to a property. That's the right WPF way to do such things.
Was This Post Helpful? 1
  • +
  • -

#6 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: c# random dice game

Posted 05 November 2012 - 02:39 PM

Thanks for your answer! As you can see I'm a starter.
I've changed the controls into meaningful names and shorten some code.

            if (Dice1.IsEnabled == true)
            {
                Dice1.Content = GetRandomNumber(1, 7);
            }
            if (Dice2.IsEnabled == true)
            {
                Dice2.Content = GetRandomNumber(1, 7);
            }


            int number = Convert.ToInt32(DobbelWaarde.Text);

            if (number == 1)
            {
                if (usedNumbers.Contains(1))
                {
                    MessageBox.Show("1 is allready been chosen");
                }
                else
                {
                    usedNumbers.Add(1);
                    CheckValue();
                    btnThrowDice.IsEnabled = true;
                }
            }


I'm not sure where to begin next. I've tried to put the redundant code in a for loop but still can't figure it out how to make it work. I realize that the code keeps coming back but I don't know how to use a for loop for the different values or to check if my list contains a specific value.
Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5676
  • View blog
  • Posts: 12,194
  • Joined: 02-June 10

Re: c# random dice game

Posted 05 November 2012 - 03:03 PM

FYI:
1 if (Dice1.IsEnabled == true)  
2 {  
3     Dice1.Content = GetRandomNumber(1, 7);  
4 }

can become
if (Dice1.IsEnabled) Dice1.Content = GetRandomNumber(1, 7);


Quote

I realize that the code keeps coming back but I don't know how to use a for loop for the different values or to check if my list contains a specific value.

As I said, you need to get away from the numerous values and put those things into collection types such as a List<T> or array[]. Then you can use a loop to iteration through them.

foreach (Dice die in DiceList)
{
   if (die.IsEnabled) die.Content = GetRandomNumber(1,7);
}


That loop would replace all the redundant code of your Button_Click_1 method (Lines 18-57) if your make a List<Dice> of your Dice objects.

MSDN Page for List<T>
http://msdn.microsof...y/6sh2ey19.aspx
Was This Post Helpful? 1
  • +
  • -

#8 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1012
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: c# random dice game

Posted 05 November 2012 - 03:47 PM

This
int number = Convert.ToInt32(DobbelWaarde.Text);

if (number == 1)
{
    if (usedNumbers.Contains(1))
    {
        MessageBox.Show("1 is allready been chosen");
    }
    else
    {
        usedNumbers.Add(1);
        CheckValue();
        btnThrowDice.IsEnabled = true;
    }
}
and all the blocks of code after it can be converted to
int number = Convert.ToInt32(DobbelWaarde.Text);
if (usedNumbers.Contains(number)) {
    MessageBox.Show(String.Format("{0} is allready been chosen", number));
} else {
    usedNumbers.Add(number);
    CheckValue();
    btnThrowDice.IsEnabled = true;
}


You should look for places where you do the same thing but with minor changes (usually hard coded values like your '1', '2', etc.) and see how you can replace them with one method that takes a variable.

This post has been edited by Momerath: 05 November 2012 - 03:50 PM

Was This Post Helpful? 1
  • +
  • -

#9 opticaltim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 19-December 11

Re: c# random dice game

Posted 06 November 2012 - 01:49 PM

Here is what I got at this moment. I made a new project (windows store application) and created an usercontrol for the die. I'm not longer showing the random dice values in a label but I'm working with different pictures now (1.png = throw 1). Instead of entering a value into a textbox, you now need to click on a dice to choose which value you want to choose and sum up. Any comments on the code?

Usercontrol code
        public Die()
        {
            this.InitializeComponent();
            image1.Source = new BitmapImage(new Uri("ms-appx:DiceFaces/" + 0 + ".png", UriKind.Absolute));        
        }

        public int MyValue
        {
            get { return (int)GetValue(MyValueProperty); }
            set { SetValue(MyValueProperty, value); }
        }

        public static readonly DependencyProperty MyValueProperty =
            DependencyProperty.Register("MyValue", typeof(int), typeof(Die), new PropertyMetadata(0, new PropertyChangedCallback(ChangeMyValue)));

        private static void ChangeMyValue(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
 	        (sender as Die).image1.Source = new BitmapImage(new Uri("ms-appx:DiceFaces/" + e.NewValue.ToString() + ".png", UriKind.Absolute));
        }



Mainpage code
List<int> usedNumbers = new List<int>();
        bool throwSix = false;

        public MainPage()
        {
            this.InitializeComponent();
            setDice();
        }

        private void setDice()
        {
            for (int i = 0; i < 4; i++)
            {
                Die die = new Die();
                die.PointerReleased += die_PointerReleased;
                die.SetValue(Grid.ColumnProperty, i);             
                gridDobbel.Children.Add(die);
            }

            for (int i = 0; i < 4; i++)
            {
                Die die = new Die();
                die.PointerReleased += die_PointerReleased;
                die.SetValue(Grid.RowProperty, 1);
                die.SetValue(Grid.ColumnProperty, i);
                gridDobbel.Children.Add(die);
            }
        }

        private async void showMessage(String message, String title)
        {
            MessageDialog msg = new MessageDialog(message, title);
            await msg.ShowAsync();
        }

        void die_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            int number = (sender as Die).MyValue;
            if (usedNumbers.Contains(number))
            {
                showMessage(number + " allready been chose", "");
                btnThrowDice.IsEnabled = true;
            }
            if (number == 6)
            {
                if (usedNumbers.Contains(6))
                {
                    //....
                }
                else{
                    usedNumbers.Add(6);
                    throwSix = true;
                    CheckValue(number);
                    btnThrowDice.IsEnabled = true;
                }
            }
            else
            {
                usedNumbers.Add(number);
                CheckValue(number);
                btnThrowDice.IsEnabled = true;
            }
        }

        private void CheckValue(int number)
        {
            foreach (Die die in gridDobbel.Children.OfType<Die>())
            {
                if (number == die.MyValue)
                {
                    sumThrowDice.Text =  (Convert.ToInt32(sumThrowDice.Text) + number).ToString();
                }               
            }   
        }
        

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnThrowDice_Click(object sender, RoutedEventArgs e)
        {
            Random num = new Random();

            foreach (Die die in gridDobbel.Children.OfType<Die>())
            {
                int Number = num.Next(1, 7);
                die.MyValue = Number;
            }    
        }




I have 1 problem left, when I was working with labels I disabled the dice when I choose value to sum.
Now that I'm working with images and loops I can't figure it out to do the same. Anyone?

Thanks! :)
Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5676
  • View blog
  • Posts: 12,194
  • Joined: 02-June 10

Re: c# random dice game

Posted 06 November 2012 - 02:35 PM

24 die.SetValue(Grid.RowProperty, 1);

This is C#, not VB6 or JAVA where you have get and set methods.
Just make a property following the models of .NET

When you use an IntegerUpDown for example you do this

myIntegerUpDown.Value = 47;

not

myIntegerUpDown.SetValue(47);

Not making your code follow well established standards like this just makes it confusing and something experienced coders won't want to work with: IE you will be shunned by other coders at work if your code is a pain in the ass to deal with.

07 public int MyValue

Not "MyValue".. Just "Value"... like any other numeric control... UpDowns, Sliders, ProgressBar and so on.

While we are on it.. If you have a public property of Value (or MyValue) then why did you also make a setter method?



12 for (int i = 0; i < 4; i++)
Why did you hard-code 4 throughout the program? What happens if you want an advanced mode of 8 die later? Use a variable to set the max then always refer to that in your methods. Make each method dynamic.

83 Random num = new Random();
Don't make a new Random each time the button is clicked. It reduces the actual randomness returned. Have one instance of the Random at class level, then get the .Next of it.

This post has been edited by tlhIn`toq: 06 November 2012 - 02:36 PM

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1