gpt4 book ai didi

Python 二维数组 - 引用网格的特定部分

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:44 27 4
gpt4 key购买 nike

我有一个 10x10 的网格,当前用零填充并使用 Pygame 的 freetype 模块渲染到屏幕上。

如何在 for 循环中呈现列表内容而不是硬编码“0”字符串?

import pygame
import pygame.freetype

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# Create a 2 dimensional array. A two dimensional
# array is simply a list of lists.
grid = [[0 for x in range(10)] for y in range(10)]

# Initialize pygame
pygame.init()

# Set the HEIGHT and WIDTH of the screen
WINDOW_SIZE = [255, 255]
screen = pygame.display.set_mode(WINDOW_SIZE)

# Loop until the user clicks the close button.
done = False

# -------- Main Program Loop -----------
while not done:

# Set the screen background
screen.fill(BLACK)

# Draw the grid
for row in range(10):
for column in range(10):
pygame.freetype.Font(None, 32).render_to(screen, (column * 32, row * 32), '0', WHITE)

pygame.display.flip()

pygame.quit()

最佳答案

您可以在此处使用enumerate 来获取您想要的任意大小的网格坐标:

    for i, row in enumerate(grid):
for j, item in enumerate(row):
pygame.freetype.Font(None, 32).render_to(screen, (j * 32, i * 32), str(item), WHITE)

这样您就不需要预先知道网格的大小。然后使用 str() 简单地获取单元格项目的字符串表示。

关于Python 二维数组 - 引用网格的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58281437/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com