The code below is a simple turn-based combat simulator in the console. I am having the issue stated in the title.
#include <iostream>
#include <ctime>
#include <random>
#include <Windows.h>
#include <string>
using namespace std;
int main(){
//Variables required to run the program
string orcNames[3] = { "Orc #1", "Orc #2", "Orc #3" };
string dwarfNames[6] = { "Dwarf #1" , "Dwarf #2", "Dwarf #3" , "Dwarf #4" , "Dwarf #5", "Dwarf #6" };
int currentOrc = 0;
int currentDwarf = 0;
int numberOfOrcs = 3;
int numberOfDwarves = 6;
int orcHealth = 100;
int currentOrcHealth = orcHealth;
int dwarfHealth = 50;
int currentDwarfHealth = dwarfHealth;
default_random_engine damageGenerator(time(NULL));
uniform_int_distribution<int> damage(5, 10);
char turn = 'D';
while (numberOfDwarves != 0 && numberOfOrcs != 0){
if (turn == 'D'){
//Calculates random damage
currentOrcHealth -= damage(damageGenerator);;
Sleep(50);
cout << dwarfNames[currentDwarf] << " attacks!" << endl;
Sleep(50);
cout << orcNames[currentOrc] << " has now " << currentOrcHealth << " HP\n\n";
if (currentOrcHealth <= 0){
//Runs if an orc has died
Sleep(100);
cout << "\n\n\t\t\t\t" << orcNames[currentOrc] << " has died.\n\n\n";
Sleep(100);
numberOfOrcs--;
currentOrc++;
currentOrcHealth = orcHealth;
}
turn = 'O';
}
if (turn == 'O'){
//Calculates random damage
currentDwarfHealth -= damage(damageGenerator);
Sleep(50);
cout << orcNames[currentOrc] << " attacks!" << endl;
Sleep(50);
cout << dwarfNames[currentDwarf] << " has now " << currentDwarfHealth << " HP\n\n";
if (currentDwarfHealth <= 0){
//Runs if a dwarf has died
Sleep(100);
cout << "\n\n\t\t\t\t" << dwarfNames[currentDwarf] << " has died.\n\n\n";
Sleep(100);
numberOfDwarves--;
currentDwarf++;
currentDwarfHealth = dwarfHealth;
}
turn = 'D';
}
}
system("PAUSE");
return 0;
}
So, I've been trying to find what is causing this for a while now, but when the combat ends in the three orcs dying, the error message in the title appears. This does not happen when the six dwarves die, as in that case the program is able to finish running. I have checked both if statements for the orcs and the dwarves, and they seem similar, except of course in the variable names.
The error message also displays "Access violation reading location 0xE81123C2."
I apologize if what is causing this is a simple mistake, since I'm no expert in C++.
Aucun commentaire:
Enregistrer un commentaire