这不是一个关于如何在 PyGame 中绘制矩形的问题。但不知何故,我的代码覆盖了我正在绘制的内容,因此当我尝试在地图上绘制一个大的绿色矩形标记时,我只能看到添加到地图中的单个像素(绿色)。
这是我正在使用的命令:
pygame.draw.rect(display, (0, 255, 0), (x, y, 1000, 1000))
我只得到一个 1x1 矩形,而不是预期的 1000 x 1000。 那些也一样:
pygame.draw.rect(display, (0, 255, 0), (x, y, x + 1000, y + 1000))
pygame.draw.rect(display, (0, 255, 0), ((x, y), (x + 1000, y + 1000)))
pygame.draw.rect(display, (0, 255, 0), ((x, y), (1000, 1000)))
他们都画了一个1x1的矩形。这是为什么?
我确实看到了矩形,而且位置是正确的。只是尺寸造成了麻烦。 完整代码:
import pygame, os, sys, ast
pygame.init()
script_dir = os.path.dirname(os.path.abspath(__file__))
txt_path = os.path.join(script_dir, "map.txt")
zoom = 1
with open(txt_path, "r") as file:
data = file.read()
data = result = ast.literal_eval(data)
display = pygame.display.set_mode((len(data), len(data[0])))
x = 0
for line in data:
x += 1
y = 0
for pixel in line:
y += 1
if pixel == 0:
pygame.draw.rect(display, (0, 0, 0), (x* zoom, y * zoom, x* zoom + zoom, y * zoom + zoom))
elif pixel == 2:
plus = 200
pygame.draw.rect(display, (0, 255, 0), (x, y, 100, 100))
print(x, y)
else:
pygame.draw.rect(display, (255, 255, 255), (x* zoom, y * zoom, x* zoom + zoom, y * zoom + zoom))
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
该文件只是一个包含地图数据的列表。
这是绘制矩形的代码。
import pygame
# Initialize Pygame
pygame.init()
# Set the dimensions of the window
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# Define colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
# Run until the user asks to quit
running = True
while running:
# Did the user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the background with white
screen.fill(WHITE)
# Draw a green rectangle (x, y, width, height)
pygame.draw.rect(screen, GREEN, (50, 50, 200, 100))
# Update the display
pygame.display.flip()
# Done! Time to quit.
pygame.quit()
这就是结果: