Dice Program C#. net using arrays [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need some help with my program I built the simple dice program to show frequencies of the sum of two dice for 100 rolls. The program will read the file.
Now what i need is to declare an array that represents the possible results of throws of two dice,For each entry in the file, increment the element of the array corresponding to that result.Last, display the frequency count for that simulation. I do not know how to use an array in my program and need help trying to implement it into my program.
namespace Dice_Program
{
public partial class RollDice : Form
{
private int Dice1;
private int Dice2;
private int SUM;
const int Roll_MAX = 100;
private void btn_roll_Click(object sender, EventArgs e)
{
Random rand = new Random();
for (int lineNum = 1; lineNum <= Roll_MAX; lineNum++)
{
Dice1 = rand.Next(6) + 1;
Dice2 = rand.Next(6) + 1;
SUM = Dice1 + Dice2;
lstboxtotal.Items.Add(" On roll. " + lineNum + " You rolled a, " + Dice1 + " and a " + Dice2 + " for a sum of " + SUM);
}
}
private void btnwrite_Click(object sender, EventArgs e)
{ // Create a StreamWriter object
StreamWriter rollLog;
rollLog = File.CreateText ("Roll Results.txt"); // Creating the file
for (int count = 0; count <lstboxtotal.Items.Count; count++)
{
rollLog.WriteLine(Convert.ToString(lstboxtotal.Items[count]));
}
rollLog.Close(); // close file after creation
MessageBox.Show ("Your results have been successfully Saved to file.");
} // only first line is written 100 times
private void btnread_Click(object sender, EventArgs e)
{
using (StreamReader rollLog = new StreamReader("Roll Results.txt"))
{
while (rollLog.Peek() >= 0)
{
lstboxtotal.Items.Add(rollLog.ReadLine());
}
}
}
}
}

I'm having slight trouble understanding your english. But i think you want somthing like this.
(*Note this is kinda psudo code, and wont compile straight away, butim not going todo your homework)
int[] Rolls = { 0, 0, 0, 0, 0, 0 }; // 1 dice = 6 possible rolls 1- 6
void RollDice() {
int randomRoll = GetRandomDiceRoll(); //assume this returns 1-6 for the roll
//We use randomRoll-1 becuase the array is zero-indexed E.g. 0-5
Rolls[randomRoll-1]++;
//This increments the value and if the roll was 3 for instance your array will look like
// { 0, 0, 1, 0, 0, 0 }
}

Related

How to make a Hp value in a console game? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
ok so im pretty new to programming and am trying to make a game where i roll random ints for the dice inside of a loop and i want to be able to subtract the results of the dice roll from a value for the enemy's Hp and have that value carry over throughout the loop until the hp value equals zero then break the loop and end the game. I have tried declaring an int for the value, but i cant figure out how to save the damage dealt from the previous dice roll loop. Can anyone point me in the right direction to do this?
Edit:
forgot to add the code whoops.
This is my crappy code
class Program
{
static void Main(string[] args)
{
Program.hit();
}
static void hit()
{
bool enemyAlive = true;
while (enemyAlive)
{
Random rnd = new Random();
int roll20 = rnd.Next(1, 21);
int roll6 = rnd.Next(1, 7);
int rollCrt = rnd.Next(1, 7);
int critDmg = roll6 + rollCrt + 4;
if (roll20 == 20)
{
WriteLine($"\nyou rolled. { roll20} CRIT!!");
WriteLine($"you deal. {roll6} + {rollCrt} + 4 = {critDmg} damage.");
//currentEhp = enemyHp - critDmg;
// WriteLine(currentEhp);
}
else if (roll20 <= 14)
{
WriteLine($"\nyou rolled. {roll20} you miss");
}
else if (roll20 >= 15)
{
WriteLine($"\nyou rolled. {roll20} you hit");
WriteLine($"you deal. {roll6} damage");
//currentEhp = enemyHp - roll6;
// WriteLine(currentEhp);
}
ReadLine();
}
}
}
Declare the int variable outside of the loop and subtract from within the loop.
For example:
int hp = 100;
// I'm guessing this is the dice roll loop
for (int i = 0; i < NumOfTimes; i++)
{
if (hp <= 0)
break;
DiceRoll();
hp -= ValueOfDiceRoll;
}

Efficiently generate all combinations (at all depths) whose sum is within a specified range [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a set of 80 numbers and I would like to find the list of combinations which totals up to a given number. The below code works fine but its takes too long could someone please help me with an enhanced version which would process it faster ?
public void sum_up(List<int> numbers, int target)
{
sum_up_recursive(numbers, target, new List<int>());
}
public void sum_up_recursive(List<int> numbers, int target, List<int> partial)
{
int s = 0;
foreach (int x in partial) s += x;
if (s == target)
val +=" sum(" + string.Join(",", partial.ToArray()) + ")=" + target + Environment.NewLine;
if (s == target && string.Join(",", partial.ToArray()).Contains("130") &&
string.Join(",", partial.ToArray()).Contains("104"))
{
string gg = " sum(" + string.Join(",", partial.ToArray()) + ")=" + target;
val += " || || sum(" + string.Join(",", partial.ToArray()) + ")=" + target + Environment.NewLine;
}
if (s >= target)
return;
for (int i = 0; i < numbers.Count; i++)
{
List<int> remaining = new List<int>();
int n = numbers[i];
for (int j = i + 1; j < numbers.Count; j++) remaining.Add(numbers[j]);
List<int> partial_rec = new List<int>(partial);
partial_rec.Add(n);
sum_up_recursive(remaining, target, partial_rec);
}
lblResult.Text = val;
}
private void btnCheck_Click(object sender, EventArgs e)
{
string[] vendorVal = txtvendor.Text.Split(',');
int[] myInts = Array.ConvertAll(vendorVal, s => int.Parse(s));
List<int> numbers = myInts.ToList();
int target = Convert.ToInt32(txtDifference.Text);
sum_up(numbers, target);
}
Any help is appreciated...
You recalculate the same partial sums again and again - this process takes a lot of time. If targer sum value is reasonable and you have enough memory - use dynamic programming approach.
Create array A of length (TargetSum + 1) containing lists possible variants for intermediate sums.
For every item value V make loop from sum S=TargetSum downto V (reverse traversal helps to avoid repeated using of the same item). If entry A[S - V] is not empty - add all variants from A[S - V] with addition of V into A[V]. Finally A[TargerSum] will contain all possible combinations.
Also consider memoization technique - it might be constructed from your recursive function - just remember sum variants in dictionary and reuse stored variants.

What should I do in order to display how many loops it takes to get a favourable number?

Im new to programming and Im currently attempting to make a dice program, where the user can input how many throws they would like to do and then a list will display how many throws it took to get a specific number, in this case that number is 6 (later on I'd like to make it for all numbers 1-6) How should I go about doing this?
Im currently trying to use an if-statement to recognize when a specific number is rolled, currently I want the program to recognize the number 6, but im a bit unsure how to display the amount of rolls it took to get that number, in a list, and also keeping the loop going until all rolls have been executed.
private void Btnkast_Click(object sender, EventArgs e)
{
bool throws;
int numberofthrows = 0;
int dice;
Random dicethrow = new Random();
throws = int.TryParse(rtbantal.Text, out numberofthrows);
int[] list = new int[numberofthrows];
for (int i = 0; i <= numberofthrows; i++)
{
dice = dicethrow.Next(1, 7);
if (dice == 6)
{...}
}
}
Also, the only reason I use tryparse is to prevent crashes when having to handle with string-values.
I have written this for you using a C# Console Application, but I'm sure you will be able to edit it to fit your requirements for Windows Forms.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Random rnd = new Random(); // create Random object
Console.WriteLine("Enter a number between 1 and 6: "); // prompt user to enter a number between 1 and 6
int chosenNumberInt;
var chosenNumber = int.TryParse(Console.ReadLine(), out chosenNumberInt); // check to see if user actually entered a number. If so, put that number into the chosenNumberInt variable
Console.WriteLine("How many rolls would you like?"); // prompt user to enter how many rolls they would like to have
int chosenRollsInt;
var chosenRolls = int.TryParse(Console.ReadLine(), out chosenRollsInt);
Console.WriteLine(); // to create space
Console.WriteLine(); // to create space
Console.WriteLine("Chosen Number = " + chosenNumberInt + " --- Chosen Rolls = " + chosenRollsInt); // show user what they entered
Console.WriteLine("------------");
int count = 0;
int numberRolled = 0;
var lstRolls = new List<int>(); // create list object
for(int i = 1; i <= chosenRollsInt; i++)
{
count++;
int dice = rnd.Next(1, 7);
numberRolled = dice;
lstRolls.Add(numberRolled); // add each roll to the list
Console.WriteLine("Roll " + i + " = " + numberRolled); // show each roll
}
var attempts = lstRolls.Count; // how many rolls did you do
var firstIndexOfChosenNumber = lstRolls.FindIndex(x => x == chosenNumberInt) + 1; // have to add 1 because finding the index is 0-based
Console.WriteLine("-------------");
if(firstIndexOfChosenNumber == 0)
Console.WriteLine("The chosen number was " + chosenNumberInt + " and that number was NEVER rolled with " + chosenRollsInt + " rolls.");
else
Console.WriteLine("The chosen number was " + chosenNumberInt + " and the number of rolls it took to hit that number was " + firstIndexOfChosenNumber);
}
}
Something that I didn't add would be the validation to ensure that the user does indeed enter a number between 1 and 6, but you can do that I'm sure.
I have created a DotNetFiddle that proves this code does work and even shows you each roll.
Let me know if this helps or if you need any more assistance.
UPDATE
Based on your comment on my original post, I have edited my code to allow the user to enter the number they want, along with how many rolls. Then, once all of the rolls have been completed, I find the index of the first occurrence of the number they selected in the beginning.
Let me know if this is what you want.
Read the comments I added in the code
private void Btnkast_Click(object sender, EventArgs e)
{
bool throws;
int numberofthrows = 0;
int dice;
Random dicethrow = new Random();
throws = int.TryParse(rtbantal.Text, out numberofthrows);
List<int> list = new List<int>(); //I changed this to a list
for (int i = 0; i < numberofthrows; i++)
{
dice = dicethrow.Next(1, 7);
list.Add(dice); //add every roll to the array to check later the values if you want
if (dice == 6)
{
//Print that you found 6 at the roll number list.Count
Console.WriteLine("Found 6 at roll number: " + list.Count);
break; //probably break the loop so you won't continue doing useless computation
}
}
}

Generate Random number in C# [duplicate]

This question already has answers here:
How do I generate a random integer in C#?
(31 answers)
Closed 6 years ago.
I am wanting to generate a random number between 1 and 10. Yet I am getting a couple of errors.
public Form1()
{
InitializeComponent();
}
int randomNumber = (0, 11);
int attempts = 0;
public int RandomNumber
{
get
{
return randomNumber;
}
set
{
randomNumber = value;
}
}
it is all on the 0, 11 under the comma is says --> struct System.Int32 represents a 32-bit signed integer <--. Under the 11 it says --> Identifier expected Syntax error, ',' expected <--. Now if I just have like int randomNumber = 0; then it will work fine, still have multiple guesses and the guess count adds up like it should, and have the too high too low labels. just the number will always be 0.
Also how can I make it to where I don't have to click the guess button, I can just hit enter on the keyboard?
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (int.Parse(textBox1.Text) > RandomNumber) label1.Text = "Too high.";
else if (int.Parse(textBox1.Text) < RandomNumber) label1.Text = "Too low.";
else
{
label1.Text = "You won.";
textBox1.Enabled = false;
label2.Text = "Attempts: 0";
textBox1.Text = String.Empty;
MessageBox.Show("You won in " + attempts + " attempts, press generate to play again.", "Winner!");
attempts = 0;
label2.Text = "Attempts: " + attempts.ToString();
return;
}
attempts++;
label2.Text = "Attempts: " + attempts.ToString();
}
catch { MessageBox.Show("Please enter a number."); }
}
To generate a Random number you have to usw the System.Random class. Your syntax can look something like this :
System.Random rng = new System.Random(<insert seed if you want>);
int randomNumber = rng.Next(1,11);
You have to do rng.Next(1,11) since the lower bound is include (1 is a possible result) and the upper bound is exclude (11 isnt getting added into the pool oft possible results).
To do implement your Enter shortcut you have to add a method to your Forms KeyPress event in which you call the button1_clicked method.
button1_Clicked_1(this, System.EventArgs.Empty);
At last you have to set your forms "KeyPreview" property to true.
You can use something like the below code to generate random number between 1 to 10
Random randomNumberGenrator = new Random();
int num = randomNumberGenrator.Next(10) + 1;
Take a look at this.
Use the Random class in order to generate a random number.
private Random _rnd = new Random();
private int RandomNumber
{
get
{
return _rnd.Next(0,11);
}
set
{
this = value;
}
}

calculating Fibonacci in C#

I am trying to calculate the Fibonacci sequence in C# in a very simple way, however when it comes to the higher numbers it bugs out and stops working by giving out wrong answers.
ulong num = 1;
ulong lnum = 0;
uint x = 1;
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("(0) " + 1);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (x <= 1000)
{
ulong newnum = lnum + num;
listBox1.Items.Add("(" + x + ") " + newnum);
listBox1.SetSelected((int)x, true);
lnum = num;
num = newnum;
x++;
}
}
I am making it in a way that I can watch it add up the numbers by adding them to a listbox 1 at a time.
ulong is too small for fibonacchi. You need to use something bigger. .NET 4 added BigInteger, that should allow for arbitrary number size.
For lower .NET versions, you need to find similliar 3rd party implementation

Categories

Resources