Archive

Archive for the ‘Programming’ Category

Ruby Math Game

September 11, 2007 Leave a comment

Created this Ruby program some time ago while I was trying to learn the language. Always wanted to create one of these math games. The game is, of course, very basic, but I thought I’d share. No harm done, right?

So here it is.

=begin
Simple math game to practice addition, subtraction and multiplication.
=end

#Ask how many times it's going to be run
print("Welcome to this basic math program!")
print("\nFirst of all, what type of problems would you like to receive? \n1 = Addition\n2 = Subtraction\n3 = Multiplication\n4 = Random\n")
choice = gets.to_i #gets returns a String. Ruby never autoconverts to Integer, so to_i does that.
firstchoice = choice #necessary to have the random choice carried out properly

print("And how many problems do you wish to receive? ")
rounds = gets.to_i #gets returns a String. Ruby never autoconverts to Integer, so to_i does that.

#Defining the values to be factored into the questions
addminusmax = 50 #The max number of add and minus calcs
factormax = 12 #The max number of factor
try = nil

while rounds > 0
  #Defining and resetting variables
  if firstchoice == 4 #if the choice is 4, from now on, keep looping the random numbers for each round
   choice = 1 + rand(3) #the 1 + thing makes it a random draw from 1 to 3 instead of 0 to 3
  end
  ctries = 0 #default try count
  aaddminus = rand(addminusmax)
  baddminus = rand(addminusmax)
  cfactormax = 1 + rand(factormax)
  dfactormax = 1 + rand(factormax)
  
  #Asking the questions
  if choice == 1
    result = aaddminus + baddminus
    puts "What is the result of #{aaddminus} + #{baddminus}?"
  elsif choice == 2
    result = aaddminus - baddminus
    puts "What is the result of #{aaddminus} - #{baddminus}?"
  elsif choice == 3
    result = cfactormax * dfactormax
    puts "What is the result of #{cfactormax} * #{dfactormax}?"
  end  
    
  #This section is to check the answers
  while try != result    
    try = gets.to_i  #gets returns a String. Ruby never autoconverts to Integer, so to_i does that.      
    ctries+=1
    if (try < result)
      puts "Incorrect. Try again! Hint: it's bigger..."  
    elsif (try > result)
      puts "Incorect. Try again! Hint: it's smaller..."
   end
    if try == result #if answer is correct
      if ctries > 1 #formulate the right answer
        print "Answer #{result} is correct! And you did it in #{ctries} tries!\n\n"
      else print "Answer #{result} is correct! And you did it in just #{ctries} try!\n\n"
      end
    end
  end
  rounds -= 1
end
Advertisements
Categories: Programming