Java實現人機猜拳游戲
本文實例為大家分享了Java實現人機猜拳游戲的具體代碼,供大家參考,具體內容如下
實現:
User類
public class User { private String name; private int score=0; private int num; public String GetName() { return this.name; } public void SetName(String name) { this.name=name; } public int GetScore() { return this.score; } public void SetScore(int score) { this.score+=score; } }
Computer類
public class Computer { private String name; private int score=0; private int num; public String GetName() { return this.name; } public void SetName(String name) { this.name=name; } public int RandNums() { int n; n=(int)(Math.random()*3)+1;// 返回1到3的隨機整數。 return n; } public int GetScore() { return this.score; } public void SetScore(int score) { this.score+=score; }}
Gamemanager類
import java.util.Scanner; public class GameManager { public static void main(String[] args) { Scanner input=new Scanner(System.in);//創建一個鍵盤掃描類對象 User user=new User(); Computer computer=new Computer(); int vsNums=0; System.out.println('出拳游戲規則:1、剪刀,2、石頭,3、布'); System.out.println('請選擇對方角色(1、劉備,2、孫權,3、曹操)'); int n=input.nextInt(); //輸入整型 switch(n) { case 1: computer.SetName('劉備'); break; case 2: computer.SetName('孫權'); break; case 3: computer.SetName('曹操'); break; } System.out.println('請輸入你的姓名'); String name=input.next(); //輸入字符串型 user.SetName(name); System.out.println(user.GetName()+' '+'VS'+' '+computer.GetName()); String flag='y'; while(flag.equals(flag)) { System.out.println('要開始嗎y/n'); String yOrn=input.next(); //輸入字符串型 if(yOrn.equals('y')) { vsNums++; System.out.println('請出拳:1、剪刀,2、石頭,3、布(輸入數字)'); int nums=input.nextInt(); //輸入整型 switch(nums) { case 1: System.out.println('你出拳:'+'剪刀'); break; case 2: System.out.println('你出拳:'+'石頭'); break; case 3: System.out.println('你出拳:'+'布'); break; } int rand=computer.RandNums(); switch(rand) { case 1: System.out.println(computer.GetName()+'出拳:'+'剪刀'); break; case 2: System.out.println(computer.GetName()+'出拳:'+'石頭'); break; case 3: System.out.println(computer.GetName()+'出拳:'+'布'); break; } if(nums==1 && rand==3 || nums==2 && rand==1 || nums==3 && rand==2) { System.out.println('恭喜,你贏了'); user.SetScore(1); } else if(nums==rand) { System.out.println('平手了'); } else { System.out.println('很遺憾,你輸了'); computer.SetScore(1); } } else { System.out.println(computer.GetName()+' '+'VS'+' '+user.GetName()); System.out.println('對戰次數:'+vsNums); System.out.println('姓名t得分'); System.out.println(user.GetName()+'t'+user.GetScore()); System.out.println(computer.GetName()+'t'+computer.GetScore()); if(user.GetScore()>computer.GetScore()) { System.out.println('恭喜,恭喜'); } else { System.out.println('繼續加油'); } break; } } }}
更多有趣的經典小游戲實現專題,分享給大家:
C++經典小游戲匯總
python經典小游戲匯總
python俄羅斯方塊游戲集合
JavaScript經典游戲 玩不停
java經典小游戲匯總
javascript經典小游戲匯總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
