我的纹理渲染功能有什么问题以及我如何解决它?

What is problem in my texture rendering function and how I solve it?

我尝试在pygame中做了一个二维纹理渲染功能。但它不起作用。这是功能:

def drawTexture(screen,texture,rect):
    last_texture_x, last_texture_y = rect[2],rect[3]
    for texture_count_y in range(0,int(rect[3]/texture.get_height())+1):
        for texture_count_x in range(0,int(rect[2]/texture.get_width())+1):
            screen.blit(texture.subsurface(0,0,min(last_texture_x,texture.get_width()),min(last_texture_y,texture.get_height())),(rect[0]+texture.get_width()*texture_count_x,rect[1]+texture.get_height()*texture_count_y))
            last_texture_x -= texture.get_width()
        last_texture_y -= texture.get_height()

此函数用纹理填充矩形。它很好地填充了宽度。但是当矩形高度大于纹理高度时,它不会填充高度。我认为问题是 texture_count_y 变量。当我手动将变量替换为数字时,该函数起作用。但是当我打印它时变量 returns 是正确的值。我的脑袋现在真的很混乱。怎样才能让功能正常运行?

编辑:

红线表示矩形。 黄线表示纹理图像函数用于填充矩形。 它很好地填充了列,但填充了一行。

问题很简单。 last_texture_x必须在内循环之前初始化:

def drawTexture(screen, texture, rect):
    last_texture_y = rect[3]
    for texture_count_y in range(0,int(rect[3]/texture.get_height())+1):
        last_texture_x = rect[2]
        for texture_count_x in range(0,int(rect[2]/texture.get_width())+1):
                screen.blit(texture.subsurface(0,0,min(last_texture_x,texture.get_width()),min(last_texture_y,texture.get_height())),(rect[0]+texture.get_width()*texture_count_x,rect[1]+texture.get_height()*texture_count_y))
                last_texture_x -= texture.get_width()
        last_texture_y -= texture.get_height()

但是,我建议使用 pygame.Rect 对象的特性来完成此任务:

def drawTexture(screen, texture, rect):
    target_rect = pygame.Rect(rect)
    for x in range(target_rect.left, target_rect.right, texture.get_width()):
        for y in range(target_rect.top, target_rect.bottom, texture.get_height()):
            clip_rect = texture.get_rect(topleft = (x, y)).clip(target_rect)
            screen.blit(texture.subsurface(0, 0, *clip_rect.size), (x, y))

最小示例:

import pygame

pygame.init()
window = pygame.display.set_mode((500, 300))
clock = pygame.time.Clock()

def drawTexture(screen, texture, rect):
    target_rect = pygame.Rect(rect)
    for x in range(target_rect.left, target_rect.right, texture.get_width()):
        for y in range(target_rect.top, target_rect.bottom, texture.get_height()):
            clip_rect = texture.get_rect(topleft = (x, y)).clip(target_rect)
            screen.blit(texture.subsurface(0, 0, *clip_rect.size), (x, y))

target_rect = pygame.Rect(25, 25, 450, 250)
texture = pygame.Surface((200, 200))
texture.fill((255, 255, 0))
pygame.draw.rect(texture, (127, 127, 127), (2, 2, 196, 196))

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False      

    window.fill(0)
    pygame.draw.rect(window, (255, 255, 255), target_rect, 5)
    drawTexture(window, texture, target_rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()