Python Forum
Using classes for room movement (text game)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using classes for room movement (text game)
#3
Alright, so let me restructure your question, to make sure I understand it right.

Given this code:
class Room:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.loc = (x, y)

room_1 = Room(0, 0)
print(room_1.loc)
room_1.y += 1
print(room_1.loc)
...why is the same tuple printed twice? Or, why didn't the change to the y variable also change the loc variable?

The loc variable is created with copies of the x/y variables, not references to them. So changes to the x/y variables will not effect the loc.

The easy way to fix this, is to use a method to return the current location:
    def get_loc(self):
        return (self.x, self.y)
The other option would be to use objects to store positioning, instead of primitive types (like an int). That would look something like this:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_loc(self):
        return (self.x, self.y)

    def __str__(self):
        return "Point: ({0}, {1})".format(self.x, self.y)

class Room:
    def __init__(self, x, y):
        self.loc = Point(x, y)

room_1 = Room(0, 0)
print(room_1.loc)
room_1.loc.y += 1
print(room_1.loc)
Reply


Messages In This Thread
RE: Using classes for room movement (text game) - by nilamo - Aug-19-2019, 07:02 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Laggy Game Movement game_slayer_99 12 4,726 Oct-05-2022, 11:34 AM
Last Post: metulburr
  [PyGame] Particle movement mystery XavierPlatinum 10 3,227 Jul-09-2022, 04:28 AM
Last Post: deanhystad
  [PyGame] Isometric Movement on Tiled Map Josselin 0 2,456 Nov-02-2021, 06:56 AM
Last Post: Josselin
  [PyGame] object's movement to left leave shadow on the screen Zhaleh 3 3,267 Aug-02-2020, 09:59 PM
Last Post: nilamo
  Adding an inventory and a combat system to a text based adventure game detkitten 2 7,046 Dec-17-2019, 03:40 AM
Last Post: detkitten
  Problem with coding for movement keys Aresofthesea 3 3,551 Jul-05-2019, 07:05 PM
Last Post: nilamo
  Pygame Movement X/Y coord TheHumbleIdiot 2 3,586 Mar-19-2019, 02:21 PM
Last Post: TheHumbleIdiot
  Movement after KEYUP, only after pause func esteel 2 3,366 Aug-22-2018, 03:03 PM
Last Post: Windspar
  Text Based Game DuaneJack 3 3,629 Aug-15-2018, 12:02 PM
Last Post: ichabod801
  [PyGame] How to stop the sprite's movement when it touches the edges of the screen? mrmn 5 11,839 May-13-2018, 06:33 PM
Last Post: mrmn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020