Skip to content

Instantly share code, notes, and snippets.

@mdm
Created March 3, 2010 14:17
Show Gist options
  • Save mdm/320634 to your computer and use it in GitHub Desktop.
Save mdm/320634 to your computer and use it in GitHub Desktop.
class Board
def initialize()
# 7 columns
@board = Array.new(7)
# 6 rows per column
for x in 0..6
@board[x] = Array.new(6)
for y in 0..5
@board[x][y] = 0
end
end
end
def draw
for y in 0..5
reverse_y = 5 - y
print reverse_y, " |"
for x in 0..6
print " ", @board[x][reverse_y]
end
# print special "newline" character
print "\n"
end
print " +"
for x in 0..6
print "--"
end
print "-\n"
print " "
for x in 0..6
print " ", x
end
print "\n\n"
end
def column_height(column)
# check column height
for y in 0..5
if (@board[column][y] == 0)
return y
end
end
return 6
end
def do_move(player_id, column)
height = column_height(column)
# make move if possible
if (height < 6)
@board[column][height] = player_id
success = true
else
success = false
end
return success
end
def undo_move(player_id, column)
height = column_height(column)
if (height > 0)
if (@board[column][height - 1] == player_id)
@board[column][height - 1] = 0
else
raise Exception.new("Trying to remove stone with incorrect player id.")
end
else
raise Exception.new("Trying to remove stone from empty column.")
end
end
end
board = Board.new()
player = 2
while (Board.game_over?(player))
if (player == 1)
player = 2
else
player = 1
end
board.draw()
if (player == 1)
# human player
success = false
while not success
print "Where do you want to move (enter a column number 0-6): "
column = gets.to_i()
success = board.do_move(player, column)
if not success
print "It's illegal to move in column ", column, ".\n"
end
end
else
# random computer player
success = false
while not success
column = rand(7)
success = board.do_move(player, column)
end
end
print "\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment