Automated S.O.S. game representation and extraction of game results

Viewed 375

I am creating a Python program which takes the dimensions of a rectangle shape and creates a table through lists. Then it must find the total amount of available positions and fill half of them with the letter 'S' and the remaining with letter 'O'. My goal is to count how many times the 'SOS' word appears horizontally, vertically & diagonally through a cycle of 50 repetitions and extract the average number of the triplets.

My code so far,

import random
n = 6
m = 7
a = [[i * j for j in range(m)] for i in range(n)]
for i in range(n):
    for j in range(m):
        if i < j:
            a[i][j] = 'O'
        elif i >= j:
            a[i][j] = 'S'

random.shuffle(a)
for i in range(50):
    for row in a:
        print(' '.join([str(elem) for elem in row]))

Although I am not sure if my method so far is appropiate, I need ideas on how to create the counting structure for horizontal, vertical and diagonal.

Thank you in advance

1 Answers

You could take a letter in a certain coordinate x,y and then search in a 3x3 block starting from that position, like so:

for y in range(len(a)): #cycle through every line
    for x in range(len(a[y])): #cycle through every column
        if a[y][x] == 'S':

            #check if it will go out of boundaries horizontally
            if not x >= len(a[y])-3:
                if a[y][x+1] == 'O' and a[y][x+2] == 'S':
                    #this will execute if there is a horizontal SOS
                    print(f"found horizontal SOS at position x: {x}; y: {y}")

            #check if it will go out of boundaries horizontally and vertically
            if (not x >= len(a[y])-3) and (not y >= len(a)-3):
                if a[y+1][x+1] == 'O' and a[y+2][x+2] == 'S':
                    #this will execute if there is a diagonal SOS
                    print(f"found diagonal SOS at position x: {x}; y: {y}")

            #check if it will go out of boundaries vertically
            if not y >= len(a)-3:
                if a[y+1][x] == 'O' and a[y+2][x] == 'S':
                    #this will execute if there is a vertical SOS
                    print(f"found vertical SOS at position x: {x}; y: {y}")

When we are checking if the script will go out of boundaries horizontally or vertically we subtract always 3 because there has to be minimum 2 position to look horizontally, the len() method returns the length of the list so since it starts at zero we subtract one and then 2 more because we need those 2 spaces.

Related