Tic Tac Toe

For beginners

Learn ruby by examples

Assumptions

  • 3X3 board
  • 2 players: X and O
  • players play the full game or enter 999 to stop
  • Smart-Stop is out of scope
  • players enter valid numbers (1..3 for the row and 1..3 for the columns)

 

 

Requirements 

  • build the board
  • print the board
  • get inputs from the user
  • switch players
  • end the game
  • validate moves
  • print out instructions for ease of use (optional)

 

Let's get started!

# initialize a variable, name, to hold a value "Sarah":
    name = "Sarah"

# print name to the screen
    puts name

# ask for user's age, read the input and save it to 
# a variable "age":
    age = gets

# define a method called 'say_hi' that takes an argument, name
# and prints a greeting:
    def say_hi(name)
        puts "Hi #{name}"
    end

# instance variable: the name of the instance variable starts 
# with '@', once the variable is defined, you can use it any 
# where in your class:
    @country = "USA"

# constant variable: constant variable's name is always in 
# uppercase, once constant variable has been initialized 
# it's value will not be changed
    SSN = "1234567890"
# array: array is a collection of elements,
# it's always good to use only one type in an array, 
# for example all strings, or all integer:
    my_arr = ["a", "b", "c", "d", "e", "f", "g"] 
    # you can access elements in the array via their index, 
    # array always starts at index 0
    my_arr[5]  # "f"
    my_arr[1] = "z" # ["a", "z", "c", "d", "e", "f", "g"] 


# conditions:
    if(condition)
        do_something
    elsif(another_contidion)
    .
    .
    .
    else
        do_something
    end

# some conditions:
    if(x == y) 		# if x and y are assert_equal
    if(x < y) 		# if x is less than y
    if(x <= y) 		# if x is less than or equal to y
    if(x > y) 		# if x is greater than y
    if(x >= y) 		# if x is greater than or equal to y
    if(something) 	# when the value of something is true
    if(!something)	# when the value of something is false


# Loop - in order to run a block at least once, you can use 
# begin/while loop:
    begin
        do_something
    end while(some_condition)

Some great tools and websites to learn ruby:

  • repl.it
  • https://www.codecademy.com/learn/ruby
  • https://ruby-doc.org/
  • https://github.com/bobbyno/ruby_drills
Made with Slides.com