I want to create a grid, but I'm not sure how to get it to display it correctly so that the grid includes "x" and doesn't look deformed

huangapple go评论68阅读模式
英文:

I want to create a grid, but I'm not sure how to get it to display it correctly so that the grid includes "x" and doesn't look deformed

问题

I'm a beginner to Python coding, and it's my first time asking a question here. So, I'm sorry if I make any mistakes in formatting this question.

As the title said, I am having trouble printing a grid so that it includes "x" while also ensuring that the grid stays in shape.

I have managed to create two versions of a code, one of which prints the grid in the desired shape, but does not include "x". The other one does include "x", but the grid is printed incorrectly.

Below is the one version of the code I have written:

from random import choice

grid_size = int(input("Enter grid size: "))
line = "-" * (7 + 6 * (grid_size-1))
main = []

def main_list():
    counter = grid_size
    while counter == grid_size or counter != 1:
        num(0)
        counter -= 1
    else:
        num(1)
        counter -= 1

def has_x():
    x = choice(range(len(main)))
    main[x] = "x"

def num(value):
    rand_num = choice(range(-30, 30))
    blank = " "
    main.append(rand_num)
    x = main[-1]

    if value == 0:
        if 0 <= x < 10:
            print("| ", x, end=blank*2)
        elif x >= 10 or -10 < x < 0:
            print("| ", x, end=blank)
        elif x <= -10:
            print("|", x, end=blank)
        elif x == 'x':
            print("|", 'x', end=blank)
    elif value == 1:
        if 0 <= x < 10:
            print("| ", x, end="  |\n")
        elif x >= 10 or -10 < x < 0:
            print("| ", x, end=" |\n")
        elif x <= -10:
            print("|", x, end=" |\n")
        elif x == 'x':
            print("|", 'x', end=" |\n")

def grid(grid_size):
    for i in range(grid_size):
        print(line)
        main_list()
    has_x()
    print(line)

grid(grid_size)

A sample output looks something like this:

>>> Enter grid size: 3
-------------------
| -14 |  -6 |  8  |
-------------------
| -24 | -24 |  26 |
-------------------
|  29 | -16 |  5  |
-------------------

The problem with this output is that since the numbers are being printed before has_x() is called, neither of the elements have been replaced with "x" yet, so it isn't displayed on the grid.

Another method I've tried is by making the following changes to main_list() and num():

def main_list():
    for i in range(grid_size):
        rand_num = choice(range(-30, 31))
        main.append(rand_num)

def num():
    for i in main:
        try:
            if 0 <= i < 10:
                print("| ", i, end="  ")
            elif i >= 10 or -10 < i < 0:
                print("| ", i, end=" ")
            elif i <= -10:
                print("|", i, end=" ")
        except:
            print("| ", "x", end="  ")

...and a sample output looks like this:

>>> Enter grid size: 3
-------------------
-------------------
-------------------
|  10 | -13 |  7  |  6  |  12 |  x  | -19 |  17 |  25 -------------------

Now, the "grid" properly displays "x", but its shape has been completely destroyed.

Is there a way for me to combine both of the codes I have written, so that has_x() is called before printing, and the grid is properly displayed?

英文:

I'm a beginner to Python coding, and it's my first time asking a question here. So, I'm sorry if I make any mistakes in formatting this question.

As the title said, I am having trouble printing a grid so that it includes "x" while also ensuring that the grid stays in shape.

I have managed to create two versions of a code, one of which prints the grid in the desired shape, but does not include "x". The other one does include "x", but the grid is printed incorrectly.

Below is the one version of the code I have written:

from random import choice
grid_size = int(input(&quot;Enter grid size: &quot;))
line = &quot;-&quot; * (7 + 6 * (grid_size-1))
main = []
def main_list():
counter = grid_size
while counter == grid_size or counter != 1:
num(0)
counter -= 1
else:
num(1)
counter -= 1
def has_x():
x = choice(range(len(main)))
main[x] = &quot;x&quot;
def num(value):
rand_num = choice(range(-30, 30))
blank = &quot; &quot;
main.append(rand_num)
x = main[-1]
if value == 0:
if 0 &lt;= x &lt; 10:
print(&quot;| &quot;, x, end=blank*2)
elif x &gt;= 10 or -10 &lt; x &lt; 0:
print(&quot;| &quot;, x, end=blank)
elif x &lt;= -10:
print(&quot;|&quot;, x, end=blank)
elif x == &#39;x&#39;:
print(&quot;|&quot;, &#39;x&#39;, end=blank)
elif value == 1:
if 0 &lt;= x &lt; 10:
print(&quot;| &quot;, x, end=&quot;  |\n&quot;)
elif x &gt;= 10 or -10 &lt; x &lt; 0:
print(&quot;| &quot;, x, end=&quot; |\n&quot;)
elif x &lt;= -10:
print(&quot;|&quot;, x, end=&quot; |\n&quot;)
elif x == &#39;x&#39;:
print(&quot;|&quot;, &#39;x&#39;, end=&quot; |\n&quot;)
def grid(grid_size):
for i in range(grid_size):
print(line)
main_list()
has_x()
print(line)
grid(grid_size)

A sample output looks something like this:

&gt;&gt;&gt; Enter grid size: 3
-------------------
| -14 |  -6 |  8  |
-------------------
| -24 | -24 |  26 |
-------------------
|  29 | -16 |  5  |
-------------------

The problem with this output is that since the numbers are being printed before has_x() is called, neither of the elements have been replaced with "x" yet, so it isn't displayed on the grid.

Another method I've tried is by making the following changes to main_list() and num():

def main_list():
for i in range(grid_size):
rand_num = choice(range(-30, 31))
main.append(rand_num)
def num():
for i in main:
try:
if 0 &lt;= i &lt; 10:
print(&quot;| &quot;, i, end=&quot;  &quot;)
elif i &gt;= 10 or -10 &lt; i &lt; 0:
print(&quot;| &quot;, i, end=&quot; &quot;)
elif i &lt;= -10:
print(&quot;|&quot;, i, end=&quot; &quot;)
except:
print(&quot;| &quot;, &quot;x&quot;, end=&quot;  &quot;)

...and a sample output looks like this:

&gt;&gt;&gt; Enter grid size: 3
-------------------
-------------------
-------------------
|  10 | -13 |  7  |  6  |  12 |  x  | -19 |  17 |  25 -------------------

Now, the "grid" properly displays "x", but its shape has been completely destroyed.

Is there a way for me to combine both of the codes I have written, so that has_x() is called before printing, and the grid is properly displayed?

答案1

得分: -1

以下是代码部分的翻译:

def print_grid(grid):
    # 假设grid是一个大小为n ** 2的列表,其中n是某个整数
    n = int(len(grid) ** 0.5)

    # 将所有的值转换为字符串
    grid = [str(value) for value in grid]

    # 每个块的间距等于
    # 网格中值的最大长度,再加2作为边距
    spacing = max(map(len, grid)) + 2

    h_line = "-" * (spacing * n + n + 1)
    v_bar = "|"

    for i in range(n):
        print(h_line)

        print(v_bar, end="")
        for j in range(n):
            value = grid[i * n + j]

            # 计算使值位于中间的位置
            remaining_space = spacing - len(value)
            left_margin = int(remaining_space / 2)
            right_margin = remaining_space - left_margin

            print(" " * left_margin + value + " " * right_margin + v_bar, end="")
        print()

    print(h_line)

def main():
    # 可以让用户选择这个值
    size = 5
    grid_size = size ** 2

    # 可以用随机函数替代range
    grid = list(range(grid_size))
    print_grid(grid)

    # 将网格中的一个块替换为"x"
    # 同样,你可以用随机方式替代这一步
    grid[-1] = "x"

    # 再次打印
    print_grid(grid)

if __name__ == "__main__":
    main()

希望这有助于你理解代码的中文翻译。

英文:

Since replacing a number with an 'x' means you have to recalculate all the spacings, it's most convenient to just print the whole table again.

Here's my implementation of a generic function that prints a grid regardless of what's in it.

def print_grid(grid):
# assume grid is a list of size n ** 2 for some n
n = int(len(grid) ** 0.5)
# convert all values to string
grid = [str(value) for value in grid]
# Spacing of each block equals
# maximum length of a value inside a grid, plus 2 for margin
spacing = max(map(len, grid)) + 2
h_line = &quot;-&quot; * (spacing * n + n + 1)
v_bar = &quot;|&quot;
for i in range(n):
print(h_line)
print(v_bar, end=&quot;&quot;)
for j in range(n):
value = grid[i * n + j]
# calculate so that the value appears in the middle
remaining_space = spacing - len(value)
left_margin = int(remaining_space / 2)
right_margin = remaining_space - left_margin
print(&quot; &quot; * left_margin + value + &quot; &quot; * right_margin + v_bar, end=&quot;&quot;)
print()
print(h_line)

The rest should be simple. First fill a grid and print it out, then replace one block with an "x", then print it out again.

def main():
# you may let user choose this value
size = 5
grid_size = size ** 2
# you may replace range with a randomizing function
grid = list(range(grid_size))
print_grid(grid)
# change one of grid&#39;s blocks to an &#39;x&#39;
# again, you may replace this with a randomizer
grid[-1] = &quot;x&quot;
# print it again
print_grid(grid)
if __name__ == &quot;__main__&quot;:
main()

huangapple
  • 本文由 发表于 2023年6月13日 10:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定