Created
February 25, 2016 03:16
-
-
Save kdstarter/9b35ef1f199c0cb576b6 to your computer and use it in GitHub Desktop.
A ruby client for Hangman Game.
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
require 'rest-client' | |
require 'json' | |
class HangmanClient | |
attr_reader :playerId, :sessionId, :number_of_words, :max_guess_count, :current_word, :result | |
def initialize(serverUri, playerId) | |
@serverUri = serverUri | |
@playerId = playerId | |
start_game | |
end | |
def start_game | |
start_game = post('startGame', playerId: @playerId) | |
@sessionId = start_game['sessionId'] | |
@number_of_words = start_game['data']['numberOfWordsToGuess'] | |
@max_guess_count = start_game['data']['numberOfGuessAllowedForEachWord'] | |
end | |
def next_word | |
result = post 'nextWord' | |
@result = result['data'] | |
end | |
def guess_word(letter) | |
return if game_over? | |
result = post 'guessWord', guess: letter.upcase | |
@result = result['data'] | |
end | |
def get_result | |
post 'getResult' | |
end | |
def submit_result | |
post 'submitResult' | |
end | |
def game_over? | |
success? || @max_guess_count <= @result['wrongGuessCountOfCurrentWord'] | |
end | |
def success? | |
!@result['word'].include?('*') | |
end | |
def post(action, params = {}) | |
result = {} | |
if action == 'startGame' | |
params.merge!({action: action}) | |
else | |
params.merge!({sessionId: @sessionId, action: action}) | |
end | |
result = RestClient.post @serverUri, params.to_json, content_type: :json | |
result = JSON.parse(result) if result.is_a? String | |
@current_word = result['data']['word'] if result['data']['word'].to_s != '' | |
puts "\nResult: {#{result}" | |
result | |
end | |
end | |
def force_guess(serverUri, playerId) | |
@client ||= HangmanClient.new(serverUri, playerId) | |
@client.next_word | |
(65..90).each { |num| | |
if @client.game_over? | |
if @client.success? | |
puts "==== #{@client.result} =====" | |
@client.submit_result && return | |
else | |
force_guess(serverUri, playerId) | |
end | |
else | |
@client.guess_word(num.chr) | |
end | |
} | |
end | |
force_guess('Replace me', 'Replace me') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment