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?
>Solution :
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]