Created
July 11, 2013 13:27
-
-
Save timyates/5975428 to your computer and use it in GitHub Desktop.
Rock Paper Scissors with groovy-stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grab( 'com.bloidonia:groovy-stream:0.5.4' ) | |
import groovy.stream.Stream | |
// A random number generator | |
Random rnd = new Random() | |
// A list of possible moves | |
List moves = [ 'rock', 'paper', 'scissors' ] | |
// A map showing whch moves beat which | |
Map beats = [ 'rock' : 'scissors', | |
'paper' : 'rock', | |
'scissors' : 'paper' ] | |
// Each player is a Stream of moves | |
def player = { String name -> | |
Stream.from { [ player:name, move:moves[ rnd.nextInt( moves.size() ) ] ] } | |
} | |
// A Closure that declares a winner between two moves | |
def winner = { move1, move2 -> | |
def ret = "$move1.move vs $move2.move : " | |
if( move1.move == move2.move ) { ret + 'no one wins' } | |
else if( move2.move == beats[ move1.move ] ) { ret + "$move1.player wins" } | |
else { ret + "$move2.player wins" } | |
} | |
// Create a never-ending stream that gives us the winner of the two players | |
def judge = Stream.from { 1 } | |
.map { winner( p1.next(), p2.next() ) } | |
.using p1: player( 'tim' ), p2: player( 'alice' ) | |
// Play 10 games | |
(1..10).each { | |
println judge.next() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment