Question: Writing a program with a nested loop for the minefield game Write a program that asks, with a nested loop, the mine positions in a

Writing a program with a nested loop for the minefield game

Write a program that asks, with a nested loop, the mine positions in a 5 by 5 minefield, and it saves the information in a string. Then, it must print out the output (use the convention that a mine is a *, and a non-mine is a dash -).

The following is the representation of a 5 by 5 minefield with 5 mines:

Column #

1

2

3

4

5

Row #

1

-

-

-

-

*

2

-

-

*

-

-

3

-

*

-

-

-

4

-

-

-

-

*

5

*

-

-

-

-

The previous minefield is saved in a string variable with the content: mines=----*--*---*-------**----.

Use a for loop with a nested for loop for collecting the mine positions. Then, use a for loop to print the string in the shape of the minefield as in the previous table (print 5 chars per line).

You should do the following (those are hints to the solution):

Create default minefield with no mines first: mines=-------------------------

For both for-loops (i and j), use the range method as the following:

range(1,5+1)

Or (which has identical result):

range(1,6)

Every time you desire to add a mine in the string position index do the following:

mines=mines[0:index]+"*"+mines[index+1:]

This instruction will replace the char in position index with a *.

The first part of the instruction takes the part of the string before the index (mines[0:index]), the last takes whatever is after index (mines[index+1:]).

Instead, to calculate the index variable properly, you should do the following instruction:

index=(i-1)*5+(j-1)

Consider that i is the row counter for loop (outside loop), and j is the column counter in the for loop (nested, innermost loop).

Consider that the range method starts from 1 and ends with 5 included. In contrast, the string addressing starts with 0 and ends in our case with 24 included.

Note that mines[index+1:] is an instruction that tolerates index above the maximum value returning an empty string in such case: mines[25:] returns .

Add the program below:

Provide the screenshot of the run-output.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!