Java開發實現人機猜拳游戲
本文實例為大家分享了Java開發實現人機猜拳游戲的具體代碼,供大家參考,具體內容如下
猜拳游戲
游戲規則:人和電分別出剪刀、石頭、布,直到人戰勝電腦,游戲結束。
整體分析:
1、總體是一個循環 ->>>(while循環終止條件是人戰勝電腦,break;)2、人的出拳數字從鍵盤獲得 ->>>(Scanner)3、電腦的出拳數字隨機產生范圍是(1,2,3)->>>Math.random()4、出拳的數字轉換為文字 ->>>switch選擇,不同case,更改String的值5、判斷輸贏 ->>> 多重if語句
package com.gui;import java.util.Scanner;/** * java實現人機猜拳游戲 * 人和電腦分別出剪刀、石頭、布,直到人戰勝電腦,游戲結束 */public class Scissors_Stone_Cloth { public static void main(String[] args) { while (true) { System.out.println('*******************************'); System.out.println('--------歡迎進入猜拳游戲--------'); System.out.println('請出拳:(1是剪刀,2是石頭,3是布)'); Scanner sc=new Scanner(System.in); int person=sc.nextInt(); //獲取用戶輸入 int computer=(int)(Math.random()*3)+1; //電腦隨機出拳 String per='用戶'; String com = '電腦'; //用戶出拳 switch(person){ case 1: per='剪刀'; break; case 2: per='石頭'; break; case 3: per='布'; break; } //電腦出拳 switch(computer){ case 1: com='剪刀'; break; case 2: com='石頭'; break; case 3: com='布'; break; } //根據出拳判斷輸贏 if(person==1&&computer==2||person==2&&computer==3||person==3&&computer==1){ System.out.println('你出的是('+per+') 電腦出的是('+com+')'); System.out.println(' 【你輸了!再來一次吧】'); //System.out.println(); }else if (person==computer){ System.out.println('你出的是('+per+') 電腦出的是('+com+')'); System.out.println(' 【平局!再來一次吧】'); // System.out.println(); }else{ System.out.println('你出的是('+per+') 電腦出的是('+com+')'); System.out.println(' 【恭喜你贏了!!!】'); System.out.println('【你終于戰勝了電腦,游戲結束!】');; break; } } }}
結果:
更多有趣的經典小游戲實現專題,分享給大家:
C++經典小游戲匯總
python經典小游戲匯總
python俄羅斯方塊游戲集合
JavaScript經典游戲 玩不停
java經典小游戲匯總
javascript經典小游戲匯總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: