首页 > 解决方案 > Pygame 中的程序地形生成是颠倒的

问题描述

import pygame
import blocks
import random

class World:
    def __init__(self):
        self.tile_list = []
        TILESIZE = 20
        minStoneHeight = 1
        maxStoneHeight = 8
        x = 0
        y = 0
        height = 10
        width = 100


        for x in range(width):
            minHeight = height - 1
            maxHeight = height + 2
            height = random.randrange(minHeight, maxHeight)
            minStoneSpawnDistance = height - minStoneHeight
            maxStoneSpawnDistance = height - maxStoneHeight
            totalStoneSpawnDistance = random.randrange(minStoneHeight, maxStoneHeight)
            for y in range(height):
                if y < totalStoneSpawnDistance:
                    t = blocks.stoneBlock(x*20, y*20 + 100)
                    self.tile_list.append(t)
                else:
                    t = blocks.dirtBlock(x*20, y*20 + 100)
                    self.tile_list.append(t)
            if(totalStoneSpawnDistance == height):
                t = blocks.stoneBlock(x*20, y*20 + 100)
                self.tile_list.append(t)
            else:
                self.tile_list.append(t)
                t = blocks.stoneBlock(x*20, y*20+100)



    def draw(self, screen):
        for tile in self.tile_list:
            tile.draw(screen)

这是我在 pygame 中用于程序地形生成的代码。我根据 Unity 的 C# 脚本改编了它。问题是 pygames 网格起点在左上角,而统一在左下角。我想知道如何让我的地形不颠倒?

标签: pythonpython-3.xpygame

解决方案


这是缩进的问题。您必须在应用程序循环而不是事件循环中移动播放器:

running = True
while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                currentPlayerImg = playerImgBack
                playerYSpeed = -5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                playerYSpeed = 0

    #<--| INDENTATION
    
    playerX += playerXSpeed
    playerY += playerYSpeed

    screen.blit(bgImg, (0, 0))
    screen.blit(currentPlayerImg, (playerX, playerY))
    pygame.display.update()

推荐阅读