Last active
August 6, 2017 19:40
-
-
Save faustinoaq/3c3c034713719d82310df3439a892843 to your computer and use it in GitHub Desktop.
Tic Tac Toe implemented using Crystal.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tic Tac Toe on Crystal based on C implementation https://gist.github.com/MatthewSteel/3158579 | |
def grid_char(i) | |
case i | |
when -1 | |
'X' | |
when 0 | |
' ' | |
when 1 | |
'O' | |
end | |
end | |
def draw(b) | |
puts " #{grid_char b[0]} | #{grid_char b[1]} | #{grid_char b[2]}" | |
puts "---+---+---" | |
puts " #{grid_char b[3]} | #{grid_char b[4]} | #{grid_char b[5]}" | |
puts "---+---+---" | |
puts " #{grid_char b[6]} | #{grid_char b[7]} | #{grid_char b[8]}" | |
end | |
def win(board) | |
wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], | |
[1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] | |
8.times do |i| | |
if (board[wins[i][0]] != 0 && | |
board[wins[i][0]] == board[wins[i][1]] && | |
board[wins[i][0]] == board[wins[i][2]]) | |
return board[wins[i][2]] | |
end | |
end | |
0 | |
end | |
def minimax(board, player) | |
winner = win(board) | |
return winner*player if winner != 0 | |
move = -1 | |
score = -2 | |
9.times do |i| | |
if board[i] == 0 | |
board[i] = player | |
this_score = -minimax(board, -player) | |
if this_score > score | |
score = this_score | |
move = i | |
end | |
board[i] = 0 | |
end | |
end | |
return 0 if move == -1 | |
score | |
end | |
def computer_move(board) | |
move = -1 | |
score = -2 | |
9.times do |i| | |
if board[i] == 0 | |
board[i] = 1 | |
temp_score = -minimax(board, -1) | |
board[i] = 0 | |
if temp_score > score | |
score = temp_score | |
move = i | |
end | |
end | |
end | |
board[move] = 1 | |
end | |
def player_move(board) | |
move = 0 | |
loop do | |
print "\nMovimiento ([0..8]): " | |
input = gets | |
if input =~ /^[0-8]$/ | |
move = input.to_s.to_i | |
if board[move] != 0 | |
print "¡Ya esta ocupado!" | |
else | |
break | |
end | |
else | |
print "Movimiento incorrecto" | |
end | |
end | |
board[move] = -1 | |
end | |
board = [0, 0, 0, | |
0, 0, 0, | |
0, 0, 0] | |
puts "Computadora: O, Persona: X" | |
player = 0 | |
loop do | |
print "Turno (1)ro o (2)do?: " | |
case gets | |
when "1" | |
player = 1 | |
break | |
when "2" | |
player = 2 | |
break | |
else | |
print " opción incorrecta" | |
end | |
end | |
turn = 0 | |
while (turn < 9) && (win(board) == 0) | |
if (turn + player) % 2 == 0 | |
computer_move(board) | |
else | |
draw(board) | |
player_move(board) | |
end | |
turn += 1 | |
end | |
case win(board) | |
when 0 | |
puts "¡Empate!" | |
when 1 | |
draw(board) | |
puts "¡Perdiste!" | |
when -1 | |
puts "¡Ganaste!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment