Skip to content

Commit fb5e06e

Browse files
committed
add number guessing game
1 parent 6ea950e commit fb5e06e

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ Run `ruby tictactoe.rb` from your command line to enjoy a game of Tic-Tac-Toe.
66

77
Play against another human or play against the computer; play on a conventional 3x3 board or play on a 4x4 board. :)
88

9+
####number_guess.rb
10+
Run `ruby number_guess.rb` to see what this one does (or, just read the comments :).
11+
912
####cracklepop.rb
1013
Run `ruby cracklepop.rb` to see what this one does (or, just read the comments :).
1114

number_guess.rb

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# determine a random number from 1-100 & let the user guess the number
2+
# report back whether their guess is correct, too high, or too low
3+
4+
# if the user guesses a number they've already guessed,
5+
# tell them they have previously guessed this number
6+
7+
# once they've guessed the correct number, congratulate them &
8+
# tell them how many guesses they took to solve the problem (minus any duplicate guesses)
9+
10+
class Game
11+
def initialize
12+
@random_num = (1..100).to_a.sample
13+
@all_guesses = Array.new
14+
end
15+
16+
def initial_prompt
17+
print "\nGuess the number I have chosen (it's between 1 and 100): "
18+
receive_guess
19+
end
20+
21+
def receive_guess
22+
@guess = gets.chomp.to_i
23+
check_guess(@guess)
24+
end
25+
26+
def check_guess(guess)
27+
if (1..100).include?(@guess.to_i)
28+
if @all_guesses.include?(@guess)
29+
print "\nHEY! You've already guessed that! Guess again: "
30+
receive_guess
31+
else
32+
@all_guesses << @guess
33+
end
34+
35+
if @guess == @random_num
36+
print "\nCONGRATULATIONS! It only took you #{@all_guesses.count} unique guesses to guess correctly!"
37+
print "\nBye now!\n\n"
38+
exit(0)
39+
elsif @guess < @random_num
40+
print "\nYour guess is too low. Try again: "
41+
receive_guess
42+
else
43+
print "\nYour guess is too high. Try again: "
44+
receive_guess
45+
end
46+
else
47+
print "\nThat's not a valid choice."
48+
initial_prompt
49+
end
50+
end
51+
end
52+
53+
Game.new.initial_prompt

0 commit comments

Comments
 (0)