猜数字游戏面向对象

Posted yangbocsu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了猜数字游戏面向对象相关的知识,希望对你有一定的参考价值。

猜数字游戏【面向对象】

一、Player 类

package com.yangbocsu.headfirstjava;

/**
 * @author: By yangbocsu
 * @date: 2022-03-10 14:30
 * @description:
 */
public class Player 
    public int number = 0;
    public void guess() 
        number = (int)(Math.random() * 10);
        System.out.println("I'm guessing " + number);
    



二、GuessGame 类

package com.yangbocsu.headfirstjava;

/**
 * @author: By yangbocsu
 * @date: 2022-03-10 14:30
 * @description:
 */
public class GuessGame 
    // 三个实例变量
    Player p1;
    Player p2;
    Player p3;

    public void startGame() 
        // 创建出Player 对象
        p1 = new Player();
        p2 = new Player();
        p3 = new Player();

        // 声明三个变量来保存猜的数字
        int guessp1 = 0;
        int guessp2 = 0;
        int guessp3 = 0;

        // 声明三个变量来保存是否猜中
        boolean p1isRight = false;
        boolean p2isRight = false;
        boolean p3isRight = false;

        int targetNumber = (int) (Math.random() * 10);
        while (true) 
            System.out.println("I'm thinking a number is " + targetNumber);
            p1.guess();
            p2.guess();
            p3.guess();

            guessp1 = p1.number;
            System.out.println("Player one guessed " + guessp1);

            guessp2 = p2.number;
            System.out.println("Player two guessed " + guessp2);

            guessp3 = p3.number;
            System.out.println("Player three guessed " + guessp3);

            // 检查各位选手有没有猜中,及时改变 pxisRight 的状态
            if (guessp1 == targetNumber) 
                p1isRight = true;
            
            if (guessp2 == targetNumber) 
                p2isRight = true;
            
            if (guessp3 == targetNumber) 
                p3isRight = true;
            

            if (p1isRight || p2isRight || p3isRight) 
                System.out.println("We have a winner!");
                System.out.println("Player one got it right?" + p1isRight);
                System.out.println("Player two got it right?" + p2isRight);
                System.out.println("Player three got it right?" + p3isRight);
                System.out.println("Gamer is over!");
                break;
             else 
                System.out.println("Players will have to try again.");
                System.out.println("----------------------------------\\n");
            
        
    


三、GameLauncher 类

package com.yangbocsu.headfirstjava;

/**
 * @author: By yangbocsu
 * @date: 2022-03-10 14:31
 * @description:
 */
public class GameLauncher 
    public static void main(String[] args) 
        GuessGame game = new GuessGame();
        game.startGame();
    


四、运行效果

以上是关于猜数字游戏面向对象的主要内容,如果未能解决你的问题,请参考以下文章

算术运算测试与猜数字游戏

第12次作业-Math对象猜数字游戏

第12次作业-猜数字游戏Math内置对象

java 猜数字游戏

从一个猜单词的小程序开始---征服OOP的思维方式01

用c#编写猜数游戏要求用户在文本框中输入1到10之间的一个数字。然后单击[猜猜]按钮产生一个随机数字,用户