Home > Software engineering >  Dynamic python grid with random numbers and empty slots
Dynamic python grid with random numbers and empty slots

Time:12-11

I am currently having some issues with the task that I was given. Can someone help me with the task?

Thank you in advance.

Image 1 - (https://i.stack.imgur.com/cZAvs.png)

Image 2- (https://i.stack.imgur.com/kbfz0.png)

I did try to make the grid using random numbers but not sure how to add random empty spaces and crawl through the grid.

CodePudding user response:

you can use hack like:

create list with [" ", your_random_number_variable] and then pick one or the other and insert into your grid. It may not be the perfect solution, but it will solve your problem.

for crawl you can simply use any loop and if you found zero or empty in that list you can print your message.

CodePudding user response:

import random #random.randint()

class Make:

def __init__(self, board=[[], [], [], [], [], [], [], [], []]):
    self.board = board

def random_generate(self):

    for row in self.board:
        i = 9
        while i > 0:
            row.append(random.randint(0, 9))
            i -= 1
    def print_board(self):

    for row in self.board:
        i = 0
        for col in row:
            if i < (len(row) - 1):
                if int(col) == 0:
                    print(f'   | ', end='')
                else:
                    print(f'{col} | ', end='')
                i  = 1
            else:
                if int(col) == 0:
                    print(' ')
                else:
                    print(col)

def generate(self):

    self.board = [[random.randint(10, 40) if b != 0 else f'{b} ' for c, b in enumerate(d)]
                  for d in self.board]

def percolation(self):
    bottom_layer = []
    check_zeros = 0
    check_count = 0
    iterations = 0
    while check_count < 9:
        for row in self.board:
            if int(row[check_count]) >= 1:
                iterations  = 1
            check_zeros  = 1

            if check_zeros == 9:
                check_count  = 1
                check_zeros = 0
                if iterations == 9:
                    bottom_layer.append('OK')

                else:
                    bottom_layer.append('NO')
                iterations = 0

    for identifier in bottom_layer:
        print(f'{identifier}   ', end='')

def clear_board(self):
    self.board = [[], [], [], [], [], [], [], [], []]

if name == 'main':

game_run = True

while game_run:
    user_input = int(input('''\nWelcome to the percolation station!

  1. generate board
  2. Percolate it
  3. exit

Choose an option: '''))

    if user_input == 1:
        Game = Make()
        Game.clear_board()
        Game.random_generate()
        Game.generate()
        Game.print_board()

    if user_input == 2:
        Game.print_board()
        Game.percolation()

    if user_input == 3:
        break
  • Related