Created
November 1, 2011 20:43
-
-
Save balinterdi/1331841 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # Rock, paper and scissors with Node | |
| net = require 'net' | |
| hands = ['rock', 'paper', 'scissors'] | |
| win_rules = [ | |
| ['rock', 'scissors'], ['scissors', 'paper'], ['paper', 'rock'] | |
| ] | |
| human_wins = 0 | |
| ai_wins = 0 | |
| expand_hand = (hand) -> | |
| switch hand[0] | |
| when 'r' then 'rock' | |
| when 's' then 'scissors' | |
| when 'p' then 'paper' | |
| else | |
| hand | |
| random_hand = -> hands[Math.floor(Math.random() * 3)] | |
| display_result = -> "#{human_wins}-#{ai_wins}" | |
| fight = (one, two) -> | |
| return 'draw' if one is two | |
| res = 'lose' | |
| win_rules.forEach (rule) -> | |
| [win, lose] = rule | |
| if one is win and two is lose | |
| res = 'win' | |
| return res | |
| server = net.createServer (socket) -> | |
| socket.setEncoding 'utf8' | |
| socket.on 'data', (data) -> | |
| your_hand = data.replace(/\W+/,'') | |
| your_hand = expand_hand your_hand | |
| if your_hand in hands | |
| ai_hand = random_hand() | |
| result = fight your_hand, ai_hand | |
| if result is 'win' | |
| human_wins++ | |
| else if result is 'lose' | |
| ai_wins++ | |
| verbose_result = if result is 'draw' then 'Draw' else "You #{result}" | |
| socket.write "#{your_hand} vs. #{ai_hand}: #{verbose_result}. Score: #{display_result()}\r\n" | |
| if human_wins is 3 | |
| socket.end "Congratulations! You won.\r\n" | |
| else if ai_wins is 3 | |
| socket.end "You have to do better than this.\r\n" | |
| server.listen 1337, "127.0.0.1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment