红宝石战场游戏



这是一款经典的战舰游戏,适用于两名玩家:

#board1 and board2 arrays are boards that players see only dots (not bumped yet), O (not ship part) and X (bumped ship part) 
board1 = []
board2 = []
#Create the board that players can see through with terminal
for i in 0..4
board1.append("O")
end
for i in 0..4
board2.append("O")
end
def print_board(board1)
for row in board1
puts board1.map { |k| "#{k}" }.join("  ")
end
end
def print_board(board2)
for row in board2
puts board2.map { |k| "#{k}" }.join("  ")
end
end

print_board(board1)
puts "n"
print_board(board2)
#array1 and array2 are obvious boards of player1 and player2 respectly 
array1 = [ [0, 1, 1, 1, 0], [1, 0, 0, 0, 0], [1, 0, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 0, 0, 0] ]
array2 = [ [1, 0, 1, 1, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 1], [0, 1, 0, 0, 1], [0, 0, 0, 0, 0] ]
#Starting of the game and the printing the board 
while true do
puts "Welcome to the game!!!"
puts "Do you want to start? (start/reset):"
a = gets.chomp
if a == 'start'
for i in 0..100
puts "Turn - Player1: "
puts "Enter row: " 
q = gets.chomp
p1_row = q.to_i 
puts "Enter coloumn: " 
w = gets.chomp
p1_col= w.to_i
if array2[p1_row][p1_col] == 1
array2[p1_row][p1_col] ="X"
board2[p1_row][p1_col] ="X"
elsif array2[p1_row][p1_col] == 0
array2[p1_row][p1_col] ="-"
board2[p1_row][p1_col] ="-"
elsif array2[p1_row][p1_col] =="X" or array2[p1_row][p1_col] =="-"
next
end
print_board(board2)
puts "Turn - Player2: "
puts "Enter row: " 
e = gets.chomp
p2_row = e.to_i 
puts "Enter coloumn: " 
r = gets.chomp
p2_col= r.to_i
if array1[p2_row][p2_col] == 1
array1[p2_row][p2_col] ="X"
board1[p2_row][p2_col] ="X"
elsif array1[p2_row][p2_col] == 0
array1[p2_row][p2_col] ="-"
board1[p2_row][p2_col] ="-"
elsif array1[p2_row][p2_col] =="X" or array1[p2_row][p2_col] =="-"
next
end
print_board(board1)
end
elsif a == 'reset'
puts "You are off the game"
break
else
puts "n"
puts "Answer can be only {start} or {reset}"
end
end

我对这个代码有两个问题。当我为播放器2输入索引4时,我得到了"字符串中的索引4(IndexError(",但我没有找到原因。另一个问题是,当if语句找到1或0时,它会更改所有列,而不会只更改数组的元素。

主要问题在于您的董事会设置。你有

for i in 0..4
board1.append("O")
end

但这只会产生一个维度。试试这个:

for i in 0..4
board1[i] = []
(0..4).each do
board1[i].append("O")
end
end

第二个问题是子程序print_board。首先,您只需要子程序的一个定义,然后,映射需要应用于"行"而不是"板",如下所示:

def print_board(board)
for row in board
puts row.map { |k| "#{k}" }.join(" ")
end
end

您的代码还有许多其他问题。我假设您正在学习Ruby,这是学习Array API的练习。在这种情况下,你最好自己继续锻炼,边走边学。

不过,还有一个提示:了解rubocop并在代码中运行它。始终如一地做到这一点将教会你良好的Ruby风格,同时也会改进你的代码。具体来说:安装rubocop-gem,然后对您的代码运行rubocop,如下所示:

rubocop -SEa battleship.rb

最新更新