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; //記錄對戰次數 //初始化:設置自己的名字 對手的名字,積分0 public 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<computer.score){ System.out.println ("很遺憾你輸瞭"); }else { System.out.println ("最終平局..."); } } public static void main ( String[] args ) { Game game = new Game (); game.start (); } }
測試結果顯示
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。