ps:分享学习java的第五天
简单的文字格斗游戏
以下是我的运行结果和源代码
import java.util.Random;public class Role {private String name;//姓名private int blood;//血量public Role() {}public Role(String name, int blood) {this.name = name;this.blood = blood;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getBlood() {return blood;}public void setBlood(int blood) {this.blood = blood;}//定义一个方法,用于攻击别人//Role r1 = new Role();//Role r2 = new Role();//r1.攻击(r2);//方法的调用这去攻击参数;public void attack(Role role){//造成的伤害是随机的 1~20Random r = new Random();int hurt = r.nextInt(20) + 1;//this 表示方法的调用者 int remainBoold = role.getBlood() - hurt; remainBoold = remainBoold < 0 ? 0: remainBoold; //对剩余血量做一个验证,如果为负数了,则改为0//修改一下挨揍的人的血量role.setBlood(remainBoold);System.out.println(this.getName() + "举起拳头,打了"+ role.getName() +"一下," +"造成了" +hurt +"伤害,"+ role.getName()+"还剩下" + remainBoold+ "点血量");} }
public class game_text {public static void main(String[] args) {//1、创建第一个角色Role r1 = new Role("张三",100);//2、创建第二个角色Role r2 = new Role("李四",100);//3、开始格斗while (true){r1.attack(r2);if (r2.getBlood() == 0){System.out.println(r1.getName() + " KO了 " + r2.getName());break;}r2.attack(r1);if (r1.getBlood() == 0){System.out.println(r2.getName() + " KO了 " + r1.getName());break;}}} }