Skip to content

Instantly share code, notes, and snippets.

@msadoon
Created May 16, 2014 16:09
Show Gist options
  • Save msadoon/446d653c15c61afb95c6 to your computer and use it in GitHub Desktop.
Save msadoon/446d653c15c61afb95c6 to your computer and use it in GitHub Desktop.
a little console base tictactoe game I wrote in Ruby.
#init variables
endcase = 0
moveNum = 0
$firstmove = 0
$a,$b,$c,$d,$e,$f,$g,$h,$i = "?", "?", "?", "?", "?", "?", "?", "?", "?"
$v = "?"
def reset(a,b,c,d,e,f,g,h,i)
system('clear')
intro = "WELCOME TO TIC TAC TOE!\nMubarak Sadoon\nMay 15, 2014\nHelp: EX: \'1 3\' means row 1 column 3 or top left corner\nType 'exit' to leave game\n\n"
puts intro
grid = "\t\t#{a}|#{b}|#{c}\n\t\t#{d}|#{e}|#{f}\n\t\t#{g}|#{h}|#{i}\n"
puts grid
puts "\n"
end
def checkboard(v, moveNum)
if ((($v != 'x') || ($v != 'o')) && (moveNum.even?))
$v = 'x'
elsif ((($v != 'x') || ($v != 'o')) && (moveNum.odd?))
$v = 'o'
end
return $v
end
def checkend
if ([$a,$b,$c].all? {|x| x=='x'} || [$d,$e,$f].all? {|x| x=='x'} || [$g,$h,$i].all? {|x| x=='x'} || [$a,$d,$g].all? {|x| x=='x'} || [$b,$e,$h].all? {|x| x=='x'} || [$c,$f,$i].all? {|x| x=='x'} || [$a,$e,$i].all? {|x| x=='x'} || [$g,$e,$c].all? {|x| x=='x'})
return 'x wins!'
elsif ([$a,$b,$c].all? {|x| x=='o'} || [$d,$e,$f].all? {|x| x=='o'} || [$g,$h,$i].all? {|x| x=='o'} || [$a,$d,$g].all? {|x| x=='o'} || [$b,$e,$h].all? {|x| x=='o'} || [$c,$f,$i].all? {|x| x=='o'} || [$a,$e,$i].all? {|x| x=='o'} || [$g,$e,$c].all? {|x| x=='o'})
return 'o wins!'
elsif (($a != '?') && ($b != '?') && ($c != '?') && ($d != '?') && ($e != '?') && ($f != '?') && ($g != '?') && ($h != '?') && ($i != '?') && ($firstmove > 1))
return 'cats game!'
end
end
begin
reset($a,$b,$c,$d,$e,$f,$g,$h,$i)
moveNum += 1
if moveNum.even?
puts "X's move: "
else
puts "O's move: "
end
$v = gets.chomp
$firstmove += 1
case $v
when '1 1'
if ($a == '?')
$a = checkboard($a, moveNum)
else
moveNum -= 1;
end
when '1 2'
if ($b == '?')
$b = checkboard($b, moveNum)
else
moveNum -= 1;
end
when '1 3'
if ($c == '?')
$c = checkboard($c, moveNum)
else
moveNum -= 1;
end
when '2 1'
if ($d == '?')
$d = checkboard($d, moveNum)
else
moveNum -= 1;
end
when '2 2'
if ($e == '?')
$e = checkboard($e, moveNum)
else
moveNum -= 1;
end
when '2 3'
if ($f == '?')
$f = checkboard($f, moveNum)
else
moveNum -= 1;
end
when '3 1'
if ($g == '?')
$g = checkboard($g, moveNum)
else
moveNum -= 1;
end
when '3 2'
if ($h == '?')
$h = checkboard($h, moveNum)
else
moveNum -= 1;
end
when '3 3'
if ($i == '?')
$i = checkboard($i, moveNum)
else
moveNum -= 1;
end
else
#do nothing
moveNum -= 1
end
if (checkend === 'x wins!')
$v = 'exit'
elsif (checkend === 'o wins!')
$v = 'exit'
elsif (checkend === 'cats game!')
$v = 'exit'
else
reset($a,$b,$c,$d,$e,$f,$g,$h,$i)
end
if ($v === 'exit')
endcase = 1
puts checkend
end
end while (endcase === 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment