Question

So I do computer programming as a school subject and have been set the task of creating a dungeon crawler like game. This was primarily to introduce me to the use of multidimensional arrays and reading from files. I am able to successfully read from a text file and create the map but was having problems moving the player around. I get the error:

TypeError: 'str' object does not support item assignment

This is when I was trying to move the player around which makes me think I have incorrectly declared the array. Help plz! Here is the code:

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 I get the error when I am trying to move the "+" representing the character around a map

elif gameMap[i][x] == "+":
gameMap[i][x] = "."
gameMap [i-1][x] = "+"
Was it helpful?

Solution

Your gameMap is actually a list of strings, not a list of lists. You're getting that error because you're trying to assign to a letter in the string. If you want it to be a list of lists, you'll need to do something like this:

def createRoom():
    return [list(row.rstrip('\n')) for row in open('Room 1.txt')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top