import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class FingerGuessing {
private String[] op = new String[] { "布", "剪刀", "石头" };
Random r = new Random();
private int wj = 0;
private int dn = 0;
private int count = 0;
private int go() {
int k = r.nextInt(3);
System.out.println("电脑:" + op[k]);
return k;
}
private void compare(int i) {
count++;
System.out.println("玩家:" + op[i - 1]);
int k = go();
if ( i - 1 == k) {
System.out.println("打平");
} else if ( i - 1 - k == 1 || i-1-k == -2) {
System.out.println("玩家获胜");
wj++;
} else {
System.out.println("电脑获胜");
dn++;
}
}
private void info() {
System.out.println("共" + count + "盘");
System.out.println("玩家获胜" + wj + "盘");
System.out.println("电脑获胜" + dn + "盘");
System.out.println("打平" + (count-wj-dn) + "盘");
}
public void start() {
String xz = "";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("n请选择:n1.布n2.剪刀n3.石头n结束请输入exit");
try {
xz = br.readLine();
if (xz.equalsIgnoreCase("exit")) {
info();
continue;
}
if (!xz.equals("1") & !xz.equals("2") & !xz.equals("3")) {
System.out.println("选择错误,请重新选择");
continue;
}
compare(Integer.parseInt(xz));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (!xz.equals("exit"));
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new FingerGuessing().start();
}
}
#include
#include
#include
void main()
{
int rand_0(void);
int game(int inp);
int start,yes=1,inp,inp_1=1;
char y;
while(yes) /*预防用户输入1或2以外的数据*/
{
printf("1:开始游戏n2:排行榜n");
scanf("%d",&start);
if((start!=1)&(start!=2))
{
printf("请输入1或2n");
}
else
yes=0;
}
start:
if(start==1) /*如果用户选择开始游戏……*/
{
printf("你出?n1:石头n2:剪刀n3:布n");
while(inp_1) /*预防用户输入别的数据*/
{
scanf("%d",&inp);
if((inp!=1)&(inp!=2)&(inp!=3))
{
printf("你出?n1:石头n2:剪刀n3:布n");
}
else
{
inp_1=0;
switch(game(inp))
{
case 1:printf("nn恭喜你,你赢了!nn");break;
case 0:printf("nn很遗憾,你输了!nn");break;
case 2:printf("nn平局nn");break;
}
}
}
}
inp_1=1;
printf("nn是否重新开始游戏?(y/n)");
scanf("%s",&y);
if((y=='y')||y=='Y')
goto start;
else
return 0;
}
int rand_0(void) /*取随机数*/
{
int i,rand_1;
srand((unsigned)time(NULL));
for(i=1;i
{
rand_1=rand()%4;
if(rand_1==0) continue;
return(rand_1);
}
}
int game(int inp)
{
int random,win; /*win变量,1是赢,2是平,0是输*/
random=rand_0();
switch(inp)
{
case 1:if(random==3) return win=0;
else if(random==2) return win=1;
else return win=2;
case 2:if(random==3) return win=1;
else if(random==2) return win=2;
else return win=0;
case 3:if(random==3) return win=2;
else if(random==2) return win=1;
else return win=0;
}
}
就做了那么点点。。。
以上是编写Java实现猜拳游戏!的详细内容。更多信息请关注PHP中文网其他相关文章!