Просто пытаюсь заставить изображения отображаться в двумерном массиве. То, что я пытаюсь сделать, - это то, что я написал в словаре, просто заменило бы то, что я написал в другом файле .txt.
Я действительно не хочу размещать 400 строк с кодами. Так что я удалил много кодов, просто к тому же возникает проблема.
def readFile (имя файла): я пытался увидеть, в чем проблема, просто возвращая char_positions. TKinter обнаружился. Но пришла только 1 картинка. и ничего больше. И когда я пишу pass вместо return, я получаю это сообщение
, строка 93, в createObjects для i в game_map:
TypeError: объект 'NoneType' не повторяется
import sys
import random
import time
from PIL import Image, ImageTk
from tkinter import Tk, Frame, Canvas, ALL, NW
BOARD_WIDTH = 1000 # In points px
BOARD_HEIGHT = 1000 # In points px
INFO_HEIGHT = 40 # Top info board in points px
STEP_SIZE = 40 # Size of objects in points px
MAX_RAND_POS = int(BOARD_WIDTH / STEP_SIZE) # If you want random spawns
NAMING = { 'M': "mario", 'P': "peach", 'B': "bowser", 'G': "goomba", 'K': "koopa", 'C': "cap", 'L': "mushroom", 'V': "wall", 'Y': "wall", 'T': "gate" }
PICTURES = { # Naming from map to image path,
'M' : "gameImages/mario.png", "P" : "gameImages/peach.png", "B" : "gameImages/bowser.png",
"G" : "gameImages/goomba.png", "K" : "gameImages/koopa.png", "C" : "gameImages/cap.png","L" : "gameImages/mushroom.png",
"V" : "gameImages/wall.png","Y" : "gameImages/wall.png" , "T" : "gameImages/gate.png"
}
def readFile(filename):
char_positions = {}
with open(filename, 'r') as f:
for y, line in enumerate(f):
for x, c in enumerate(line):
if not c.isspace():
char_positions[(x, y)] = c
pass
def main():
root = Tk() # Start graphics window
MarioGame("level1.txt") # Start Mario Game graphics inside root window
root.mainloop() # Run graphics loop
class Board(Canvas):
def __init__(self, level): # Python class initiation function
super().__init__(width=BOARD_WIDTH, height=BOARD_HEIGHT,
background="black", highlightthickness=0)
self.initGame(level)
self.pack()
def initGame(self, level):
'''initializes game'''
self.inGame = True # TRUE = Not finished
self.hasCap = False # super power
self.jumping = False # is jumping or not
self.jumptime = 0 # Store time when jump started here
self.life = 3 # Current number of lives
self.score = 0 # Current score
self.moveX = 0 # relative x direction coordinate
self.moveY = 0 # relative y direction coordinate
game_map = readFile(level) # Read in map
self.imagesDict = self.loadImages()
self.createObjects(game_map)
self.bind_all("<Key>", self.onKeyPressed)
# Debug specter mode
self.specterMode = False # press ctrl + s to change to True
def loadImages(self):
try: # All possible images here
imagesDict = {}
for key in PICTURES:
imagesDict[key] = self.loadImage(PICTURES[key])
# Special case for jumping mario
self.jmario = self.loadImage("gameImages/jumpingMario.png")
return imagesDict
except IOError as e:
print(e)
sys.exit(1)
def loadImage(self, path):
'''loads single image from the disk'''
openImg = Image.open(path)
openImg = openImg.resize((STEP_SIZE, STEP_SIZE), Image.ANTIALIAS)
return(ImageTk.PhotoImage(openImg))
def createObjects(self, game_map):
'''creates objects on Canvas'''
# Create score board
self.create_text(30, 10, text="Score: {0}".format(self.score),
tag="score", fill="white")
self.create_text(30, 30, text="Life: {0}".format(self.life),
tag="life", fill="white")
# Create map
for i in game_map:
map_type = game_map[i]
xCoord = i[0]*STEP_SIZE
yCoord = INFO_HEIGHT + i[1]*STEP_SIZE
if map_type == "M": # special case to hide jumping mario under mario
self.create_image(xCoord, yCoord, image=self.jmario,
anchor=NW, tag="jmario", state="hidden")
self.create_image(xCoord, yCoord, image=self.imagesDict[map_type],
anchor=NW, tag=NAMING[map_type])
class MarioGame(Frame):
def __init__(self, level):
super().__init__() # load init from super class
self.master.title('Mario 8-bit') # Title of window
self.board = Board(level)
self.pack()
if __name__ == '__main__' and len(PICTURES) > 0: # Call main if true
main()
else: # Else you have not done task 2 yet
print("Define PICTURES before you can start")
текстовый файл
YYYYYYYYYYYYYYYYYYYYYY
YM Y
Y Y
YVVVVVV VVVVVVVVVVY
Y K G K G CY
Y K K KVVVVVVVVVVY
Y LY
YV VVVVVVVVVVVVVVVVVVY
YV VL G KLY
YV V VVVV G KKY
YVGV V VVVV Y
YV V V G V G VVVV Y
YV V V V V GY
YVKV V VG V Y
YV VGGG V V Y
YV G V Y
YVVVVVVVVVVVVVVVVVVKVY
YL K G Y
Y G Y
Y K G VBVY
Y K VTPY
YYYYYYYYYYYYYYYYYYYY Y
Y Y Y
Y YTY