Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9020977
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T05:08:55+00:00 2026-06-16T05:08:55+00:00

So I’m trying to pass vars from one class to another. I want the

  • 0

So I’m trying to pass vars from one class to another. I want the Map class to receive the vars from the Game class. When I run it I get an error:

self.width      = w*self.multi 
TypeError: Error when calling the metaclass bases
can't multiply sequence by non-int of type 'dict'

How can I fix this, or should I be going about this differently?

import pygame, os
from pygame.locals import *
from pygame import Color
from time import time
from datetime import datetime




class Game():
    """ Lets try to get this going by simple steps
    One by one. First step, lets figure how to make a class
    that can do the display stuff. NOTE TO SELF: Remember, these
    are only called ONCE at the start. Lord have mercy on my soul"""
    def __init__(self, w=256, h=224, multi=3):
        """Initialization"""
        pygame.init()
        self.multi      = multi
        self.runGame    = True
        self.width      = w*self.multi
        self.height     = h*self.multi
        self.sprSz      = 16*self.multi
        self.clock      = pygame.time.Clock()
        self.screen     = pygame.display.set_mode((self.width, self.height))
        self.kl         = []
        self.walk       = [0, 0]
        self.speed      = self.multi*1.5
        self.x,self.y   = (self.width/2-(self.sprSz/2)), (self.height/2-(self.sprSz/2))
        self.music      = self.sndLoad('relent.ogg')
        self.playerSpr  = self.imgLoad('link1.png', self.multi, 0, 0)
        self.playerRec  = Rect(self.x,self.y,self.sprSz,self.sprSz)
        self.aSprite    = self.imgLoad('greenwall_01.png', self.multi, 0, 0)
        self.aSpriteRec = Rect(self.aSprite.get_rect())


    def imgLoad(self, image, size, flipx, flipy):
        try:
            self.img=pygame.image.load('images/'+image).convert_alpha()
        except pygame.error, message:
            print "Unable to load image: " + image
            raise SystemExit, message               
        if size>1:
            self.img=pygame.transform.scale(self.img, (self.img.get_width()*size, self.img.get_height()*size))
        if flipx==1:
            self.img=pygame.transform.flip(self.img, True, False)
        if flipy==1:
            self.img=pygame.transform.flip(self.img, False, True)
        if flipy>1 or flipy<0:
            self.img=pygame.transform.rotate(self.img, flipy)        
        return self.img


    def sndLoad(self, sound):
        try:
            self.sound = pygame.mixer.Sound('sounds/'+sound)
        except pygame.error, message:
            print "Cannot load sound: " + sound
            raise SystemExit, message
        return self.sound    


    def mainLoop(self):
        """Loop through the main game routines
        1. Drawing  2. Input handling  3. Updating
        Then loop through it until user quits"""
        self.music.play()
        self.music.set_volume(0.01)
        while self.runGame:
            self.clock.tick(160)
            self.events()
            self.draw()


    def events(self):
        """Time to handle some events"""
        for e in pygame.event.get():
            if (e.type == pygame.QUIT) or (e.type == KEYDOWN and e.key == K_ESCAPE):
                self.runGame = False
                break
            if e.type == KEYDOWN and e.key == K_PRINT:
                self.screenShot()
            if e.type==KEYDOWN:    
                if e.key==pygame.K_a: self.kl.append(1)
                if e.key==pygame.K_d: self.kl.append(2)
                if e.key==pygame.K_w: self.kl.append(3)
                if e.key==pygame.K_s: self.kl.append(4)             
            if e.type==pygame.KEYUP:
                if e.key==pygame.K_a: self.kl.remove(1)            
                if e.key==pygame.K_d: self.kl.remove(2)
                if e.key==pygame.K_w: self.kl.remove(3)             
                if e.key==pygame.K_s: self.kl.remove(4)

            if   self.kl[-1:]==[1]: self.walk=[-self.speed, 0]
            elif self.kl[-1:]==[2]: self.walk=[ self.speed, 0]
            elif self.kl[-1:]==[3]: self.walk=[0,-self.speed]
            elif self.kl[-1:]==[4]: self.walk=[0, self.speed]
            else:                   self.walk=[0, 0]

        self.playerRec.move_ip(*self.walk)              # instead of self.x+=self.walk[0] / self.y+=self.walk[1]
        self.playerRec.clamp_ip(self.screen.get_rect()) # probably do this right after 'move_ip'


    def screenShot(self):
        """Lets make a folder if it doesnt exist for screenshots
        Then lets name teh screenshot something useful and unique"""
        if not os.path.exists('screenshots'):
            os.makedirs('screenshots')
        t = datetime.now()
        pygame.image.save(self.screen, ('screenshots/'+str(t.strftime("%a-%d-%b-%Y-%H.%M.%S_%f"))+'.png'))


    def idk(self):
        pygame.sprite.collide_rect(left, right)

    def draw(self):
        """Draw and update the main screen. Sacrifice virgins to the
        unholy prankster god of programming and cross fingers"""
        pygame.display.set_caption('Grid2. FPS: '+str(round(self.clock.get_fps(), 1)))
        back = self.screen.fill(Color('darkblue'))
        map.drawMapArray(map.readMap('kk.txt'))             
        link = self.screen.blit(self.playerSpr, self.playerRec) # 'blit' accepts a 'Rect' as second parameter
        bush = self.screen.blit(self.aSprite, self.aSpriteRec)
        d = link.colliderect(bush)
        print d  
        pygame.display.update()



class Map(Game()):
    """What we need to do here is go out and open a map file. 
    Read the file, and for each charactor load it onto the surface 
    in the right x/y coords. Should be easy. lulz"""
    def __init__(self, md='maps/'):
        self.md     = md
        self.tiles  = []
        #self.sprSz  = game.sprSz
        #self.multi  = game.multi
        #self.screen = game.screen

    def readMap(self, mapfile):
        """Lets open that map file up in a semi elegant way. Let
        us code cleanly and improve on simple things. """
        try:
            self.mpath  = os.path.join(self.md, mapfile)
            self.map    = open(self.mpath, 'r')
        except IOError, message:
            print "Unable to Map: " + self.md+mapfile
            raise SystemExit, message

        self.lines  = self.map.readlines()        
        self.Ty     = len(self.lines)
        self.Tx     = len(self.lines[0])-1
        self.map.close()

        for c in range(self.Ty):
            self.tiles.append([])
            for r in range(self.Tx):
                self.tiles[c].append(self.lines[c][r])                        
        return self.tiles


    def drawMapArray(self, map):
        for x in range(0, self.Tx):
            for y in range(0, self.Ty):
                #Determines tile type.
                curTile=tile_d[map[y][x]][3]
                #print x,y
                #print map
                #print curTile
                #if  tile_d[self.readMap[y][x]][2]>-1:
                    #game.screen.blit(curTile, (x*game.sprSz, y*game.sprSz+game.multi*56), (tile_d[self.readMap[y][x]][2]*resmulti*16, 0, 16*resmulti, 16*resmulti))
                #else:
                e = self.screen.blit(curTile, (x*self.sprSz, y*self.sprSz+self.multi*56))
                #print e


if __name__ == "__main__":
    game = Game()
    map = Map()   
    tile_d={
'#' : ('Link', True, 0, game.imgLoad("link1.png", game.multi, 0, 0)),
' ' : ('Link', True, 0, game.imgLoad("empty.png", game.multi, 0, 0)),
'Q' : ('Link', True, 0, game.imgLoad("link1.png", game.multi, 0, 0)),
'R' : ('Link', True, 0, game.imgLoad("empty.png", game.multi, 0, 0)),
'W' : ('Link', True, 0, game.imgLoad("link1.png", game.multi, 0, 0)),
'E' : ('Link', True, 0, game.imgLoad("empty.png", game.multi, 0, 0)),
'R' : ('Link', True, 0, game.imgLoad("link1.png", game.multi, 0, 0)),
'B' : ('Link', True, 0, game.imgLoad("empty.png", game.multi, 0, 0)),
'T' : ('Link', True, 0, game.imgLoad("link1.png", game.multi, 0, 0)),
'Y' : ('Link', True, 0, game.imgLoad("empty.png", game.multi, 0, 0)),
}
    game.mainLoop()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T05:08:56+00:00Added an answer on June 16, 2026 at 5:08 am

    You’re using Python’s syntax for class inheritance. Inheritance is used for ‘is a’ relationships, hypothetical classes like Sidescroller or FPS, because they are types of games.

    Map is not a type of game, it’s something in a game, so Game and Map have a ‘has a’ relationship. Your game has a map, like it has sprites and sounds. There is no special syntax for a ‘has a’ relationship. The parent class just creates an instance of the child class.

    Since you want access to Game‘s variables, you could pass its original instance to Map when you declare a map. If you declare Map within Game, you can pass the instance of game using self. Here is an example:

    # print the game's title via the Map class
    
    class Game:
    
        def __init__(self):
            self.title = "Robot Ninja Spaceman: Lazer Quest"
            self.map = Map(self)
    
    class Map:
    
        def __init__(self, game):
            print game.title
    
    if __name__ == "__main__":
        game = Game()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to render a haml file in a javascript response like so:
I am doing a simple coin flipping experiment for class that involves flipping a
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.