遊戲規則:

game會產生介於0~9的之間的隨機數字,有三個Player物件要去猜這個數字是什麼,此遊戲牽涉到gameplayer這兩個物件

小試身手小範例:

test.class

package p038;

public class test {
    public static void main(String[] args)
    {
        GuessGame Game = new GuessGame();
        Game.GameStart();
    }
}

Player.class

package p038;

public class Player {
    int nNumber = 0;
    String name;
    
    public void guess()
    {
        nNumber = (int)(Math.random()*10);
        System.out.println( name + " I'm guessing " + nNumber);
    }
}

GuessGame.class

package p038;

public class GuessGame {
    Player p1;
    Player p2;
    
    public void GameStart(){
        p1 = new Player();
        p2 = new Player();
        p1.name = "Player01";
        p2.name = "Player02";
        int targetNumber = (int)(Math.random()*10);
        System.out.println("Hint: The number between 0 and 9 ");
        while(true)
        {
            p1.guess();
            p2.guess();
            if(p1.nNumber == targetNumber)
            {
                System.out.println( p1.name + " Win!");
                break;
            }
            if(p2.nNumber == targetNumber)
            {
                System.out.println( p2.name + " Win!");
                break;
            }
        }
    }
}

運行結果(每次結果皆不同)

Hint: The number between 0 and 9 
Player01 I'm guessing 8
Player02 I'm guessing 9
Player01 I'm guessing 2
Player02 I'm guessing 0
Player01 I'm guessing 3
Player02 I'm guessing 2
Player01 Win!

 

文章標籤

S 發表在 痞客邦 留言(0) 人氣()