报错信息C:\Users\Lenovo\Desktop\aiXU1.cpp In function 'void Start()':
133 12 C:\Users\Lenovo\Desktop\aiXU1.cpp [Error] 'index' was not declared in this scope#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <bits/stdc++.h>
// 英雄类
class Hero {
public:
// 英雄的属性:名字,血量,攻击力,防御力,等级
std::string name;
int health;
int attack;
int defense;
int level;
// 构造函数
Hero(std::string name, int health, int attack, int defense, int level)
: name(name), health(health), attack(attack), defense(defense), level(level) {}
// 普通攻击,计算伤害并返回
int NormalAttack(Hero& enemy) {
int damage = attack - enemy.defense;
// 伤害最低为1
if (damage < 1) {
damage = 1;
}
enemy.health -= damage;
return damage;
}
// 技能攻击,可以给己方加血或给对方造成伤害
// 这里简单地定义为给己方加血
void SkillAttack(Hero& ally) {
ally.health += 10;
}
// 查看己方英雄的属性
void Show() {
std::cout << "名字: " << name << std::endl;
std::cout << "等级: " << level << std::endl;
std::cout << "血量: " << health << std::endl;
std::cout << "攻击力: " << attack << std::endl;
std::cout << "防御力: " << defense << std::endl;
}
};
// 己方队伍
std::vector<Hero> allies;
// 敌方队伍
std::vector<Hero> enemies;
// 游戏开始
void Start() {
// 初始化己方队伍
allies.push_back(Hero("无极剑圣", 100, 10, 5, 1));
allies.push_back(Hero("蛮族之王", 110, 11, 6, 2));
allies.push_back(Hero("德邦总管", 120, 12, 7, 3));
// 初始化敌方队伍
enemies.push_back(Hero("巨魔1", 100, 8, 3, 1));
enemies.push_back(Hero("巨魔2", 110, 9, 4, 2));
enemies.push_back(Hero("巨魔3", 120, 10, 5, 3));
enemies.push_back(Hero("巨魔4", 130, 11, 6, 4));
enemies.push_back(Hero("巨魔5", 140, 12, 7, 5));
// 游戏主循环
bool gameover = false;
while (!gameover) {
// 选择关卡
int level;
std::cout << "请选择关卡(1~5): ";
std::cin >> level;
level--; // 敌方队伍的索引是从0开始的
if (level >= 0 && level < enemies.size()) {
// 开始战斗
std::cout << "战斗开始" << std::endl;
// 判断游戏是否结束
bool gameover = false;
while (!gameover) {
// 己方回合
std::cout << "己方回合" << std::endl;
for (auto& ally : allies) {
std::cout << ally.name << ": " << std::endl;
// 显示己方英雄属性
ally.Show();
std::cout << "请选择攻击方式(1.普通攻击 2.技能攻击): ";
int choice;
std::cin >> choice;
if (choice == 1) {
// 普通攻击
int damage = ally.NormalAttack(enemies[level]);
std::cout << "造成" << damage << "点伤害" << std::endl;
} else if (choice == 2) {
// 技能攻击
ally.SkillAttack(ally);
std::cout << "使用技能攻击" << std::endl;
}
// 敌方队伍阵亡
if (enemies[level].health <= 0) {
std::cout << "敌方队伍阵亡" << std::endl;
gameover = true;
break;
}
}
// 敌方回合
std::cout << "敌方回合" << std::endl;
for (auto& enemy : enemies) {
// 敌方随机选择一个英雄进行攻击
int index = rand() % allies.size();
int damage = enemy.NormalAttack(allies[index]);
std::cout << enemy.name << "对" << allies[index].name << "造成" << damage << "点伤害" << std::endl;
// 己方队伍阵亡
if (allies[index].health <= 0) {
std::cout << "己方队伍阵亡" << std::endl;
gameover = true;
break;
}
}
}
// 战斗结束
std::cout << "战斗结束" << std::endl;
// 判断胜负
if (allies[index].health > 0) {
std::cout << "胜利" << std::endl;
} else {
std::cout << "失败" << std::endl;
}
} else {
std::cout << "无效的关卡" << std::endl;
}
}}
|