Skip to content

Instantly share code, notes, and snippets.

@mcasey8540
Forked from dbc-challenges/card.rb
Created October 24, 2012 23:41
Show Gist options
  • Select an option

  • Save mcasey8540/3949628 to your computer and use it in GitHub Desktop.

Select an option

Save mcasey8540/3949628 to your computer and use it in GitHub Desktop.
FlashCardinator
# card.rb
class Card
attr_reader :term, :definition
def initialize(term, definition)
@term = term
@definition = definition
end
def match?(input)
input == @term
end
end
require_relative 'card'
describe Card do
let(:c) {Card.new("alias","To create a second name for the variable or method.")}
context '#initialize' do
it 'should have a term' do
c.term.should eql("alias")
end
it 'should have a definition' do
c.definition.should eql("To create a second name for the variable or method.")
end
end
end
require_relative 'card'
class Deck
attr_reader :position, :current_card
attr_accessor :cards
def initialize(file_name)
@cards = []
@file_name = file_name
from_file
@position = 0
end
def next_card
@position += 1
end_of_deck_error
current_card
end
def current_card
@cards[@position]
end
def match?(input)
current_card.match?(input)
end
private
def from_file
contents = File.read(@file_name)
contents.each_line do |line|
words = line.split
@cards << Card.new(words.shift, words.join(" "))
end
end
def end_of_deck_error
raise DeckError, "No more cards in the deck" if @cards[@position] == nil
end
end
class DeckError < StandardError;end
require_relative 'deck'
require_relative 'card'
describe Deck do
after(:each)
File.unlink('dummy.txt') if File.exists?('dummy.txt')
end
describe "#initialize" do
it 'should populate a new deck from a file' do
term = 'apple'
definition = 'fruit from tree'
File.open('dummy.txt', 'w+') do |line|
line.write "#{term}\t#{definition}"
end
cards = Deck.new('dummy.txt').cards
cards.first.term.should == term
cards.first.definition.should == definition
end
describe "card play" do
let(:d) {Deck.new('dummy.txt')}
before(:each) do
term_1 = 'apple'
def_1 = "red fruit"
term_2 = 'lemon'
def_2 = 'yellow fruit'
File.open('dummy.txt', 'w+') do |line|
line.write "#{term_1}\t#{def_1}\n#{term_2}\t#{def_2}"
end
end
it "#next_card" do
d.cards.first.term.should eql("apple")
d.cards.first.definition.should eql ("red fruit")
d.next_card.term.should eql("lemon")
end
it "next card should raise an error if end of deck" do
d.next_card
expect {d.next_card}.to raise_error
end
end
end
apple red fruit
lemon yellow fruit
alias To create a second name for the variable or method.
and A command that appends two or more objects together.
BEGIN Designates code that must be run unconditionally at the beginning of the program before any other.
begin Delimits a "begin" block of code, which can allow the use of while and until in modifier position with multi-line statements.
break Gives an unconditional termination to a code block, and is usually placed with an argument.
case starts a case statement; this block of code will output a result and end when it's terms are fulfilled, which are defined with when or else.
class Opens a class definition block, which can later be reopened and added to with variables and even functions.
def Used to define a function.
defined? A boolean logic function that asks whether or not a targeted expression refers to anything recognizable in Ruby; i.e. literal object, local variable that has been initialized, method name visible from the current scope, etc.
do Paired with end, this can delimit a code block, much like curly braces; however, curly braces retain higher precedence.
else Gives an "otherwise" within a function, if-statement, or for-loop, i.e. if cats = cute, puts "Yay!" else puts "Oh, a cat."
elsif Much like else, but has a higher precedence, and is usually paired with terms.
END Designates, via code block, code to be executed just prior to program termination.
end Marks the end of a while, until, begin, if, def, class, or other keyword-based, block-based construct.
ensure Marks the final, optional clause of a begin/end block, generally in cases where the block also contains a rescue clause. The code in this term's clause is guaranteed to be executed, whether control flows to a rescue block or not.
false denotes a special object, the sole instance of FalseClass. false and nil are the only objects that evaluate to Boolean falsehood in Ruby (informally, that cause an if condition to fail.)
for A loop constructor; used in for-loops.
if Ruby's basic conditional statement constructor.
in Used with for, helps define a for-loop.
module Opens a library, or module, within a Ruby Stream.
next Bumps an iterator, or a while or until block, to the next iteration, unconditionally and without executing whatever may remain of the block.
nil A special "non-object"; it is, in fact, an object (the sole instance of NilClass), but connotes absence and indeterminacy. nil and false are the only two objects in Ruby that have Boolean falsehood (informally, that cause an if condition to fail).
not Boolean negation. i.e. not true # false, not 10 # false, not false # true.
or Boolean or. Differs from || in that or has lower precedence.
redo Causes unconditional re-execution of a code block, with the same parameter bindings as the current execution.
rescue Designates an exception-handling clause that can occur either inside a begin<code>/<code>end block, inside a method definition (which implies begin), or in modifier position (at the end of a statement).
retry Inside a rescue clause, causes Ruby to return to the top of the enclosing code (the begin keyword, or top of method or block) and try executing the code again.
return Inside a method definition, executes the ensure clause, if present, and then returns control to the context of the method call. Takes an optional argument (defaulting to nil), which serves as the return value of the method. Multiple values in argument position will be returned in an array.
self The "current object" and the default receiver of messages (method calls) for which no explicit receiver is specified. Which object plays the role of self depends on the context.
super Called from a method, searches along the method lookup path (the classes and modules available to the current object) for the next method of the same name as the one being executed. Such method, if present, may be defined in the superclass of the object's class, but may also be defined in the superclass's superclass or any class on the upward path, as well as any module mixed in to any of those classes.
then Optional component of conditional statements (if, unless, when). Never mandatory, but allows for one-line conditionals without semi-colons.
true The sole instance of the special class TrueClass. true encapsulates Boolean truth; however, <emph>all</emph> objects in Ruby are true in the Boolean sense (informally, they cause an if test to succeed), with the exceptions of false and nil.
undef Undefines a given method, for the class or module in which it's called. If the method is defined higher up in the lookup path (such as by a superclass), it can still be called by instances classes higher up.
unless The negative equivalent of if. i.e. unless y.score > 10 puts "Sorry; you needed 10 points to win." end.
until The inverse of while: executes code until a given condition is true, i.e., while it is not true. The semantics are the same as those of while.
when Same as case.
while Takes a condition argument, and executes the code that follows (up to a matching end delimiter) while the condition is true.
yield Called from inside a method body, yields control to the code block (if any) supplied as part of the method call. If no code block has been supplied, calling yield raises an exception.
require_relative 'deck'
class GameUI
attr_reader :deck, :guess_number
MAX_GUESS_COUNT = 3
def initialize(deck)
@deck = deck
@guess_number = 0
game_start
end
def match(input)
if @deck.match?(input)#input == @deck.current_term#.current_card.term
correct!
@deck.next_card
reset_guess_count
else
@guess_number += 1
incorrect!
if too_many_guesses?
failed!
@deck.next_card
reset_guess_count
end
end
end
private
def too_many_guesses?
@guess_number == MAX_GUESS_COUNT
end
def reset_guess_count
@guess_number = 0
puts "You've got #{MAX_GUESS_COUNT} guesses left."
end
def correct!
puts "Good job! Next card is coming up."
end
def incorrect!
puts "You suck. Try again!"
end
def failed!
puts "You fail at life. We are moving on to the next card. Try harder next time."
end
def game_start
input = ""
puts "Welcome to FlashCardinator!"
puts "---------------------------"
puts "Enter 1 to practice. Enter 2 to play."
input = gets.to_i
case input
when 1
practice
when 2
game
end
end
def practice
puts "Memorize these flash cards. Hit any key to view next card. Hit 'Q' to quit."
input = ""
while input != 'Q'
puts "#{@deck.current_card.term}: #{@deck.current_card.definition}"
@deck.next_card
input = gets.chomp
end
end
def game
puts "You have #{MAX_GUESS_COUNT} guesses for each card. Go big or go home! Hit 'Q' to quit."
input = ""
while input != 'Q'
puts "Guess the term for: #{@deck.current_card.definition}"
input = gets.chomp
match(input)
end
end
end
GameUI.new(Deck.new('flashcards_data.txt'))
require_relative 'deck'
require_relative 'game'
describe GameUI do
let(:g) {GameUI.new(Deck.new('dummy.txt'))}
describe "should start with a deck of cards loaded" do
it "#initialize" do
g.deck.cards.should_not be_empty
end
end
describe "game play" do
let(:g) {GameUI.new(Deck.new('dummy.txt'))}
before(:each) do
term_1 = 'apple'
def_1 = "red fruit"
term_2 = 'lemon'
def_2 = 'yellow fruit'
File.open('dummy.txt', 'w+') do |line|
line.write "#{term_1}\t#{def_1}\n#{term_2}\t#{def_2}"
end
end
it "#guess_number equals two when guess is incorrect" do
g.deck.current_card
g.match("lemon")
g.guess_number.should eql(1)
end
it "incorrect input resets guess_number" do
g.match("orange")
g.match("orange")
g.match("orange")
g.guess_number.should eql(0)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment