Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TicTacToe
- def initialize()
- @board = Array.new(9, " ")
- @player1 = {"name":nil, "mark":"X"}
- @player2 = {"name":nil, "mark":"O"}
- @players_turn = @player1
- @game_over = false
- @winner = nil
- set_names
- start_game
- end_game
- end
- def set_names
- player1_set = false
- until player1_set
- print "Player 1 enter your name: "
- input = gets.chomp
- @player1[:name] = input; player1_set = true if check_name(input)
- end
- player2_set = false
- until player2_set
- print "Player 2 enter your name: "
- input = gets.chomp
- @player2[:name] = input; player2_set = true if check_name(input)
- end
- end
- def start_game
- while !@game_over
- next_turn
- end
- end
- def next_turn
- board_set = nil
- good_input = nil
- until board_set
- good_input = ask_for_mark()
- if set_board(good_input) == true
- board_set = true
- else
- puts "This place is already taken"
- board_set = false
- end
- end
- check_if_ended ? @game_over = true : @game_over = false
- next_player
- end
- def next_player
- @players_turn == @player1 ? @players_turn = @player2 : @players_turn = @player1
- end
- def set_board(position)
- if @board[position - 1] == " "
- @board[position - 1] = @players_turn[:mark]
- return true
- else
- return false
- end
- end
- def ask_for_mark
- ask_ok = nil
- print_board
- until ask_ok
- print "#{@players_turn[:name]}, please enter where you want to put your #{@players_turn[:mark]}: "
- input = gets.chomp
- input == "exit" ? exit : input = input.to_i
- if good_mark?(input)
- return input
- else
- puts "Try again"
- ask_ok = false
- end
- end
- end
- def good_mark?(input)
- input.to_i > 0 && input.to_i < 10 ? true : false
- end
- def print_board
- print "
- | #{@board[0]} | #{@board[1]} | #{@board[2]} |
- ------------
- | #{@board[3]} | #{@board[4]} | #{@board[5]} |
- ------------
- | #{@board[6]} | #{@board[7]} | #{@board[8]} |
- \n"
- end
- def check_name(input)
- return input.length < 20 ? true : false
- end
- def check_if_ended
- if @board[0..2].uniq.length == 1 && @board[0] != " " ||
- @board[3..5].uniq.length == 1 && @board[3] != " " ||
- @board[6..8].uniq.length == 1 && @board[6] != " " ||
- @board[0] == @board[3] && @board[3] == @board[6] && @board[0] != " " ||
- @board[1] == @board[4] && @board[4] == @board[7] && @board[1] != " " ||
- @board[2] == @board[5] && @board[5] == @board[8] && @board[2] != " " ||
- @board[0] == @board[4] && @board[4] == @board[8] && @board[0] != " " ||
- @board[2] == @board[4] && @board[4] == @board[6] && @board[2] != " "
- @winner = @players_turn
- return true
- end
- @board.include?(" ") == true ? (return false) : @winner = nil; return true
- end
- def end_game
- print_board
- puts @winner == nil ? "There is no winner" : "The winner is #{@winner[:name]}"
- end
- end
- new_game = TicTacToe.new()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement