猜拳小游戏
效果:
使用对象调方法实现此功能
入口类test,用于调用方法开始游戏
public class test {
/**
* 入口函数
* @param args
*/
public static void main(String[] args) {
// 实例化一个游戏对象
Game game = new Game();
// 让游戏开始
game.startGame();
}
Game类,程序的逻辑运行
public class Game {
/**
* 游戏开始
*/
public void startGame(){
System.out.println("猜拳小游戏");
// 实例化一个甲方对象
Player ply = new Player();
System.out.println(ply.Punches());
// 实例化出来一个电脑对象
Npc np = new Npc();
System.out.println(np.Punches());
// 判断对象的实例化
Referee rf = new Referee();
String str = rf.referee(ply.playerFist,np.npFist);
System.out.println(str);
}
}
Npc类,存放电脑随机出拳的方法
public class Npc {
String npFist;
public String Punches(){
// 电脑随机出一个数字
int random =1+ (int) (Math.random()*(3-1+1));
// 把电脑出的数字变成字符串
// 1.石头
// 2.剪刀
// 3.布
switch (random){
case 1:
npFist = "石头";
break;
case 2:
npFist = "剪刀";
break;
case 3:
npFist = "布";
break;
default:
npFist = "错误拳";
break;
}
return "电脑选择出拳:"+npFist;
}
}
Player类,用于存放玩家出拳的方法
import java.util.Scanner;
/**
* 玩家类
*/
public class Player {
/**
* 出拳方法,无参,有返回值
*/
String playerFist;
public String Punches(){
Scanner ipt = new Scanner(System.in);
// 玩家出拳
System.out.println("请输入你要出的拳");
System.out.print("(1.石头 2.剪刀 3.布):");
int choose = ipt.nextInt();
switch (choose){
case 1:
playerFist = "石头";
break;
case 2:
playerFist = "剪刀";
break;
case 3:
playerFist = "布";
break;
default:
playerFist = "false";
break;
}
// 返回玩家的出拳
return "玩家选择出拳:"+playerFist;
}
}
Referee类,存放用于判断输赢的方法
public class Referee {
String is_win;
public String referee(String ply, String np) {
if (ply.equals("石头")&&np.equals("剪刀")
||ply.equals("剪刀")&&np.equals("布")
||ply.equals("布")&&np.equals("石头")){
is_win = "胜利";
}else if (ply.equals(np)){
is_win = "平局";
}else{
is_win = "失败";
}
return "游戏结果:"+is_win;
}
}