【问题标题】:Python, multidimensional arraysPython,多维数组
【发布时间】:2014-05-21 22:08:06
【问题描述】:

因此,我将计算机编程作为一门学校科目,并被设置为创建一个类似地牢爬行者的游戏。这主要是向我介绍多维数组的使用和从文件中读取。我能够成功地从文本文件中读取并创建地图,但是在移动玩家时遇到了问题。我得到了错误:

TypeError: 'str' object does not support item assignment

这是当我试图移动播放器时,这让我觉得我错误地声明了数组。请帮忙!代码如下:

import pygame, sys
from pygame.locals import *

def getResources():
    floorImage = pygame.image.load("/Volumes/Data/Users/name/Desktop/Python/Scripts/Pygame/RPG GAME FOLDER/floor.png")
    wallImage = pygame.image.load("/Volumes/Data/Users/name/Desktop/Python/Scripts/Pygame/RPG GAME FOLDER/wall.png")
    return (floorImage, wallImage)

def createRoom():
    f = open("Room 1.txt", "r")
    gameMap = []
    for x in f:
        row = ""
        for character in x:
            row = row + character
        if "\n" in row:
            row = row[:len(row) - 1]
        gameMap.append(row)
    return (gameMap)

def drawRoom(gameMap, floorImage, wallImage):

    for i in range(0, len(gameMap)):
        for x in range(0, len(gameMap[i])):
            xC = x * 30
            y = i * 30
            if gameMap[i][x] == "*":
                screen.blit(wallImage, (xC, y))
            elif gameMap[i][x] == ".":
                screen.blit(floorImage, (xC, y))
            elif gameMap[i][x] == "+":
                gameMap[i][x] = "."
                gameMap [i-1][x] = "+"

pygame.init()

FPS = 50
screen = pygame.display.set_mode((600, 600), 0, 32)
pygame.display.set_caption("RPG Game - name")
clock = pygame.time.Clock()


# Colours
black = (0, 0, 0)
white = (255, 255, 255)

# Player Variables
playerMotion = {
    "right": False
    }


# Initial Functions
floorImage, wallImage = getResources()
gameMap = createRoom()

while True:
    clock.tick(FPS)
    screen.fill(black)
    drawRoom(gameMap, floorImage, wallImage)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                playerMotion["right"] = True


    pygame.display.update()

P.S 当我试图在地图周围移动代表角色的“+”时出现错误

elif gameMap[i][x] == "+":
gameMap[i][x] = "."
gameMap [i-1][x] = "+"

【问题讨论】:

  • 你在哪一行得到这个错误?

标签: python-2.7 multidimensional-array pygame typeerror tile


【解决方案1】:

您的游戏地图实际上是一个字符串列表,而不是列表列表。您收到该错误是因为您试图分配给字符串中的一个字母。如果您希望它成为列表列表,则需要执行以下操作:

def createRoom():
    return [list(row.rstrip('\n')) for row in open('Room 1.txt')]

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 2010-10-05
    相关资源
    最近更新 更多