因此,我将计算机编程作为学校的一门学科,并被设定为创建类似游戏的地牢爬行者的任务。这主要是为了向我介绍多维数组的使用和从文件中读取。我能够成功地从文本文件中读取并创建 map ,但是在移动播放器时遇到了问题。我收到错误:
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 当我试图在 map 上移动代表角色的“+”时出现错误
elif gameMap[i][x] == "+":
gameMap[i][x] = "."
gameMap [i-1][x] = "+"
最佳答案
您的 gameMap 实际上是一个字符串列表,而不是列表列表。您收到该错误是因为您试图分配给字符串中的一个字母。如果你想让它成为列表的列表,你需要做这样的事情:
def createRoom():
return [list(row.rstrip('\n')) for row in open('Room 1.txt')]
关于python-2.7 - Python,多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22950133/