Pygame的screen.blit()如何从非零y坐标开始绘制?

3
我想在特定的层级[y]上画出草,下面只显示土地。这几乎是我所有的代码,只删除了无关的内容。
import pygame
from pygame import *

pygame.init()

width, height = 640, 480
screen = pygame.display.set_mode((width, height))
height_of_grass = 150
run = True
speed_of_player = 1

player = pygame.image.load("images/steve.png")
grass = pygame.image.load("images/grass_block.jpg")
dirt = pygame.image.load("images/dirt_block.jpg")
sky = pygame.image.load("images/sky.png")
clouds = pygame.image.load("images/cloud.png")
oak_wood_log = pygame.image.load("images/oak_wood_log.png")
oak_leaves = pygame.image.load("images/oak_leaves.png")

keys = [False, False, False, False]
player_position = [100, 100]

while run:
    screen.fill((50, 168, 158))


    screen.blit(player, player_position)
    for x in range(int(width/grass.get_width()) + 1):
        screen.blit(grass, (x*grass.get_width(), height_of_grass))
    x = 0
    for x in range(int(width/dirt.get_width()) + 1):
        for y in range(height_of_grass, int(height / grass.get_height()) + 1):
           screen.blit(dirt, (x*dirt.get_width, y*dirt.get_height))
    pygame.display.flip()

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


    if player_position[0] < -16 or player_position[0] > (width + 16) or player_position[1] < -16 or player_position[1] > (height + 16):
        print("You´ve broke the game! Congratilations")
        exit(-1)

这只是我遇到问题的部分代码。我的Pygame窗口没有显示下面的泥土。


我的问题仍然是一样的:代码没有显示草地下面的污垢。感谢您调试关闭序列。 - mkoo7mk
它必须是 if event.type == pygame.QUIT 而不是 if event == pygame.QUIT - Rabbid76
2个回答

3
由于内部循环的范围不正确和污垢瓷砖的y位置没有被正确计算,因此无法显示脏块。
计算污垢开始的y级别以及需要覆盖污垢的区域的高度:
dirt_start_height = height_of_grass + grass.get_width()
all_dirt_height = height - dirt_start_height

在绘制污垢的嵌套循环中使用dirt_start_heightall_dirt_height
while run:

    # [...]

    dirt_start_height = height_of_grass + grass.get_width()
    all_dirt_height = height - dirt_start_height
    for x in range(int(width/dirt.get_width()) + 1):
        for y in range(int(all_dirt_height / grass.get_height()) + 1):
           screen.blit(dirt, (x*dirt.get_width(), dirt_start_height + y*dirt.get_height()))

我已经在后面调用了pygame.flip.display.flip(),但我已将其放在此代码后面,仍然没有显示。 - mkoo7mk
这是我的第一个Python游戏和第一个较大的项目,我不知道处理是什么。 程序显示草和玩家没问题,但那块土地... - mkoo7mk
你让我的游戏运行更流畅,谢谢你。我有事件处理,但它不起作用:while run: for event in pygame.event.get(): if event == pygame.QUIT: run = False - mkoo7mk
@mkoo7mk 我已经修改了答案。 - Rabbid76

1
在你的“脏数据绘图循环”中,你正在查看 grass.get_height()
for x in range(int(width/dirt.get_width()) + 1):
    for y in range(height_of_grass, int(height / grass.get_height()) + 1):
        screen.blit(dirt, (x*dirt.get_width(), y*dirt.get_height()))

我认为你的意思是把 dirt.get_height 放在那里。

1
没起作用。在我的“草绘制循环”中,我使用了grass.get_width()它运行良好。 - mkoo7mk
1
很可能 dirt 是一个 pygame.Surface 对象,在这种情况下,使用 get_height() 是正确的。 - Rabbid76

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接