-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimedMathGame.rb
More file actions
84 lines (74 loc) · 2.03 KB
/
TimedMathGame.rb
File metadata and controls
84 lines (74 loc) · 2.03 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require 'date'
class Timer
def initialize
@start_time = DateTime.now
end
def reset
@start_time = DateTime.now
end
def passed
(DateTime.now - @start_time).to_f * 24 * 60 * 60
end
end
def add_gen(num1, num2)
puts "What is #{num1} + #{num2}?"
return num1 + num2
end
def sub_gen(num1, num2)
puts "What is #{num1} - #{num2}?"
return num1 - num2
end
if __FILE__ == $0
Thread.abort_on_exception = true
puts "Greetings traveler, what is your name?"
player_name = gets.chomp
right_now = DateTime.now
this_day = right_now.strftime(fmt='%Y%m%d')
player_file = "./#{player_name.downcase}-#{this_day}.txt"
if File.exists?(player_file)
file = File.open(player_file, "a+")
else
file = File.new(player_file, "w+")
end
puts "You've practiced #{file.readlines.length} times today."
puts "How long in seconds are you going to practice math today?"
time_limit = gets.chomp.to_f
correct = 0
incorrect = 0
number_limit = 11
timer = Timer.new
interrupt = false
Thread.new {
while true
if timer.passed >= time_limit
interrupt = true
puts "\nSorry, you've run out of time."
puts "You got #{correct} correct, and #{incorrect} incorrect."
final_grade = ((correct/(correct+incorrect).to_f)*100).round
puts "Your final grade is #{final_grade}%"
file.puts("#{right_now.strftime(fmt='%T')} #{player_name.downcase} got #{correct} out of #{correct + incorrect}, for a grade of #{final_grade}%.")
file.close
exit
end
end
}
until interrupt
puts "\n\n\nYou have #{(time_limit - timer.passed).round} seconds left."
num1 = rand(number_limit)
num2 = rand(number_limit)
if rand(2) == 1
answer = add_gen(num1, num2)
else
answer = sub_gen(num1, num2)
end
input = gets.chomp.to_i
if input == answer
correct += 1
puts "#{input} is correct!"
number_limit += 2
else
incorrect += 1
puts "I'm sorry, the correct answer was #{answer}."
end
end
end