人機猜拳遊戲Java
作業要求:
我的程式碼:
package day20181119;
/**
* 猜拳遊戲
* @author Administrator
* @version1.0
*/
import java.util.Scanner;
public class FingerGuessing {
String chName;
String name;
int i;
int ch1;
int Score1;
int ch2;
int Score2;
public void showLoginMenu(){
System.out.println("--------------歡迎來到遊戲世界------------");
System.out.println("\t***********************");
System.out.println("\t *****猜拳,開始*****");
System.out.println("\t***********************");
System.out.println("\n出拳規則:1.剪刀2.石頭3.布");
System.out.print("請選擇對方角色:(1.劉備2.孫權3.曹操)");
Scanner input=new Scanner (System.in);
int ch=input.nextInt();
if(ch==1){
chName="劉備";
showStartGame();
}else if(ch==2){
chName="孫權";
showStartGame();
}else if(ch==3){
chName="曹操";
showStartGame();
}else{
System.out.println("您的輸入有誤,請重新輸入!");
showLoginMenu();
}
}
public void showStartGame(){
Scanner input=new Scanner(System.in);
System.out.print("請輸入您的姓名:");
name=input.nextLine();
System.out.println(name+"VS"+chName+"對戰!");
showStart();
}
public void showStart(){
Scanner input=new Scanner(System.in);
i=i+1;
System.out.print("\n要開始第"+i+"輪嗎?(Y/N)");
String ch=input.nextLine();
if(ch.equals("Y")){
showFist();
}else{
showResult2();
}
}
public void showFist(){
System.out.print("請出拳:1.剪刀2.石頭3.布(輸入相應數字):");
Scanner input=new Scanner(System.in);
ch1=input.nextInt();
if(ch1==1){
System.out.println("你出拳:剪刀");
showComputer();
}else if(ch1==2){
System.out.println("你出拳:石頭");
showComputer();
}else if(ch1==3){
System.out.println("你出拳:布");
showComputer();
}
}
public void showComputer(){
ch2=(int)(Math.random()*3);
if(ch2==0){
System.out.println(chName+"出拳:剪刀");
showResult();
}else if(ch2==1){
System.out.println(chName+"出拳:石頭");
showResult();
}else if(ch2==2){
System.out.println(chName+"出拳:布");
showResult();
}
}
public void showResult(){
if(ch1==1&&ch2==1||ch1==2&&ch2==2||ch1==3&&ch2==0){
System.out.println("結果是:^_^,你輸了,下次加油啊!");
Score2++;
showStart();
}else if(ch1==1&&ch2==2||ch1==2&&ch2==0||ch1==3&&ch2==1){
System.out.println("結果是:恭喜,你贏了!");
Score1++;
showStart();
}else if(ch1==1&&ch2==0||ch1==2&&ch2==1||ch1==3&&ch2==2){
System.out.println("結果是:和局,真帥!");
showStart();
}
}
public void showResult2(){
System.out.println("------------------------------------");
System.out.println(name+"VS"+chName);
System.out.println("對戰次數:"+(i-1));
System.out.println("姓名\t得分");
System.out.println(name+"\t"+Score1);
System.out.println(chName+"\t"+Score2);
if(Score1>Score2){
System.out.print("結果:恭喜恭喜!");
}else if(Score1<Score2){
System.out.println("結果:下次再加油哦!");
}else if(Score1==Score2){
System.out.println("真是皆大歡喜的結局呢!");
}
System.out.println("------------------------------------");
}
}
-------------------------------------------------------------------------------------
package day20181119;
public class TestFingerGuessing {
public static void main(String[] args) {
FingerGuessing game=new FingerGuessing();
game.showLoginMenu();
}
}