【发布时间】:2016-05-08 09:10:33
【问题描述】:
我是 Java 的初学者。我在大学第一门课程的第二周,已经喜欢编程了。我一直在尝试使用我在讲座和实验室中学到的一些东西来创建一个小游戏,但我遇到了一些问题。
代码如下:
public class MathGame {
public static void main(String args[]){
System.out.println("~~~~Welcome to ____!~~~~~");
System.out.println("Press 'S' to continue");
char startGame;
char correctStart = 'S';
startGame = TextIO.getChar();
if (startGame == correctStart){
System.out.println("Both you and the computer will start with 20 lives"); //Game explanation
System.out.println("Use different move options to reduce your opponents life");
System.out.println("First one down to zero loses!");
System.out.println("OK here we go:");
int lifeTotal1 = 10;
int lifeTotal2 = 10;
int turnNum = 0;
turnNum ++;
System.out.println("Start of turn: " + turnNum);
System.out.println("Your life total is " + lifeTotal1 + " your opponents life total is " + lifeTotal2); //Starts turn
System.out.println("Select a move:");
System.out.println("Press 1 to do 3 damage");
System.out.println("Press 2 to do a random amount of damage");
System.out.println("Press 3 to heal 2 damage");
int userAttack1;
userAttack1 = TextIO.getInt();
if(userAttack1 == 1){ //User attack #1 selected
lifeTotal2 -=3;
}
if(userAttack1 == 2){ //User attack #2 selected
double random1 = Math.random();
if (random1 > 0 && random1 <= .2){
lifeTotal2 -= 1;
}
if (random1 > .2 && random1 <= .4){
lifeTotal2 -= 2;
}
if (random1 > .4 && random1 <= .6){
lifeTotal2 -= 3;
}
if (random1 > .6 && random1 <= .8){
lifeTotal2 -= 4;
}
if (random1 > .8 && random1 <= 1){
lifeTotal2 -=5;
}
}
if (userAttack1 == 3){
lifeTotal1 += 2;
}
System.out.println("End of turn");
System.out.println("Your current health is " + lifeTotal1);
System.out.println("Your opponents current health is " + lifeTotal2);
if (lifeTotal1 <= 0){
System.out.println("Game over, you lose");
if (lifeTotal2 <= 0){
System.out.println("Game over, you win");
}
}else{
在 else 语句之后,我实际上只是复制并粘贴了代码以开始新的回合,直到其中一个生命总数降至 0。这是一个问题,因为它创建了有限数量的回合。如何让我的代码继续循环,直到生命总数达到零?
我知道游戏还远未完成。我将不胜感激任何帮助! 非常感谢
【问题讨论】:
-
A
while-loop是循环代码的常用方法。
标签: java loops if-statement while-loop