0

To practice object programming I decided to write small cRPG game and have a problem with optimizing movement.

Created an area where you can move between rooms, so for example from room 3 you are able only to go to room 2, 4, 6, 8 or from room 10 only to room 9.

The way I made it works and is maybe ok with several rooms, but if I'd want to expand it in future, it'll be just ugly and long:

self.territory.region1()
path = int(input("Which path you want to pick? "))
region = (2) # Numbers of regions you are able to go from current one
while path != 0:
    if region == 1:
        self.territory.region1()
        path = int(input("Which path you want to pick? "))
        if path == 1:
            region = 2
(...)
    elif region == 3:
        self.territory.region3()
        path = int(input("Which path you want to pick? "))
        if path == 1:
            region = 8
        elif path == 2:
            region = 4
        elif path == 3:
            region = 6                
        elif path == 4:
            region = 2
(...)
    elif region == 9:
        self.territory.region9()
        path = int(input("Which path you want to pick? "))
        if path == 1:
            region = 10
        elif path == 4:
            region = 8
    elif region == 10:
        self.territory.region10()
        path = int(input("Which path you want to pick? "))
        if path == 4:
            region = 9

Is there any simple way to make it shorter and better adjusted for adding regions?

Mr. Chris
  • 35
  • 5
  • 2
    Use a json/dict to configure your region and path, and use a function to parse and process it. Also, there is no idea w.r.t other functions you call – Kris May 05 '22 at 14:40

1 Answers1

1

You could use a dict to make this more expandable. A simple illustration of how you might use this:

regions = {
    1: {
        1: 2,
    },
    2: {
        1: 8,
        2: 4,
        3: 6,
        4: 2,
    },
    # ...
    9: {
        1: 10,
        4: 8,
    },
    # ...
}

region = 1
while True:
    print(f"You're in region {region}")
    path = int(input("What path? "))
    region = regions[region][path]
isaactfa
  • 5,461
  • 1
  • 10
  • 24
  • that's exactly a solution I was looking for, thank you :) – Mr. Chris May 05 '22 at 14:49
  • Glad it helped! You can accept the solution to mark this quesiton as resolved (and give me some sweet, sweet reputation ;)). – isaactfa May 05 '22 at 14:50
  • 1
    Solution accepted :) and tried to "thumb you up" even earlier, but need 15 rep to do it – Mr. Chris May 05 '22 at 14:54
  • 1
    This omits handling the `self.territory.region#()` call, but that should be fixable by getting rid of numbered methods in favor of passing the region number as an argument to a plain method named `region()`, e.g. `self.territory.region(region)`. – ShadowRanger May 05 '22 at 17:51