java实现简单猜拳小游戏

本文实例为大家分享了java实现猜拳小游戏的具体代码,供大家参考,具体内容如下
User.java

import java.util.Scanner; public class User {String name; int score; public int showFist(){System.out.println ("请出拳:1.剪刀\t2.石头\t3.布"); Scanner input=new Scanner ( System.in ); int choice=input.nextInt (); if(choice==1){System.out.println ("您出了剪刀"); }else if(choice==2){System.out.println ("您出了石头"); }else if (choice==3){System.out.println ("您出了布"); }else {System.out.println ("输入有误!"); }return choice; }}

Computer.java
public class Computer {String name; int score; public int showFist () {int choice = (int) (Math.random () * 3) + 1; //产生随机数if (choice == 1) {System.out.println (name +"出了剪刀" ); } else if (choice == 2) {System.out.println (name +"出了石头" ); } else if (choice == 3) {System.out.println (name +"您出了布" ); } else {System.out.println ( "输入有误!" ); }return choice; }}

Game.java
import java.util.Scanner; public class Game {User user; //用户Computer computer; //计算机int count; //记录对战次数//初始化:设置自己的名字对手的名字,积分0public void init(){System.out.println ("请输入自己的名字"); Scanner input = new Scanner ( System.in ); String name = input.next (); user=new User (); //对象初始化user.name=name; user.score=0; System.out.println ("请选择你的对手:\n1.张三\t2.李四\t3.王五"); int choice = input.nextInt (); computer=new Computer (); //对象初始化computer.score=0; switch (choice){case 1:computer.name="张三"; case 2:computer.name="李四"; case 3:computer.name="王五"; break; default:System.out.println ("输入有误!"); }System.out.println ("你选择与TA对战:"+computer.name); }public void start() {init (); Scanner input=new Scanner ( System.in ); String isContinue = null; do {int userFist = user.showFist (); //人出拳int chomputerFist = computer.showFist (); //计算机出拳calcResult ( userFist, chomputerFist ); System.out.println ("是否继续?y(继续)/其他(结束)"); isContinue=input.next (); }while ("y".equals ( isContinue )); showResult (user,computer); //显示最终结果}//计算每一轮的结果public void calcResult(int userFist,int computerFist){//"1.剪刀\t2.石头\t3.布"if((userFist==1&&computerFist==3)||(userFist==2&&computerFist==1)||(userFist==3&&computerFist==2)){System.out.println ("您赢了"); user.score++; }else if((userFist==3&&computerFist==1)||(userFist==1&&computerFist==2)||(userFist==2&&computerFist==3)){System.out.println ("您输了"); computer.score++; }else {System.out.println ("您平局"); }}//计算最终结果public void showResult(User user,Computer computer){System.out.println (user.name +"\t" +user.score ); System.out.println (computer.name +"\t" +computer.score); if (user.score>computer.score){System.out.println ("恭喜,获得了最终的胜利"); }else if (user.score
测试结果显示
【java实现简单猜拳小游戏】java实现简单猜拳小游戏
文章图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读