Skip to content

Instantly share code, notes, and snippets.

@Papillard
Last active September 20, 2022 20:12
Show Gist options
  • Save Papillard/2edebd2ba23a5efbbc89 to your computer and use it in GitHub Desktop.
Save Papillard/2edebd2ba23a5efbbc89 to your computer and use it in GitHub Desktop.
Longest-Word Rails livecode @lewagon
require 'open-uri'
require 'json'
class GameController < ApplicationController
def run
# build the grid
@grid = generate_grid(10).join
@start_time = Time.now
end
def score
# Retrieve all game data from form
grid = params[:grid].split("")
@attempt = params[:attempt]
start_time = Time.parse(params[:start_time])
end_time = Time.now
# Compute score
@result = run_game(@attempt, grid, start_time, end_time)
end
private
def generate_grid(grid_size)
Array.new(grid_size) { ('A'..'Z').to_a[rand(26)] }
end
def included?(guess, grid)
guess.split("").all? { |letter| grid.include? letter }
end
def compute_score(attempt, time_taken)
(time_taken > 60.0) ? 0 : attempt.size * (1.0 - time_taken / 60.0)
end
def run_game(attempt, grid, start_time, end_time)
result = { time: end_time - start_time }
result[:translation] = get_translation(attempt)
result[:score], result[:message] = score_and_message(
attempt, result[:translation], grid, result[:time])
result
end
def score_and_message(attempt, translation, grid, time)
if translation
if included?(attempt.upcase, grid)
score = compute_score(attempt, time)
[score, "well done"]
else
[0, "not in the grid"]
end
else
[0, "not an english word"]
end
end
def get_translation(word)
response = open("http://api.wordreference.com/0.8/80143/json/enfr/#{word.downcase}")
json = JSON.parse(response.read.to_s)
json['term0']['PrincipalTranslations']['0']['FirstTranslation']['term'] unless json["Error"]
end
end
# Very precious debug gems :)
gem 'binding_of_caller', group: :development
gem 'better_errors', group: :development
Rails.application.routes.draw do
root 'game#run'
get "game", to: "game#run"
get "result", to: "game#score"
end
<h1>WELCOME TO THE LONGEST WORD GAME</h1>
<h2>Grid: <%= @grid %></h2>
<form action="<%= result_path %>" method="get">
<input type="text" name="attempt">
<input type="hidden" name="grid" value="<%= @grid %>">
<input type="hidden" name="start_time" value="<%= @start_time %>">
<input type="submit" value="GO">
</form>
<h1>Your result</h1>
<ul>
<li>Attempt: <%= @attempt%></li>
<li>Translation: <%= @result[:translation]%></li>
<li>Time: <%= @result[:time]%></li>
<li>Message: <%= @result[:message]%></li>
<li>Score: <%= @result[:score]%></li>
</ul>
<%= link_to("Restart", game_path) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment