【问题标题】:Is there a way to use for loops to make a game map in pygame?有没有办法使用 for 循环在 pygame 中制作游戏地图?
【发布时间】:2021-01-29 01:24:17
【问题描述】:

所以我想在我的 pygame 中使用 for 循环制作一个游戏地图,但显然我这样做的方式不起作用。代码如下,如果你能看一下就好了!

Pygame

import pygame
import sys
import random
import subprocess


# _______initiate Game______________ #
class Game:
    pygame.init()
    width = 800
    height = 800
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Maze Game")
    pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)

    white = [255, 255, 255]
    black = [0, 0, 0]
    lblue = [159, 210, 255]
    background = input(
        "What color background would you like? (White, Black, or Light Blue): ")
    if background == "White":
        screen.fill(white)
        pygame.display.flip()
    elif background == "Black":
        screen.fill(black)
        pygame.display.update()
    elif background == "Light Blue":
        screen.fill(lblue)
        pygame.display.update()
    else:
        screen.fill(black)
        pygame.display.update()
    for "." in "map1.txt":
        pygame.image.load("winter.Wall.png")



# ___________________TO RUN___________________________ #
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    if event.type == pygame.KEYDOWN:
        command = "python JakeGame.py"
        subprocess.call(command)

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.type == pygame.K_ESCAPE:
            pygame.quit()
# _______________________________________________ #

pygame.quit()

这是地图 txt 文件和我遇到的错误

...1...........................................
...11111111111111..............................
1111............11111111111111.................
1............................111...............
111............................................
1..............................................
111111111111111111111111111....................
..................1............................
1111111111111111111............................
..................1............................
..................11111111.....................
..........111111111......111111111.............
.................................1.............

所以基本上,我要做的是将所有这些时间段转换为加载名为 winterWall.png 的图像。

我得到的错误是“无法分配文字”谢谢你们的帮助:p

【问题讨论】:

  • 您有完整的错误文本吗?即堆栈跟踪?
  • 对于“。”在“map1.txt”中:^ SyntaxError: cannot assign to literal
  • 你对那行有什么期望?
  • 所有要替换为图片的句点

标签: python pygame


【解决方案1】:

这比你建议的要复杂一些(这是无效的语法)。

代码需要打开文件,然后遍历地图数据的行和列。然后,对于它找到的每种类型的字母,渲染某种基于图块的表示 - 这里我只使用了红色和绿色块。另一个版本也可以轻松渲染位图。

您需要做的第一件事是打开文件并将文本读入字符串列表 - 每行一个:

map_data = open( map_filename, "rt" ).readlines()

对这种方法的一个警告是,每一行的末尾仍然有其行尾。并且最好处理错误(例如文件丢失),而不是崩溃。

然后我们创建一个Surface,它只是一个离屏图像。它需要与地图一样大,乘以图块的大小。由于这是在 TileMap 类中创建的,因此它存储在 TileMap.image 中(即:self.image)。

接下来代码遍历每一行,然后每个字母绘制一个矩形。代码为此使用了常量TILE_SIZE。您需要确定这是否适用于彩色方块或位图等 - 但显然您的所有图块都需要使用相同的大小。

    # iterate over the map data, drawing the tiles to the surface
    x_cursor = 0  # tile position
    y_cursor = 0
    for map_line in map_data:             # for each row of tiles
        x_cursor = 0
        for map_symbol in map_line:       # for each tile in the row
            tile_rect = pygame.Rect( x_cursor, y_cursor, TileMap.TILE_SIZE, TileMap.TILE_SIZE )
            if ( map_symbol == '.' ):
                pygame.draw.rect( self.image, RED, tile_rect )
            elif ( map_symbol == '1' ):
                pygame.draw.rect( self.image, GREEN, tile_rect )
            else:
                pass  # ignore \n etc.
            x_cursor += TileMap.TILE_SIZE
        y_cursor += TileMap.TILE_SIZE

请注意,我们创建了 x_cursory_cursor。这是即将绘制的地图图块的左上角。当我们遍历每个角色时,我们会将其更新到地图上的下一个位置。

在每个点,地图都有一个 TILE_SIZE x TILE_SIZE (16x16)“单元格”,我们在其中绘制一个彩色方块,具体取决于地图项的类型。

在操作结束时,我们已经加载了所有的地图瓦片,并将地图绘制到屏幕外的Surface (self.image),可以快速轻松地绘制到屏幕上。

TileMap 类将所有这些简单地包装在一起。

参考代码:

import pygame

WINDOW_WIDTH = 800
WINDOW_HEIGHT= 600
SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE

#define colours
BLACK = (0,0,0)
RED   = ( 200, 0, 0 )
GREEN = (0,255,0)


### Class to render map-data to a surface image
class TileMap:
    TILE_SIZE=16    # size of map elements

    def __init__( self, map_filename ):
        """ Load in the map data, generating a tiled-image """
        map_data = open( map_filename, "rt" ).readlines()     # Load in map data  TODO: handle errors
        map_width  = len( map_data[0] ) - 1  
        map_length = len( map_data )
        # Create an image to hold all the map tiles
        self.image = pygame.Surface( ( map_width * TileMap.TILE_SIZE, map_length * TileMap.TILE_SIZE ) )
        self.rect  = self.image.get_rect()
        # iterate over the map data, drawing the tiles to the surface
        x_cursor = 0  # tile position
        y_cursor = 0
        for map_line in map_data:             # for each row of tiles
            x_cursor = 0
            for map_symbol in map_line:       # for each tile in the row
                tile_rect = pygame.Rect( x_cursor, y_cursor, TileMap.TILE_SIZE, TileMap.TILE_SIZE )
                if ( map_symbol == '.' ):
                    pygame.draw.rect( self.image, RED, tile_rect )
                elif ( map_symbol == '1' ):
                    pygame.draw.rect( self.image, GREEN, tile_rect )
                else:
                    pass  # ignore \n etc.
                x_cursor += TileMap.TILE_SIZE
            y_cursor += TileMap.TILE_SIZE

    def draw( self, surface, position=(0,0) ):
        """ Draw the map onto the given surface """
        self.rect.topleft = position
        surface.blit( self.image, self.rect )


### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), SURFACE )
pygame.display.set_caption("Render Tile Map")

### Load the map
tile_map = TileMap( "map1.txt" )


### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True

    # Update the window, but not more than 60fps
    window.fill( BLACK )

    # Draw the map to the window
    tile_map.draw( window )

    pygame.display.flip()
    clock.tick_busy_loop(60)

pygame.quit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-14
    • 2011-04-30
    • 2011-10-26
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    相关资源
    最近更新 更多