Reputation: 11
I Just started programming with python and I've been tasked in printing a grid in python that looks as follows (image is attached). I'm really stumped on how i would achieve this through defining a function:
def display_game(game, grid_size):
The argument (game) is the strings that represent the cells in the game i.e (~), whilst the grid_size represents the size of the grid, i.e 7 would correspond to a 7x7 grid.
I know string splicing, for loops and print statements would be viable, i just don't know how to piece it together.
Any help would be much appreciated, Cheers.
Upvotes: 0
Views: 9350
Reputation: 152
def display_game(game, grid_size):
c = 65
# First row
print(f" ", end='')
for j in range(grid_size):
print(f"| {j+1} ", end='')
print("| ")
print((grid_size*4+4)*"-")
# Other rows
for i in range(grid_size):
print(f"{chr(c+i)} ", end='')
for j in range(grid_size):
print(f"| {game} ", end='')
print("| ")
print((grid_size*4+4)*"-")
display_game('~', 7)
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------
A | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
B | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
C | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
D | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
E | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
F | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
G | ~ | ~ | ~ | ~ | ~ | ~ | ~ |
--------------------------------
Upvotes: 2
Reputation: 2948
There you go:
def display_game(game, grid_size):
header_row = ''
row = ''
for x in range(1,grid_size+1):
header_row = header_row + '|' + str(x)
row = row + '|' + game
print(header_row + '|')
print('-' * (len(row)+1))
char = 64
for x in range(1,grid_size+1):
char = char +1
print(chr(char) + row + '|')
display_game('~', 7)
This should give the following output:
Upvotes: 0