Printing an array in a method, from a different class? - c#

I'm a fairly inexperienced programmer, and i'm currently working on a Console Application project. It's basically a little 'mathematics game'; the application generates two random numbers, that have either been added, subtracted, multiplied or divided against each other randomly. The answer is shown on screen and the user has to pick from the menu which is the right mathematical operator, once the correct answer is picked the application then displays on screen how long it took for the user in milliseconds to input the correct answer.
Now I want to save the times of the players in an array that can be called up later with all the scores. I need to include a method in this programme and I figured a method to save the times into an array would be suitable. I seem to have stumbled across a little problem though.
I'm not quite sure what's wrong:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mathgame
{
class Program
{
}
class arrayclass
{
public static void saveInArray(int duration)
{
int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};
if (duration < 1000)
{
duration = TopTenScores[000];
}
else if ((duration >= 1000) && (duration <= 1999))
{
duration = TopTenScores[1000];
}
else if ((duration >= 2000) && (duration <= 2999))
{
duration = TopTenScores[2000];
}
else if ((duration >= 3000) && (duration <= 3999))
{
duration = TopTenScores[3000];
}
else if ((duration >= 4000) && (duration <= 4999))
{
duration = TopTenScores[4000];
}
else if ((duration >= 5000) && (duration <= 5999))
{
duration = TopTenScores[5000];
}
else if ((duration >= 6000) && (duration <= 6999))
{
duration = TopTenScores[6000];
}
else if ((duration >= 7000) && (duration <= 7999))
{
duration = TopTenScores[7000];
}
else if ((duration >= 8000) && (duration <= 8999))
{
duration = TopTenScores[8000];
}
else if ((duration >= 9000) && (duration <= 9999))
{
duration = TopTenScores[9000];
}
Console.WriteLine(TopTenScores);
}
static void Main(string[] args)
{
int intInput, num1, num2, incorrect, array1;
float answer;
string input;
System.Random randNum = new System.Random();
Console.WriteLine("Welcome to the Maths game!");
Console.WriteLine("(Apologies for the glitchiness!)");
Console.WriteLine();
Console.WriteLine("Please choose from the following options:");
Console.WriteLine();
retry:
Console.WriteLine("1 - Test your Maths against the clock!");
Console.WriteLine("2 - Exit the application.");
Console.WriteLine("3 - Top scores");
Console.WriteLine();
input = Console.ReadLine();
intInput = int.Parse(input);
if (intInput == 1)
{
goto start;
}
else if (intInput == 2)
{
goto fin;
}
else if (intInput == 3)
{
array1 = array1.saveInArray;
goto retry;
}
Now, in the last 'else if' statement in the code, you can see my variable array1 trying to call the method, but no matter what I do I keep getting errors.
This is the only error I have at the moment, but I have a feeling soon as I resolve that error, another will come up. For now i'm just determined to get past this error:
'int' does not contain a definition for 'saveInArray' and no extension method 'saveInArray' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?).
Any help would be kindly appreciated, apologies in advanced for my ugly written code! And thank you to any help that I receive!
Regards,
Omar.

Okay,
There's quite a bit in this code that needs fixing TBH.
I'll start with your error first:
You are declaring the variable array1 as an integer. In C# integers are primitive types. This means that they have no methods and no class members. So, when you call array1.saveInArray the compiler is basically saying "the type integer doesn't have any methods... I can't find an appropriate method to match your call".
Instead of calling array1.saveInArray I think what you meant to call was arrayclass.saveInArray(x).
Notice the x in that call above. I'm passing a variable called x which is of type int into the function saveInArray().
This brings us to the second error. If saveInArray was a property, then you could just go arrayclass.saveInArray. However, it is a function which requires an argument... namely an integer.
When you call arrayclass.saveInArray(someInteger) you are passing someInteger as an argument into a method. The method is then free to use this argument to do its calculations.
That should fix your most basic errors and hopefully you can compile.
Moving on to some other errors that will cause you problems at runtime:
In the method saveInArray you are declaring an integer array called TopTenScores.
You are declaring this fine... however later on when you are indexing into TopTenScores, you are using an index that is way out of range of TopTenScores.
Here is your declaration of TopTenScores:
int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};
Notice that there are 10 numbers in this declaration. This means that the max index you can have is 9. Why? Because arrays start indexing at 0 in C#.
I think you might be thinking that this array is associative... however this is not the case. When you do TopTenScores[1000] you are saying "give me the value at index 1000". This value does not exists and you will get a runtime error.
Instead, you would want to call TopTenScores[1] if you wanted to access the value 1000.
Also, you are not overwriting the default value with the new top score, rather you are overwriting the new top score with the default value. I don't think this is intended. Instead, switch your calls from this: duration = TopTenScores[1000];
to this: TopTenScores[1] = duration;
Edit: Lastly, as the commenter pointed out, using goto is bad practice and greatly discouraged. You will understand why later on as you start to understand program flow and organization better. For now, it is best to try and avoid the habit of using goto. goto maps to a low level system construct, which we should avoid when using a higher level language like C#. Your code can get confusing and error prone quickly with using goto.
Anyways, feel free to ask more questions/comment etc if you have questions or you need to clarify something. Welcome to StackOverflow!

One of your problems is that you're missing the fundamental concept of what an array is. Think of an array as a row of numbered mailboxes. This line of code:
int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};
is creating an array of 10 integers that look something like this in memory:
Index Value
----- -----
0 0
1 1000
2 2000
3 3000
4 4000
5 5000
6 6000
7 7000
8 8000
9 9000
It is unclear how this is a useful structure to represent your top scores, and I'm not sure what your saveInArray method is trying to do. In that method, here's how one of your lines of code is interpreted:
duration = TopTenScores[1000];
What that means is "take what's at index 1000 of TopTenScores and store it in duration." As you can see from the table above, there is no index 1000, and besides, that code has nothing to do with saving a top score.
Another problem you're having is that you don't seem to have your algorithm in place for accomplishing the task. For the top ten functionality, try breaking down what needs to be done into instructions on how you would do it manually if you were a score keeper. It would be something like this:
I keep track of the top scores by stacking index cards with the scores on them in order of highest to lowest. At first, I have no index cards.
I can do two things: record scores and tell someone the top ten scores.
When someone asks me to record a score, I:
Write the score down on an index card
Look through the stack of previous scores in order until I find a score lower than this new score.
If I find a score that was lower than this new one, I place the card on top of the lower score.
Otherwise, if this score is the lowest one of the bunch, including if this is the first score recorded, I'll place the score at the bottom of the stack.
When someone asks me to tell them the top 10 scores, I:
Go through the first 10 cards or all the cards if I have less than 10.
For each of those scores, write them down in order.
Give the list of scores to the one requesting them.
It may seem silly to do this, but most programs are really only sequences of simple steps, and as a programmer, you need to be able to determine those steps before translating them into a language that the compiler can understand. Once you formulate the problem in simple terms, you can start translating it into code for example:
// You can think of a role a person would do for a manual process as a class
// in a program.
public class ScoreKeeper
{
// Our high score list (stack of cards) is empty to begin with. Unlike
// arrays, lists allow us insert items rather than placing them in
// numbered slots.
private List<int> _scores = new List<int>();
// This is the method for when someone asks us to record a score. The
// "score" parameter is the new score which you can think of as being
// written on a card.
public void RecordScore(int score)
{
// Go through each of the existing scores. "i" is the index in the
// list.
for (int i = 0; i < _scores.Count; i++)
{
// See if the new score is less than the score at index #i
if (_scores[i] < score)
{
// It is lower than this new score. Insert the new score
// above that score.
_scores.Insert(i, score);
// We're done. Stop looping and exit RecordScore.
return;
}
}
// If we get here, we found no scores lower than this new one. Add
// this score to the bottom of the stack.
_scores.Add(score);
}
// This is the method for when someone asks us for the top 10 scores.
// Notice that we return an array of integers, which will represent
// our piece of paper we hand back to the one requesting the scores.
public int[] GetTop10Scores()
{
// We start with a blank piece of paper.
int[] result = new int[10];
// Go through the scores. The first 10 are the top 10 because
// RecordScore puts them in order. We also need to make sure
// we don't try to get more scores than we've recorded.
for (int i = 0; i < 10 && i < _scores.Count; i++)
{
// Write down the score on the paper
result[i] = _scores[i];
}
// Send back the list of scores to the requester
return result;
}
}
Now, inside of your main program, you can create a ScoreKeeper and ask it to do its score keeping:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Maths game!");
Console.WriteLine("(Apologies for the glitchiness!)");
Console.WriteLine();
Console.WriteLine("Please choose from the following options:");
Console.WriteLine();
// This object keeps track of scores
ScoreKeeper scoreKeeper = new ScoreKeeper();
bool keepRunning = true;
while (keepRunning)
{
Console.WriteLine("1 - Test your Maths against the clock!");
Console.WriteLine("2 - Exit the application.");
Console.WriteLine("3 - Top scores");
Console.WriteLine();
string input = Console.ReadLine();
int intInput = int.Parse(input);
if (intInput == 1)
{
// You should avoid gotos. Try writing a method instead
// Play the game and get the player's score.
int newScore = PlayGame();
// Have the score keeper record the new score.
scoreKeeper.RecordScore(newScore);
}
else if (intInput == 2)
{
keepRunning = false;
}
else if (intInput == 3)
{
// Get the top scores from the score keeper
int[] topScores = scoreKeeper.GetTop10Scores();
// Print each score
for (int i = 0; i < topScores.Length; i++)
{
Console.WriteLine("{0}: {1}", i + 1, topScores[i]);
}
}
}
}
private static int PlayGame()
{
// Put your game logic in here. Return the score.
}
}
Once you become more familiar with the fundamentals of programming, you'll find there are existing classes you can reuse, like SortedList, that can already take care of common tasks like maintaining an ordered list.

Related

What is stopping this program from having an output

I made this code to brute force anagrams by printing all possible permutables of the characters in a string, however there is no output. I do not need simplifications as I am a student still learning the basics, I just need help getting it to work this way so I can better understand it.
using System;
using System.Collections.Generic;
namespace anagramSolver
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter anagram:");
string anagram = Console.ReadLine();
string temp = "";
List<string> storeStr = new List<string>(0);
List<int> storeInt = new List<int>(0);
//creates factorial number for anagram
int factorial = 1;
for (int i = anagram.Length; i > 0; i--)
{
factorial *= i;
}
while (storeStr.Count != factorial)
{
Random rnd = new Random();
while(temp.Length != anagram.Length)
{
int num = rnd.Next(anagram.Length - 1);
if (storeInt.Contains(num) == true)
{
}
else
{
storeInt.Add(num);
temp += anagram[num];
}
}
if (storeStr.Contains(temp) == true)
{
temp = "";
}
else
{
storeStr.Add(temp);
Console.WriteLine(temp, storeStr.Count);
temp = "";
}
}
}
}
}
edit: added temp reset after it is deemed contained by storeStr
Two main issues causing infinite loop:
1)
As per Random.Next documentation, the parameter is the "exclusive" upper bound. This means, if you want a random number between 0 and anagram.Length - 1 included, you should use rnd.Next(anagram.Length);.
With rnd.Next(anagram.Length - 1), you'll never hit anagram.Length - 1.
2)
Even if you solve 1, only the first main iteration goes well.
storeInt is never reset. Meaning, after the first main iteration, it will have already all the numbers in it.
So, during the second iteration, you will always hit the case if (storeInt.Contains(num) == true), which does nothing and the inner loop will go on forever.
Several issues here...
The expression rnd.Next(anagram.Length - 1) generates a value between 0 and anagram.Length - 2. For an input with two characters it will always return 0, so you'll never actually generate a full string. Remove the - 1 from it and you'll be fine.
Next, you're using a list to keep track of the character indices you've used already, but you never clear the list. You'll get one output (eventually, when the random number generator covers all the values) and then enter an infinite loop on the next generation pass. Clear storeInt after the generation loop to fix this.
While not a true infinite loop, creating a new instance of the random number generator each time will give you a lot of duplication. new Random() uses the current time as a seed value and you could potentially get through a ton of loops with each seed, generating exactly the same values until the time changes enough to change your random sequence. Create the random number generator once before you start your main loop.
And finally, your code doesn't handle repeated input letters. If the input is "aa" then there is only a single distinct output, but your code won't stop until it gets two. If the input was "aab" there are three distinct permutations ("aab", "aba", "baa") which is half of the expected results. You'll never reach your exit condition in this case. You could do it by keeping track of the indices you've used instead of the generated strings, it just makes it a bit more complex.
There are a few ways to generate permutations that are less error-prone. In general you should try to avoid "keep generating random garbage until I find the result I'm looking for" solutions. Think about how you personally would go about writing down the full list of permutations for 3, 4 or 5 inputs. What steps would you take? Think about how that would work in a computer program.
this loop
while(temp.Length != anagram.Length)
{
int num = rnd.Next(anagram.Length - 1);
if (storeInt.Contains(num) == true)
{
}
else
{
storeInt.Add(num);
temp += anagram[num];
}
}
gets stuck.
once the number is in storeInt you never change storeStr, yet thats what you are testing for loop exit

C# slotmachine supposed to keep one continuous score, somehow keeps multiple separate scores

I've been working on a slotmachine in C# for practise purposes, and the machine itself works as intentional. The points system, however, does not. The game starts at 100 points, and if, for example, the player lose three 5-point bets and wins 40 points on the fourth bet, the expected points would be 100-20+40=120 points. For some reason however, the code treats ALL the previous bets as being 40 point wins as well, bringing the total to 100-20+160=240 points. If the player then lose the fifth 5-point bet, the score jumps to 75.
I start by setting the 'points' value to 100, which should then update everytime the 'game()' function is called upon.
public static void Main()
{
int points = 100;
int num = 0;
Console.WriteLine("Welcome to 'Slotmachine'!\nThe aim of this game is to get a score of 1000 or higher.\nYou lose if you reach 0 or lower.\nPress enter to play");
Console.ReadLine();
Console.Clear();
points = points + game(100);
while(points<1000 && points>0)
{
num = num + 1;
Console.WriteLine("You've played for "+num+" number of round(s)");
points = points + game(points);
}
}
The 'game()' funtion returns the players winnings, which is used to update the 'points' value (Suspect nr 1?).
Inside the game function I have a 'usrbet' which takes an input from the user (1-10), which is then fed into the 'slots()' function to determine the winnings (the 'points' that are fed from 'Main()' are checked to see what the user can bet)
Console.WriteLine("Here are your current points: "+points+"\nHow much would you like to bet?\nmin bet: 1\nmax bet: 10");
try
{
usrbet = Convert.ToInt32(Console.ReadLine());
}
catch
{
usrbet = 1;
}
winnings = slots(usrbet);
int RetWin = winnings - usrbet;
return RetWin;
Here's what the 'slots()' function does, with some examples of the winnings calculations
public static int slots(int usrbet)
{
int Win;
int x;
int y;
int z;
Random slot = new Random();
x = slot.Next(2,10);
y = slot.Next(2,10);
z = slot.Next(2,10);
Console.WriteLine(x+""+y+""+z);
Example 1
if(x == y && y == z && x== 7)
{
Win = usrbet*250;
Console.WriteLine("WOW! That's incredible, you just won "+Win+"!");
}
Example 2
else if(x == z)
{
Win = usrbet*5;
Console.WriteLine("Congratulations, you win "+Win+".");
}
Example 3
else
{
Win = 0;
Console.WriteLine("Ah, bummer. You didn't win anything this time.");
}
After that, the 'Win' value is sent back to 'game()', updating 'winnings'.
I apologize for poor formatting of the question. I'll include a link to the code, in case my problem lies elsewhere in the code: https://dotnetfiddle.net/D5TwL0
I've tried making arrays of the 'bet' and 'usrbet' variables, in an attempt to have a "new" value to update the 'points' with at every run of 'game()', but that changed absolutely nothing other than limiting how many times 'game()' can run before getting an overflow error.
It turns out that the problem wasn't with the code, but with the compiler. Dotnetfiddle is where I made the code and had the issue, but trying it in another compiler, it managed to count just fine.

Kattis run time error solving Jumbo Javelin with C#

I am new to Kattis and trying solve the challenge Jumbo Javelin with C# but I get run time error even though I am exiting my program with 0.
Here is my code:
using System;
namespace JumboJavelin
{
class Program
{
static void Main(string[] args)
{
int l = int.Parse(Console.ReadLine());
int sum = 0;
int loss = 1;
for (int n = 0; n <= 100; n++)
{
sum += l;
if((n + 1) % 2 == 0 && !n.Equals(0))
{
sum -= ((n + 1) / 2)*loss;
}
try
{
l = int.Parse(Console.ReadLine());
}
catch (FormatException)
{
break;
}
}
Console.WriteLine(sum);
Environment.Exit(0);
}
}
}
Can someone please help me? I know my solution eventually outputs the wrong answer but right now I am trying to get rid of the run time error since it works perfectly fine on Visual Studio 2019.
All help is appreciated. Thanks
If you change the error your catch to Exception you will see that it is actually a wrong answer, so something goes wrong. You do exit your program with an exit code 0 at the bottom of your code, however, it throws an Exception somewhere else. Two things to consider:
First, the problem statement explains that as a first input, you get an integer N (this N indicates the amount of steel rods he has) and CAN BE between 1 and 100 (1 not inclusive hence, 1<N<=100). You now have a loop that always loops from 1 to 100. And the loop should loop from 1 up to and including whatever value N is. Try to see what you can do about that.
Second you read the input at the "tail" of the loop. This means that after the last cycle you do another read input. And that you do not read the first l. Try changing reading the input for l at the beginning of the loop. (and the first input you read in your Main, should not be for l (see point 1)).
See how far this gets you, is something is not clear please let me know.
As Kasper pointed out, n is dynamically provided on the first line; don't assume you have 100 lines to collect with for (int n = 0; n <= 100; n++).
There's no need to handle errors with the format; Kattis will always adhere to the format they specify. If something goes wrong parsing their input, there's no point trying to catch it; it's up to you to fix the misunderstanding. It's better to crash instead of catch so that you won't be fooled by Kattis telling you the failure was due to a wrong answer.
A simple approach is as follows:
Collect n from the first line of input; this is the preamble
Loop from 0 to n, collecting each line
Accumulate the values per line into a sum
Print sum - n + 1, the formula you can derive from their samples
using System;
class JumboJavelin
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += int.Parse(Console.ReadLine());
}
Console.WriteLine(sum - n + 1);
}
}
You can use this pattern on other problems. You won't always aggregate one result after n lines of input though; sometimes the input is a single line or you have to print something per test case. Some problems require you to split and parse each line on a delimiter.
Regardless of the case, focus on gathering input cleanly as a separate step from solving the problem; only combine the two if you're confident you can do it without confusion or if your solution is exceeding the time limit and you're sure it's correct otherwise.

Constructing a MasterMind game without using Arrays in c#?

I am trying to create a mastermind game without using arrays that generates 5 random numbers 1-9, and you have 15 tries to guess them.*=Correct -=WRONG +=incorrect positionbut the number is right.
I created the first part of it, and it works for trying to guess the first random digit of 1-9. I am unsure of how to goto the second number for the player to guess the second 1-9 digit, and how to make the code keep using the same int's/keep adding onto the guesses that I set up already. I tried everyway I knew how and I can't figure it out. If I could get some assistance of where I am going wrong, and how to set it up correctly it would be very much appreciated. Cheers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decisions
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess the 5 Digit code, Under 15 tries!");
Random myRandom = new Random();
Int32 one = myRandom.Next(1, 10);
Int32 two = myRandom.Next(1, 10);
Int32 three = myRandom.Next(1, 10);
Int32 four = myRandom.Next(1, 10);
Int32 five = myRandom.Next(1, 10);
int guesses = 0;
bool incorrect = true;
do
{
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
if (result == one.ToString())
incorrect = false;
else if (result == two.ToString())
Console.WriteLine("+");
else if (result == three.ToString())
Console.WriteLine("+");
else if (result == four.ToString())
Console.WriteLine("+");
else if (result == five.ToString())
Console.WriteLine("+");
else
Console.WriteLine("-");
} while (incorrect);
if (guesses < 15)
Console.WriteLine("*Correct! It took {0} guesses.", guesses);
if (guesses > 15)
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
}
}
I think what you're looking to use is a list. But first -
Keep in mind you want to be careful about how you order things in your program, especially when it comes to user experience. For instance:
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
So, when guesses is 14, it will show the text, have the user guess and increment "guesses" - however, when it iterates back to the beginning, your program will skip over the prompt: "Guess a number between 1 and 9" - but it will still wait for the users input. After they put in their input it will prompt that they went over the amount of tries, but it will still check if that number matched! How you order your program can be very important to a users experience.
Your program can look something like this:
const int iMaxGuesses = 15;
const int iListSize = 5;
static void Main(string[] args)
{
Random myRandom = new Random();
// Hold a list of integers
List<int> numbers = new List<int>();
int guesses = 0;
// Value where we will rebuild the code
string result = string.Empty;
// Placeholder for user's guess
string strGuess;
// Converted guess
int guess;
// Generate random list of numbers
for (int i = 0; i < iListSize; i++)
numbers.Add(myRandom.Next(1, 10));
// Prompt user
Console.WriteLine("Guess the {0} Digit code, Under {1} tries!", iListSize, iMaxGuesses);
// Open the game loop
do
{
// Check if we have exceeded the max amount of times we get to guess
if (guesses > iMaxGuesses)
Console.WriteLine("You went over 15 tries! Better luck next time");
else
{
// Prompt user
Console.WriteLine("Guess a number between 1 and 9");
// Get input
strGuess = Console.ReadLine();
// Check if input is in fact an integer, if so - put the value in our variable 'guess'
if (int.TryParse(strGuess, out guess))
{
// We have a proper guess, increment
guesses++;
// Checks if the number is the next in our list
if (numbers[0] == guess)
{
Console.WriteLine("Congratulations, {0} was a match!", guess);
// Remove that from the List
numbers.Remove(numbers[0]);
// Add it to our sequence (result)
result += guess;
}
else if(numbers.Contains(guess))
Console.WriteLine("Right number, wrong spot!");
else
Console.WriteLine("Incorrect, please try again!");
}
else // Inform user we will only accept numbered input
Console.WriteLine("That was not a number. Please try again!");
}
} while (guesses <= iMaxGuesses && numbers.Count > 0);
if (guesses < iMaxGuesses)
Console.WriteLine("Correct! It took {0} guesses to come up with the pattern {1}", guesses, result);
else
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
Couple things to note: We have class-level constants for the List Size (we'll get to that) and how many guesses, in case these need to be changed on the fly. You can ignore this.
The first thing you may notice is a List of integers List<int> numbers = new List<int>() Here is some Reading (what is difference between string array and list of string in c#) about the differences between Arrays and Lists (collections).
We initialize the list of Random numbers by creating a loop the max size of our list, and ADDING a random integer to that list.
On the Do/While loop, we are checking that we are still less than iMaxGuesses and we have objects left in our list. So we take the users input. First we use int.TryParseto determine if we do actually have a number. If we do have a number, we will check that against the first number that appears in the list, numbers[0], and if it does, we remove it from the list: numbers.Remove(numbers[0]); The cool part about lists, is that when you REMOVE an item, it resizes the list, unlike an array that has a fixed size. So if your list is 12345, and you remove the 1, the next time you check the value of numbers[0], it will be 2!
I'm pretty sure the rest should be self explanatory. Let me know if anything was missed or you need help understanding anything.

Call method when specific division of integer is reached

I am programming a video game, and in it, I would like to call a method that adds a player bonus life for every 2,000 points scored. I have no idea what operator(s) to use for such a thing.
If (score is divisible by 2000, each increment){
DoSomething();
}
I'm not even sure if I'm asking this question correctly. Basically when the player scores 2,000pts, 4,000pts, 6,000pts, etc, I want to give him/her a bonus life by calling a method. I already have the method created; I was just wondering how I can apply the conditions that call it.
I tried using this:
public int bonusTarget = 2000;
paddle = GameObject.Find("Paddle").GetComponent<Paddle>();
if(score >= bonusTarget){
paddle.Bonus();
bonusTarget += 2000;
}
but, it awarded more than one bonus life each increment. I need to award the bonus life only one time for each 2,000pts
"score is divisible by 2000"
if (score % 2000 == 0) DoSomething()
If You need to track score use property instead of varilable eg.:
private int _score;
public int Score
{
get
{
return _score;
}
set
{
var a = Math.Floor(_score / 2000)
var b = Math.Floor(value / 2000)
if (a < b) DoSomething();
_score = value;
}
}
Put the if(score is divisible by 2000) check inside the DoSomething() method.
There's no reason to keep this outside the method that increases the bonus lives, in the dozens of possible code paths that increase the score. You need ONE CENTRAL location that the score increases, and checks various conditions.
You need a centralized location to add to the score, like this:
public void AddToScore(int points)
{
score += points;
if (score >= bonusTarget)
{
bonusTarget += 2000;
paddle.Bonus();
}
}
I switched the two lines inside the conditional block in case paddle.Bonus() tries adding points itself, which could cause issues, possibly even infinite recursion.
If you make it so you always add to the score using this method, you can add any special handling you want. You might also want to write a ResetScore() and a GetScore() so you never access score directly elsewhere in your code.

Categories

Resources