-
Notifications
You must be signed in to change notification settings - Fork 5
/
numguess.cr
64 lines (48 loc) · 1.52 KB
/
numguess.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
require "readline"
require "math"
# Reads a string from the terminal
def input(prompt : String)
Readline.readline(prompt + " ") || ""
end
# Reads a number from the terminal
# Returns a tuple of { value, valid? }
def inputNumber(prompt : String)
{ input(prompt).to_i, true }
rescue
{ 0, false }
end
puts "Welcome to NumGuess Crystal version!\n\n"
name = input("Enter your name:")
name = "Player" if name.empty?
limit = inputNumber("\nWelcome #{name}, enter upper limit:")[0]
limit = 10 if limit < 10
maxTries = Math.log2(limit).floor + 1
loop do
num = rand(limit) + 1
tries = 0
puts "\nGuess my number between 1 and #{limit}!\n\n"
loop do
result = inputNumber("Guess:")
guess = result[0]
isNum = result[1]
if !isNum || !(1..limit).includes?(guess)
puts "That's just plain wrong." unless isNum
puts "Out of range." if isNum
next
end
tries += 1
puts "Too low!" if guess < num
puts "Too high!" if guess > num
break if guess == num
end
puts "\nWell done #{name}, you guessed my number from #{tries} tr" + (tries == 1 ? "y!" : "ies!")
msg = "I find your lack of skill disturbing!"
msg = "Try harder, you can do better!" if tries <= limit
msg = "Very good result!" if tries <= maxTries * 1.1
msg = "You are a machine!" if tries == maxTries
msg = "You are the master of this game!" if tries < maxTries
msg = "You're one lucky bastard!" if tries == 1
puts msg
break unless input("Play again [y/N]?") =~ /y|Y/
end
puts "\nOkay, bye."