剪刀石头布游戏

1. 游戏结果

package cn.yjq.game;

public enum Outcome {
	//赢,输,平
	WIN, LOSE, DRAW;
}

2. 游戏Item

package cn.yjq.game;

import static cn.yjq.game.Outcome.*;

public interface Item {
	Outcome compete(Item it);
	Outcome eval(Paper p);
	Outcome eval(Scissors s);
	Outcome eval(Rock r);
}

class Paper implements Item {   //布
	public Outcome compete(Item it) { return it.eval(this); }
	public Outcome eval(Paper p) { return DRAW; }
	public Outcome eval(Scissors s) { return WIN; }
	public Outcome eval(Rock r) { return LOSE; }
	public String toString() { return "Paper"; }
}

class Scissors implements Item {   //剪刀
	public Outcome compete(Item it) { return it.eval(this); }
	public Outcome eval(Paper p) { return LOSE; }
	public Outcome eval(Scissors s) { return DRAW; }
	public Outcome eval(Rock r) { return WIN; }
	public String toString() { return "Scissors"; }
}

class Rock implements Item {   //石头
	public Outcome compete(Item it) { return it.eval(this); }
	public Outcome eval(Paper p) { return WIN; }
	public Outcome eval(Scissors s) { return LOSE; }
	public Outcome eval(Rock r) { return DRAW; }
	public String toString() { return "Rock"; }
}

3. 游戏机

package cn.yjq.game;

import java.util.Random;

public class Game {
	
	static final int SIZE = 10;
	static final Random random = new Random(47);
	
	public static Item newItem() {
		switch(random.nextInt(3)) {
			default :
			case 1 : 
				return new Paper();
			case 2 : 
				return new Scissors();
			case 3 : 
				return new Rock();
		}
	}
	
	public static void match(Item a, Item b) {
		System.out.println(a + " VS " + b + " : " + a.compete(b));
	}
	
	public static void main(String[] args) {
		for(int i=0; i<SIZE; i++) {
			match(newItem(), newItem());
		}
	}
	
}
//output
Scissors VS Scissors : DRAW
Paper VS Scissors : LOSE
Paper VS Scissors : LOSE
Paper VS Scissors : LOSE
Paper VS Paper : DRAW
Paper VS Paper : DRAW
Paper VS Paper : DRAW
Scissors VS Paper : WIN
Paper VS Paper : DRAW
Scissors VS Paper : WIN



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值