Battle of the Robots

Let's take a look at what we have learned so far by making a simple game.

Problem statement

Let’s build a simple game together, to sum up, all information that we have gathered from the previous chapters. We’ll have 20 robots and two teams, with 10 robots in each team. Each team will be represented by its array, with a size of 10. Each element, or cell, of the array may have only one of these two values:

  1. 0 when the robot is destroyed.
  2. 1 when the robot is still alive.

Define two arrays. 1 in the example below indicates that we defined an array with robots who are still alive

arr1 =, 1)
arr2 =, 1)

Each team will attack one after the other. But what does it mean “to attack” in this case? If 1 in the array represents a robot that is alive, and 0 signifies a dead robot, then “to attack” means to "change the value for a certain cell in the array from 1 to 0.” But which cell are we going to attack? We have ten of them in each team. In this situation, we have two options:

  • We can “attack” the cells one by one, sequentially. In other words, we can start by attacking cell 1 of array 1, then cell 1 of array 2, and so on. Whoever starts attacking first wins the game. This approach seems predictable and doesn’t sound too interesting.

  • It’s much more fun to pick an index randomly. Randomness isn’t a guarantee that the index will remain unique while generating random numbers, so one team can attack the same cell of another team. For example, on a fifth turn, the second team will attack the third cell, but it’s possible that this cell was attacked before. So, the team won’t reach its goal in this turn of destroying the enemy, because the cell will already be equal to 0, and the number of destroyed enemies will remain the same. With this approach, the result of the battle is always determined by luck.

For now, let’s stick with the latter approach and implement our game this way. We already know how to generate a random index from 0 to 9:

i = rand(0..9)

We only need to access the array element and replace it with 0 if it is equal to 1. We can find out if the cell has already been attacked if its value is 0. Here is the Ruby code that implements this logic:

if arr[i] == 1
  arr[i] = 0
  puts "Robot by index #{i} destroyed"
  puts 'Oops, missed that!'

Get hands-on with 1200+ tech skills courses.