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

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

Related

dice roll game stuck in a loop

I am trying to make a program for a game of pig where there user enters a point total to play for and then takes turns with a computer player until one player reaches the point total. For the human turn the player rolls and if they roll 2-6 then they can use r to roll again or h to hold. when hold is selected it adds up the total points and goes to the next turn. If 1 is rolled then they get 0 points for the round and it goes to the computers turn. For some reason when I select h to hold it just keeps going and when it does end the points don't get added up. Not sure how to fix this
any help would be appericated
static int pigRoll()
{
Random random = new Random();
int die1 = 0;
die1 = random.Next(1, 6);
Console.WriteLine($"You rolled {die1}");
return die1;
}
static double humanTurn()
{
double pointTotal = 0;
string gameSelect = null;
var pigDiceRoll = 0;
Console.WriteLine("It's your turn");
do
{
pigDiceRoll = pigRoll();
if (pigDiceRoll != 1)
{
Console.WriteLine("r to roll or h to hold (r/h)");
gameSelect = Console.ReadLine();
pointTotal = pointTotal + pigDiceRoll;
}
else if(pigDiceRoll ==1)
{
pointTotal = 0;
}
} while (gameSelect != "r" || pigDiceRoll != 1);
Console.WriteLine($"Your turn point total is {pointTotal}");
return pointTotal;
}
The while statement should read:
while (gameSelect == "r" && pigDiceRoll != 1)
This translates to keep looping while the user wants to roll again and they didn't roll a 1.
Alternatively you could use:
while (!(gameSelect != "r" || pigDiceRoll == 1))
Both are logically the same, but the first is probably easier to read.

Random class and if statements in dice roll simulator?

I am a beginner at C# and I have a homework assignment where I have to write a dice roll simulator.
The user can chose a maximum of 5 die and then as they roll each one the sum is added up with the one rolled previously. At the end the number of rolls and the the total sum is presented.
However, if the user rolls a 6 then this result is not added to the sum but the die is rolled twice more and then the sum is added.
I have a few points where I have gotten stuck and/or would like to know a better way of writing it. I have included a snippet below.
Below I have stated my Random class every time the dice rolls but is it possible for me to do this only once and then use throughout my code?
Is there a simple way to write the part with what happens if you roll a 6? I mean I guess I could write another if statement every time the die rolls but seems that this would very long?
if (intnumberofdie == 1)
{
Random rnd1 = new Random();
int dice1 = rnd1.Next(1, 7);
Console.WriteLine("You have rolled " + dice1);
else if (intnumberofdie == 2)
{
Random rnd1 = new Random();
int dice1 = rnd1.Next(1, 7);
Console.WriteLine("The first die rolled " + dice1);
Console.ReadKey();
Random rnd2 = new Random();
int dice2 = rnd2.Next(1, 7);
Console.WriteLine("The second die has rolled " + (dice2));
Console.ReadKey();
Console.WriteLine("The total sum so far is " + (dice1 + dice2));
}
Give this one a go:
var rnd1 = new Random();
var rollsRemaining = 6;
var sum = 0;
while (rollsRemaining > 0)
{
int dice1 = rnd1.Next(1, 7);
Console.WriteLine("You have rolled " + dice1);
if (dice1 == 6)
{
rollsRemaining += 2;
}
else
{
sum += dice1;
rollsRemaining -= 1;
}
}
Console.WriteLine("The sum is " + sum);
Since you are a beginner I'll try to explain a few things first.
If you have a number of times you have to do the same thing, you should never handle each case yourself. This means you shouldn't use the if else if else.. but instead use a loop like for or while.
I have written a short function which should do what you want.
private int GetNumber(int amountDie) {
if (amountDie <= 0 || amountDie > 5) return 0;
int total = 0;
for (int i = 0; i < amountDie; i++)
{
int roll = rnd.Next(1, 7);
if (roll == 6)
{
int specialRoll1 = rnd.Next(1, 7);
int specialRoll2 = rnd.Next(1, 7);
total += specialRoll1;
total += specialRoll2;
}
else {
total += roll;
}
}
return total;
}
Now some more explaining:
Since you said that you can't have more than 5 die, we will first check if the value given was valid, otherwise we'll just return 0 (there are better things to do in this case but for simplicity we'll just say they get back 0).
After that we declare a total to keep track of how many points we have to return.
Then we start the loop. For each dice, we roll once (first line in the for-construct).
Since we need to check if the user rolled a 6, we have this if there. Inside it we roll two die and add both results to the total. Note, that for these two rolls 6 is just like any other number and not handled differently (if you need that, it would be a bit more complicating).
If the user didn't roll a 6, we just add whatever they rolled to the total.
After we've done that for all die we simply return the total we got.
You'll see that if you just copy paste this code, it will not compile. The reason for that is that you are missing a Random-object. In your code you always created a new one everytime you rolled. This is a problem since the Random class isn't as random as you might think and you should always create just one for many random numbers.
Thats why I added this at the top of my class:
private static readonly Random rnd = new Random();
This random-object is only created once and then used for every die. This gives you a lot more randomness and prevents that every user always rolls the same value.
I hope this shows you how you can create a method like this. Of course you can add the console-output etc like you did in your code.

C# craps simulation

I have seen questions related to Craps, but they were related to python and Java. I hope someone familiar with C# can help me. The code below is meant to simulate the game of craps. The code mostly works, except for one issue.
I suppose I should briefly explain the game. Two 6 sided dice are rolled. If the result is a 7 or 11. The player or "shooter" wins automatically. If a 2, 3, or 12 is rolled, the shooter loses automatically. However, if another number is rolled, that number becomes the "point". The shooter rolls again until either they roll the point again or a 7. If the point is rerolled the shooter wins. If a 7 is rolled, this time it is a loss.
So, the problem is that this code still gives wins or losses automatically for 2, 3, 11, and 12 after the first roll. For example: The shooter rolls a 6. 6 becomes the point and the shooter rolls again. If the shooter rolls a 3 this code marks this result as a loss when it should just keep rolling until a 6 or 7 is rolled. This incorrect end happens whenever a 2, 3, 11, or 12 is rolled after the first roll. Any help on correcting the logic of this code would be greatly appreciated. Thanks Also, I hope this question is formatted correctly. Please let me know if it is not.
class Craps
{
const int dieSides = 6;
int roll;
//const int repeatGame = 1000;
Random random = new Random();
public void RollDice()
{
int die1 = 0;
int die2 = 0;
die1 = random.Next(1, 7);
die2 = random.Next(1, 7);
roll = die1 + die2;
//Console.WriteLine("The shooter roled: {0}", roll);
}
public void PlayCraps()
{
RollDice();
Console.WriteLine("The shooter roled: {0}", roll);
int gameStatus = 0;
int point = roll;
int numRolls = 1;
if (roll != 7 || roll != 11 || roll != 2 || roll != 3 || roll != 12)
{
Console.WriteLine("The point is: {0}", point);
}
while (gameStatus < 1)
{
if (roll == 7 || roll == 11)
{
Console.WriteLine("You won!");
gameStatus++;
break;
}
else if (roll == 2 || roll == 3 || roll == 12)
{
Console.WriteLine("You lost.");
gameStatus++;
break;
}
else
{
while (point != roll || roll != 7)
{
RollDice();
if (roll == point)
{
Console.WriteLine("The shooter roled: {0}", roll);
Console.WriteLine("You won!");
numRolls++;
gameStatus++;
break;
}
if (roll == 7)
{
Console.WriteLine("The shooter roled: {0}", roll);
Console.WriteLine("You lost");
numRolls++;
gameStatus++;
break;
}
else
{
numRolls++;
Console.WriteLine("The shooter roled: {0}", roll);
break;
}
}
}
}
Console.WriteLine("This game was {0} roll(s)", numRolls);
}
static void Main(string[] args)
{
Craps NewGame = new Craps();
NewGame.PlayCraps();
Console.ReadLine();
}
}
User pm100 commented saying that the final break returned the code back to the outer loop and that this was causing the error. Removing this fixed the issue described in my question. There may be other errors or ways to improve this code, but that comment solved the particular focus of this question.

make simple program using 'while' and 'do' [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 4 years ago.
Improve this question
I'm trying to print
*
**
***
****
*****
and
*****
****
***
**
*
using 'While' and 'do - while'.
But I have no idea how to approach this problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 0;
while (a <= 0)
{
while (b <= a)
{
Console.Write("*");
b++;
}
a++;
Console.WriteLine();
}
Console.ReadLine();
}
}
}
I've kept trying to approach like above, but I think It never works ever!
P.S How would I improve my logic about programming? I feel like I'm lack of thinking logically.
I figure this is a homework problem and I usually don't answer them, but I think this may help you understand how to program better, so let me try explain...
Think through what you're trying to do - You want to print 1 star first and then stop at 5 stars and then print the reverse.
So, firstly, name your variables to make sense:
int numStars = 1;
int maxNumStars = 5;
Next, you can loop something along the lines of:
while( numStars <= maxNumStars) { ... }
Firstly, it lets you understand your problem better, secondly, it becomes readable and debug-able.
Your final procedure can look something as follows:
static void Main(string[] args)
{
int numStars = 1;
int maxNumStars = 5;
// Print the ascending number of stars
while(numStars <= maxNumStars)
{
// Write numStars number of stars to the console using the string constructor:
Console.WriteLine(new string('*', numStars));
numStars++;
}
// Print the descending number of stars
while (numStars >= 1)
{
// Write numStars number of stars to the console using the string constructor:
Console.WriteLine(new string('*', numStars));
numStars--;
}
}
Again, not a fan of doing work for a person, but I hope it makes enough sense to actually help you figure out similar problems like this in the future.
Edit:
For completeness sake, to use loops everywhere, your code / loop could look something like this:
// Declare a variable for writing the stars to the console:
int numWritten;
// Print the ascending number of stars
while(numStars <= maxNumStars)
{
// Reset the number of stars written:
numWritten = 0;
// Write the stars with a loop:
while (++numWritten <= numStars)
Console.Write("*");
// End the line and increment the numStars variable:
Console.WriteLine();
numStars++;
}
This is one of many ways to do it:
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 0;
int c = 4;
while (a <= c)
{
b = 0;
while (b <= a)
{
Console.Write("*");
b++;
}
a++;
Console.WriteLine();
}
Console.WriteLine();
if (a > c)
{
a--;
while (a >= 0)
{
b = a;
while (b >= 0)
{
Console.Write("*");
b--;
}
a--;
Console.WriteLine();
}
}
Console.ReadLine();
}
}
}
Probably work in this direction:
int a = 0;
int b = 0;
string s = string.Empty;
while (a < 5)
{
while (b <= a)
{
s += "*";
b++;
}
Console.Write(s);
s = string.Empty;
a++;
b = 0;
}
Hope it gives you some idea...
using while loops can be confusing so I came up with this recursive solution (for science)
public static void Main()
{
test();
}
public static void test(string lastOutPut = "",int maxBound = 5,bool goingup = true,int cursor = 0,int maxOutputs = 10){
if(cursor>maxOutputs)return;
Console.Write("\n");
if(goingup){
Console.Write(lastOutPut+="*");
cursor++;
test(lastOutPut,maxBound,lastOutPut.Length <= maxBound,cursor,maxOutputs);
}else{
lastOutPut=lastOutPut.Substring(0,lastOutPut.Length-1);
Console.Write(lastOutPut);
cursor++;
test(lastOutPut,maxBound,lastOutPut.Length <= 0,cursor,maxOutputs);
}
}

Dice Program C#. net using arrays [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 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 }
}

Categories

Resources