给我写一个宝可梦游戏的c++代码
时间: 2023-08-20 22:13:46 浏览: 318
以下是一个简单的宝可梦游戏的C++代码示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
using namespace std;
class Pokemon {
private:
string name;
int hp;
int attack;
int defense;
public:
Pokemon(string n, int h, int a, int d) {
name = n;
hp = h;
attack = a;
defense = d;
}
void attackPokemon(Pokemon& other) {
int damage = (int)(((2.0 * this->attack / other.defense) + 2) * (rand() % 16) + 1);
other.hp -= damage;
cout << this->name << " attacked " << other.name << " and dealt " << damage << " damage!" << endl;
}
bool isAlive() {
return hp > 0;
}
friend ostream& operator<<(ostream& os, const Pokemon& p) {
os << p.name << " [HP: " << p.hp << ", Attack: " << p.attack << ", Defense: " << p.defense << "]";
return os;
}
};
int main() {
srand(time(nullptr));
vector<Pokemon> pokemonList;
pokemonList.push_back(Pokemon("Pikachu", 35, 55, 40));
pokemonList.push_back(Pokemon("Charmander", 39, 52, 43));
pokemonList.push_back(Pokemon("Squirtle", 44, 48, 65));
pokemonList.push_back(Pokemon("Bulbasaur", 45, 49, 49));
cout << "Welcome to the Pokemon game!" << endl;
cout << "Choose your Pokemon: " << endl;
for (int i = 0; i < pokemonList.size(); i++) {
cout << i + 1 << ". " << pokemonList[i] << endl;
}
int playerChoice;
cin >> playerChoice;
Pokemon playerPokemon = pokemonList[playerChoice - 1];
cout << "You have chosen " << playerPokemon << endl;
Pokemon opponentPokemon = pokemonList[rand() % pokemonList.size()];
cout << "The opponent has chosen " << opponentPokemon << endl;
while (playerPokemon.isAlive() && opponentPokemon.isAlive()) {
playerPokemon.attackPokemon(opponentPokemon);
if (opponentPokemon.isAlive()) {
opponentPokemon.attackPokemon(playerPokemon);
}
}
if (playerPokemon.isAlive()) {
cout << "Congratulations, you won!" << endl;
} else {
cout << "Sorry, you lost!" << endl;
}
return 0;
}
```
这个代码实现了一个简单的宝可梦对战游戏。玩家可以从四个可选的宝可梦中选择一个,然后与随机选择的对手宝可梦进行战斗。每个宝可梦有自己的属性,包括名称、生命值、攻击力和防御力。在每个回合中,玩家和对手都可以攻击对方,造成伤害。当一个宝可梦的生命值降至零以下时,它就会死亡。最终,如果玩家的宝可梦存活了下来,他就赢了游戏。
阅读全文