Java实例01-HeroGame
实现一个文字类小游戏
代码:
import java.util.Scanner; /** * @author: TSCCG * @date: 2021/4/17 */ public class MyHero { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //英雄属性 System.out.print("请输入英雄的名字:"); String heroName = scanner.next(); System.out.print("请输入" + heroName + "的血量:"); int heroBlood = scanner.nextInt(); System.out.print("请输入" + heroName + "的攻击力:"); int heroAttack = scanner.nextInt(); System.out.print("请输入" + heroName + "的防御力:"); int heroDefence = scanner.nextInt(); //boss属性 String bossName = "古达"; int bossBlood = 10000; int bossAttack = 150; int bossDefence = 50; //战斗开始 while (heroBlood > 0 && bossBlood > 0) { //英雄攻击 bossBlood = getBlood(heroName, heroAttack, bossName, bossBlood, bossDefence); //判断boss是否死亡 if (bossBlood > 0) { //boss攻击 heroBlood = getBlood(bossName, bossAttack, heroName, heroBlood, heroDefence); } } if (heroBlood <= 0) { System.out.println(bossName + "击败了" + heroName); } else { System.out.println(heroName + "击败了" + bossName); } } private static int getBlood(String name1, int attack, String name2, int blood, int defence) { int damage = attack - defence; //防止伤害为负数 if (damage <= 0) { damage = 0; } else if (damage > blood) { //防止溢伤 damage = blood; } blood -= damage; sleep(1); System.out.println(name1 + "攻击了" + name2 + ",造成了" + damage + "点伤害," + name2 + "血量剩余" + blood + "点"); return blood; } public static void sleep(int time) { try { Thread.sleep(time * 1000L); } catch (InterruptedException e) { e.printStackTrace(); } } }
运行:
请输入英雄的名字:Ass 请输入Ass的血量:200 请输入Ass的攻击力:5 请输入Ass的防御力:5 Ass攻击了古达,造成了0点伤害,古达血量剩余10000点 古达攻击了Ass,造成了145点伤害,Ass血量剩余55点 Ass攻击了古达,造成了0点伤害,古达血量剩余10000点 古达攻击了Ass,造成了55点伤害,Ass血量剩余0点 古达击败了Ass