连接四个游戏

时间:2018-12-07 09:45:25

标签: arrays ruby

在Ruby课堂上,我正在构建一个Connect Four游戏,我的教授将在命令提示符下运行该游戏。

必须使用双精度数组和while循环来完成,并且没有break / exit / abortloop do,类,实例,或全局变量。

我的网格数组由嵌套数组中的64个'.'占位符组成。我试图从8x8网格的底部开始,插入玩家的棋子:'X''0'

如果一列的底部行已经被占用,我不确定如何从第8行/索引7向上移动到第7行/索引6。我是否使用ifcase语句?我要减少行数吗?我曾尝试放入if / elsif,但无果而终。

def print_playing_grid (playing_board)
  puts "1 2 3 4 5 6 7 8"
  playing_board.each do |row|
    puts row.join(" ")
  end
end

print_playing_grid(grid_array)

# this 'win'/while is only here for testing so the board will repeat on screen
win = false
while win == false
  puts
  puts "Please select a column to make your move (Player X):"
  user_choice = gets.to_i
  row = 7
  column = user_choice - 1
  while row < grid_array.size
    grid_array[row][column] = 'X'
    row += 1
  end
  puts
  print_playing_grid(grid_array)
end

1 个答案:

答案 0 :(得分:0)

由于只有两个条件(单元是否被占用),我将更可能使用if而不是case ...我会在多个情况下使用case进行测试,因为它比ifelsif干净一点。

player_token = 'X'
row = grid_array.size - 1
column = user_choice - 1
while (grid_array.size - row) <= grid_array.size
  if grid_array[row][column] == '.'
    grid_array[row][column] = player_token
    row = -1 # (to exit the while loop)
  else
    row -= 1
  end
end

举一个我考虑使用案例的例子...

player_token = 'X'
row = grid_array.size - 1
column = user_choice - 1
dropping_a_token = true
while dropping_a_token
  case 
  when row < 0
    dropping_a_token = false
  when grid_array[row][column] == '.'
    grid_array[row][column] = player_token
    dropping_a_token = false
  else
    row -= 1
  end
end