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"));
}
/**
* @參數參數
*/
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或2\n");
}
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("\n\n恭喜你,你贏了!\n\n");break;
case 0:printf("\n\n很遺憾,你輸了!\n\n");break;
case 2:printf("\n\n平手\n\n");break;
}
}
}
}
inp_1=1;
printf("\n\n是否重新開始遊戲?(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中文網其他相關文章!