Я только учусь JSON и только что запуталась проблема. Я не уверен, как это структурировать и когда реализовать часть json.
вот инструкция
Характеристики
Если вы смотрите французское телевидение, возможно, вы наткнулись на Des chiffres et des lettres. Для английских студентов, вы можете быть более знакомы с обратным отсчетом!
Цель этого задания - написать упрощенную версию этой игры из терминала, где:
You are given a random set of letters.
You have to enter the longest english word you can find using only letters in the grid.
After typing your answer, you get your score combined with the time you took, and eventually an error message if you failed.
Ограничения:
You will use the Wagon Dictionary API. Let's have a look at what we get back from the API when we submit a correct English word and a wrong one. Pay attention to the structure of the URL.
Your grid must be a random grid where it's possible to embed the same characters multiple times.
Make sure you are validating that 1) your word is an actual English word, and 2) that every letter in your word appears in the grid (remember you can only use each letter once).
If the word is not valid or is not in the grid, the score will be 0 (and should be accompanied by a message to the player explaining why they didn't score any points).
The score depends on the time taken to answer, plus the length of the word you submit. The longer the word and the quicker the time, the better the score! Feel free to invent your own penalty rules too!
Ключевые пункты обучения
What's a JSON? How is it similar to the structure of a ruby hash?
How could you refactor your code to separate the responsibilities of each method?
Дополнительные предложения и ресурсы
Этот вызов намеренно не направляется. Вот некоторые элементы, которые помогут вам:
Write the pseudo code to figure out how to proceed before diving into the code
You can install the extension Json Formatter for Chrome to help you read a JSON rendered by an API (see JSONView for Mozilla)
Use the open-uri package from ruby standard library to make HTTP requests to this API and get a JSON result. Use the json package to parse returned JSON files.
For testing the grid inclusion, try making use of Enumerable#all?
Я испортил структуру и продолжаю получать ошибки в своем тесте. я не думаю, что я даже приближаюсь к тому, что мне нужно
мои методы в настоящее время (метод check_validity - это мое собственное творение, и он может пойти, если он только мешает):
require 'open-uri'
require 'json'
def generate_grid(grid_size)
# TODO: generate random grid of
counter = 0
a = []
charset = [*"A".."Z"]
while counter < grid_size
a << charset.sample(1)
counter += 1
end
return a
# ("a".."z").to_a.sample(9)
end
def run_game(attempt, grid, start_time, end_time)
# TODO: runs the game and return detailed hash of result
end
def check_validity(attempt)
word = attempt
url = "https://wagon-dictionary.herokuapp.com/#{word}"
word_list = open(url).read
word_check = JSON.parse(word_list)
end
def set_score(attempt, start_time, end_time)
# if word is not valid or not in a grid
end
мои тесты
require "longest_word"
describe "#generate_grid" do
let(:grid) { generate_grid(9) }
it "should generate grid of required size" do
expect(grid.size).to eq 9
end
it "should generate random grid" do
expect(grid).not_to eq generate_grid(9)
end
it "should allow for repetitive letters" do
long_grid = generate_grid(27)
expect(long_grid.uniq.length).not_to eq long_grid.length
end
end
describe "#run_game" do
let(:perfect) { run_game("wagon", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
let(:quick) { run_game("law", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
let(:slow) { run_game("law", %w(W G G Z O N A L), Time.now, Time.now + 10.0) }
let(:repetitive) { run_game("season", %w(S S A Z O N E L), Time.now, Time.now + 1.0) }
context "the given word is not an english one" do
let(:not_english) { run_game("zon", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
it "should compute score of zero for non-english word" do
expect(not_english[:score]).to eq 0
end
it "should build a custom message for an invalid word" do
expect(not_english[:message]).to match(/not an english word/i)
end
end
context "the given word is not in the grid" do
let(:not_in_the_grid) { run_game("train", %w(W G G Z O N A L), Time.now, Time.now + 1.0) }
it "should compute score of zero for word not in the grid" do
expect(not_in_the_grid[:score]).to eq 0
end
it "should build a custom message for a word not in the grid" do
expect(not_in_the_grid[:message]).to match(/not in the grid/i)
end
end
context "the given word has the correct letters but not in sufficient number" do
let(:not_enough_letters) { run_game("spell", %w(S P E L O O O O), Time.now, Time.now + 1.0) }
it "should tell it's not in the grid" do
expect(not_enough_letters[:score]).to eq 0
expect(not_enough_letters[:message]).to match(/not in the grid/i)
end
end
it "should compute higher score for longer word" do
expect(perfect[:score] > quick[:score]).to eq true
end
it "should compute higher score for quicker answer" do
expect(quick[:score] > slow[:score]).to eq true
end
it "should allow success when answer has repetitive letters" do
expect(repetitive[:score] > 0).to eq true
end
it "should build a custom messages for a correct word" do
expect(perfect[:message]).to match(/well done/i)
end
end
````````````````
my terminal interface
````````````````
require_relative "longest_word"
puts "******** Welcome to the longest word-game!********"
puts "Here is your grid:"
grid = generate_grid(9)
puts grid.join(" ")
puts "*****************************************************"
puts "What's your best shot?"
start_time = Time.now
attempt = gets.chomp
end_time = Time.now
puts "******** Now your result ********"
result = run_game(attempt, grid, start_time, end_time)
puts "Your word: #{attempt}"
puts "Time Taken to answer: #{result[:time]}"
puts "Your score: #{result[:score]}"
puts "Message: #{result[:message]}"
puts "*****************************************************"
Пока я только что сделал сетку и сгенерировал 9 случайных чисел. Если бы я мог получить помощь в выяснении, может быть, просто псевдокода для следующих шагов, я думаю, я мог бы, возможно, получить остальное самостоятельно.