c# Math game win counter - c#

So I created a game where player one and player two can play a game where they answer math questions, basically they go one after another for 5 rounds, so if one player answers the question right first they "Win" and if they both answer it right it is a "tie". Kind of a weird way to explain a weird game, but that's not my issue. I already finished the game inside of a class and it is functional and fine, my problem is that I need the players to play 5 games, and for it to tell who won the game the most, ex: "Player 1( or player 2, or draw) has won {0} times!" I have tried a lot of different things, but its all not working. Here is my code:
static void Main(string[] args)
{
string ID = "";
bool gOver = false;
Console.WriteLine("ID 1 ");
ID = Console.ReadLine();
MathGame p1 = new MathGame(1, ID);
Console.WriteLine();
Console.WriteLine("ID 2");
ID = Console.ReadLine();
MathGame p2 = new MathGame(2, ID);
Console.WriteLine();
while (!gOver)
{
MathGame.prblm();
while (!p1.Game() && !p2.Game())
gOver = true;
}
}
To reiterate; I'd like to make the game loop 5 times and tell me who won the most. I feel like my mistake is simple, make its just where I'm tired. Thanks for any and all help, this website is very helpful.

You need to wrap your game in a for loop, not a while. Then when the while loop (of your game) ends you should check who won and tally it. After the for loop you should have counters to display then.
There are many ways to "tally" but the easiest would be to add a variable for each player and increment when they win.
const in GAME_COUNT_TO_PLAY = 5;
for(int i = 0; i < GAME_COUNT_TO_PLAY; i++)
{
MathGame.prblm();
while (!p1.Game() && !p2.Game())
{
//Keep track of score here, incriment some counter for winner
//e.g. if(p1.Win) p1Count++;
}
}
After the for loop you can check for who won.
if(p1Count > p2Count)
Display("Player 1 Wins!");
else if(p1Count < p2Count)
Display("Player 2 Wins!")
else
Display("Draw!");

Related

unity how to count turns to change players

I would like to make a bowling game in unity and I want to change the players after they threw the ball two times and the whole game to continue for 4 turns.
so I have two balls and each one has a script with a playerController that moves around the balls and after collision they respawn in the original position.
so for the turns I made a gameController that enables player1 (ball) input and disables player2 input then it enables player2 and disables player1.
How can I make player 1 to play twice and then change to player 2.
the script is:
public IEnumerator gamePlay()
{
if (pl1.hasPlay == false)
{
pl1.gameObject.SendMessage("Activate");
pl2.gameObject.SendMessage("Deactivate");
}
if (pl1.hasPlay == true)
{
pl2.gameObject.SendMessage("Activate");
pl1.gameObject.SendMessage("Deactivate");
}
yield return 0;
}
I'd recommend using two integers: one to store the number of plays and another to store the number of rounds.
It would look like this:
private int plays;
private int rounds;
private void Start()
{
plays = 0;
rounds = 0;
StartCoroutine(gamePlay());
}
public void NextBall()
{
plays++;
// Here you can change the logic behind the 2 balls
// (I remember it changes depending on whether you did a strike or not, if it's your last play or not, ...)
if (plays >= 2)
{
plays = 0;
rounds++;
StartCoroutine(gamePlay());
}
}
public IEnumerator gamePlay()
{
// This is based on player 1 being the first player
pl1.hasPlay = (rounds % 2 == 0);
pl2.hasPlay = !pl1.hasPlay;
pl1.gameObject.SendMessage(pl1.hasPlay ? "Activate" : "Deactivate");
pl2.gameObject.SendMessage(pl2.hasPlay ? "Activate" : "Deactivate");
yield return 0;
}
Also i'm not sure why you declared gamePlay() as an IEnumerator and not as a method but I guess you needed it this way :)
I changed the if/else condition by a ternary operator since the content on both part was similar, I find it easier to read like this.
Hope this helps,

Player-turn based Dice game (having trouble with loops)

Background; I'm trying to create a dice game for multi-players where you can choose how many players, sides on the die and dice's themselves you want in the game. And players each take a turn rolling n amount of dices and per each roll the score gets appended to the player classes playerScore property. Once a player reaches X amount of points, player is declared a winner.
Problem; The below code is part of the "Game" class. When I compile the code, the game does what I expect for the most part; it rolls 5 dices each turn per player and appends the points to said player, but once the player reaches 100 points, the player is declared a winner, but the die's are rolled again for another player, despite the fact that the while loop is invalidated. The way i see it, the problem is with the for loop, but I have no idea how to fix this, i tried "break" but it only breaks from the if statement.
My program has 3 classes; Die, Player, Game. If you need more information or screen shots. I can provide them.
P.S. If you think this code could be improved, please comment, I'd be glad to hear it out.
The if statements are messing with your flow. Why?
if (gameEnded || playerArray[i].PlayerScore >= maxPoints)
{
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
gameEnded = true;
break;
}
else if (!gameEnded )
{
playerArray[i].PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
}
Here, you're checking if the current player has reached the final score. If so, you break you for loop and set gameEnded = true, breaking the while loop as well. But this checks the score of the current player; it doesn't check if the current player has reached the score. This way, you will only discover if Player A won the game on the next round, not the current.
This way, as soon as a player reaches the score, the game ends:
public void StartGame(int maxPoints)
{
playerArray[0].PlayerTurn = true; // Not sure why you're doing this, so I'm gonna leave this here
Player winner = null;
while (!gameEnded)
{
for (int i = 0; i < playerArray.Length; i++)
{
Player currentPlayer = playerArray[i];
currentPlayer.PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);
if (currentPlayer.PlayerScore >= maxPoints)
{
winner = currentPlayer;
gameEnded = true;
break;
}
}
}
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", winner.PlayerName, winner.PlayerScore);
}
There is only one "problem" within this code: as soon as a player reaches the number of points, it ends the game. It doesn't wait for the round to end..
You could do like this:
public void StartGame(int maxPoints)
{
//playerArray[0].PlayerTurn = true; // Is it necessary?
while (true)
{
for (int i = 0; i < playerArray.Length; i++)
{
Player currentPlayer = playerArray[i];
currentPlayer.PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);
if (currentPlayer.PlayerScore >= maxPoints)
{
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", currentPlayer.PlayerName, currentPlayer.PlayerScore);
return;
}
}
}
}
I think your flow was just a little off, this may work better. To me the real issue was you should have rolled the dice first, then checked if it was a win. This would make your WHILE work properly.
public void StartGame(int maxPoints)
{
while (!gameEnded)
{
for (int i = 0; i < playerArray.Length; i++)
{
playerArray[i].PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
if(playerArray[i].PlayerScore >= maxPoints){
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
gameEnded = true;
break;
}
}
}
}

C# infinite spawning of platforms - will it create a lag?

Alright, Im working in Unity in C# and Ive created a few simple functions to spawn a series of platforms (game objects) indefinitely in accordance with the z position of the player. I delete the game objects once they are securely out of sight and called this update method every time player moves forward:
void spawnSectorGroup()
{
int i = numSectorsToSpawn; //get position of last sectors, when its exceeded by player then delete and spawn again
while (i >= 0) {
int j = Random.Range (0, sectors.Length);
spawnSector (gamePosition.position, sectors [j]);
i--;
}
}
void checkAndUpdateSectors()
{
//print ("Player pos"+playerPosition.position);
//print ("last sector"+gamePosition.position);
if (gamePosition.position.z - playerPosition.position.z <= 20) { //safe value ahead
print ("theyre almost there, spawn new group");
print (gamePosition.position.z - playerPosition.position.z);
spawnSectorGroup ();
}
//destroy past ones
GameObject[] objects = FindObjectsOfType(typeof(GameObject)) as GameObject[];
//GameObject[] objects = GameObject.FindGameObjectsWithTag("Block");
foreach (GameObject o in objects) {
if (o.gameObject.tag == "Block" || o.gameObject.tag == "Cage" || o.gameObject.tag == "Animal" || o.gameObject.tag == "Enemy") {
if (playerPosition.position.z - o.transform.position.z >= 100) { //safe aways back
print ("destroying past object");
print (o.transform.position);
Destroy (o.gameObject);
}
}
}
}
void spawnSector(Vector3 relativePosition,GameObject sector){
GameObject newSector = GameObject.Instantiate (sector, relativePosition, transform.rotation) as GameObject;
gamePosition.position += newSector.GetComponent<Sector> ().length;
}
This all works, however Im worried in the long run if this spawning of about 10 new "sectors" each time the player is within 20 or so units of the last spawned sector will build up and create a lag from the multitude of game objects.
Im not experienced with indefinite spawning - will this be a problem? Or is this good practice with indefinite spawning?
Creating and destroying objects is expensive and something you want to avoid doing in large amounts while your game is running.
Check out this Unity tutorial on Object Pooling. The basic idea is that instead of creating and destroying the objects, you take them from a pool of existing objects and return them when you are done so they can be reused.

Enemy AI in game is eating too much RAM

I need help. I'm currently trying to make a game and so far I'm doing okay. The only major problem I've encountered is adding enemy AI. Without the AI, my game only uses about 200-400mb of ram. When I made the AI, the game now eats upwards of 2GB of RAM. That's too much for a simple 2D Game. Here's a sample of the AI code(please assume that all necessary syntax is in my program. There are no errors since I can get it to run):
public void launch()
{
enemyGen.Tick += enemyGen_Tick;// in charge of generating enemies
enemyGen.Interval = 1000;
enemyGen.Start();
}
private void eneMove_Tick(object sender, EventArgs e)
{
for (int a = 0; a < 3; a++)
{
if (eneGen[a] == 1)//creates BLUE ENEMY
{
EnAIaY[a] += 2;
eneCount++;
if (a == 3)
{ a = 0; }
}
}
}
private void enemyGen_Tick(object sender, EventArgs e)
{
if (eneCount < 3)//creates an enemy if there are less than 3 enemies
{
for (int a = 0; a < 3; a++)
{
if (eneGen[a] != 1)
{
Random rnd = new Random();
eneGen[a] = rnd.Next(0, 5);//Generates a random number for enemy generation
if (a == 3)
{ a = 0; }
}
}
}
}
To explain the code I made, there is an array of 3 objects. In "enemygen_Tick", I had it generate a random number between 0 and 5 per array object. Every time the number generated was a 1, it would spawn an enemy.
I also added an if statement in the for loops so that every time the for loop would reach 3, the maximum number of objects, it would start generating random numbers again per object.
My question is how do I reduce RAM usage? When the program reaches the 2GB memory usage point, it starts lagging so bad.
There is a null reference exception after the first enemy despawns(gets eliminated), but that's a question for another time. I can't debug the game if a Powerpoint slide has a faster FPS than the game.

Changing GameState based on an if statement?

I'll get to the point. Having an issue with a beginner level game im coding at the moment. I have 2 lists to store "Objects" that are in the game. One is for "diamonds" pushable blocks that are to be moved onto the "Goals". Once all diamonds are on the goals, the level should change. I'm currently using "GameStates" to load each level. Here is the snippet of my code I'm having issues with. What happens currently is the game will allow me to push the "diamonds" onto the "goals", but the gamestate will not change once I do this. Not sure what I am missing - any help is appreciated. Thankyou for your time!
void Level1Update(KeyboardState cKB, KeyboardState oKB)
{
for (int i = 2; i < diamondlist.Count; i++)
{
if ((Goallist[i].Position == diamondlist[i].Position))
{
CurrentGameState = GameState.Level2;
}
}
}
If I understood correctly, you want to set current game state to the next level only if all the diamonds and goals are on the same tiles. The following code ensures that.
void Level1Update(KeyboardState cKB, KeyboardState oKB)
{
int i;
for (i = 0; i < diamondlist.Count; ++i)
{
if (Goallist[i].Position != diamondlist[i].Position)
break;
}
// When breaked off the loop, i is never equal to list count
if (i == diamondList.Count)
CurrentGameState = GameState.Level2;
}

Categories

Resources