Java自制人机小游戏——————————剪刀、石头、布

2023-05-28,,

package com.hello.test;

import java.util.Scanner;

public class TestGame {

    public static void main(String[] args)
{
Player p = new Player() ; //实例化玩家对象 Game g = new Game(p) ;//实例化游戏对象 g.startGame();//调用方法
} } //游戏类
class Game
{
private Player p ; //设置玩家 public Game(Player p)
{
this.p =p ;
} //制定游戏规则
public int rule(String s1 ,String s2)
{
if(s1.equals(s2)) //先将电脑跟人出拳相同情况拿出
{
return 0 ;
}
if(s1.equals("剪刀"))
{
if(s2.equals("布"))
{
return 1 ;
}
if(s2.equals("石头"))
{
return -1 ;
}
}
if(s1.equals("石头"))
{
if(s2.equals("布"))
{
return -1 ;
}
if(s2.equals("剪刀"))
{
return 1 ;
}
}
if(s1.equals("布"))
{
if(s2.equals("剪刀"))
{
return -1 ;
}
if(s2.equals("石头"))
{
return 1 ;
}
}
return 0;
} public boolean panduan(String s)
{
if("剪刀".equals(s)||"布".equals(s)||"石头".equals(s)||"esc".equals(s))
{
return true ;
}
else
{
return false ;
}
} //游戏开始方法
public void startGame()
{
System.out.println("开始游戏"); System.out.println("请输入您的游戏昵称:"); Scanner s = new Scanner(System.in) ; String sg = s.nextLine() ; p.setName(sg); p.setScore(100); System.out.println("恭喜您注册成功,您的初始积分为100"); System.out.println(p.getName()+"进入游戏"); while(true)
{
String[ ] array = new String[ ] {"剪刀","石头","布"} ; System.out.println("请输入剪刀、石头或布,结束请输入esc"); Scanner sc = new Scanner(System.in) ; //提供输入窗口 String s1 = sc.nextLine() ; if(!panduan(s1))
{
System.out.println("输入有误,重新输入!");
continue ;
} if(s1.equals("esc"))
{
break ;
} int a = (int)(Math.random()*3) ; //随机0,1,2作为索引 String s2 = array[a] ; int it = rule(s1,s2) ; if(it>0)
{
System.out.println("您出的是"+s1+"电脑出的是"+s2);
System.out.println("恭喜"+p.getName()+"赢了,奖励10积分");
p.setScore(p.getScore()+10);
}
else if(it<0)
{
System.out.println("您出的是"+s1+"电脑出的是"+s2);
System.out.println("对不起"+p.getName()+"您输了,扣除10积分为");
p.setScore(p.getScore()-10);
}
else
{
System.out.println("您出的是"+s1+"电脑出的是"+s2);
System.out.println("打平了");
p.setScore(p.getScore());
}
System.out.println(p);
}
System.out.println(p.getName()+"退出了游戏,当前积分为:"+p.getScore());
} } //玩家类
class Player
{
private String name ; //玩家姓名 private int score ; //玩家积分 //setting、getting
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getScore() {
return score;
} public void setScore(int score) {
this.score = score;
} @Override
public String toString() {
return "玩家:" + name + ", 当前积分:" + score;
} }

Java自制人机小游戏——————————剪刀、石头、布的相关教程结束。

《Java自制人机小游戏——————————剪刀、石头、布.doc》

下载本文的Word格式文档,以方便收藏与打印。