Skip to content

Instantly share code, notes, and snippets.

@rickardlindberg
Created August 24, 2023 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickardlindberg/fe4d2f14dbfc42b70c586bfaf27dbf91 to your computer and use it in GitHub Desktop.
Save rickardlindberg/fe4d2f14dbfc42b70c586bfaf27dbf91 to your computer and use it in GitHub Desktop.
import itertools
class World:
def __init__(self, interactions):
self.objects = []
self.interactions = interactions
def add(self, item):
self.objects.append(item)
def tick(self):
for a, b in itertools.combinations(self.objects, 2):
self.interactions.interact(world, a, b)
class GameObject:
def __init__(self, name):
self.name = name
class Player(GameObject):
pass
class Shot(GameObject):
pass
class Monster(GameObject):
pass
class Interactions:
def interact(self, world, a, b):
first, second = sorted([a, b], key=lambda x: x.__class__.__name__.lower())
name = f"{first.__class__.__name__.lower()}_{second.__class__.__name__.lower()}"
if hasattr(self, name):
getattr(self, name)(world, first, second)
else:
print(f"interaction {name} not defined")
def player_shot(self, world, player, shot):
print(f"player {player.name} vs shot {shot.name}")
def monster_player(self, world, monster, player):
print(f"monster {monster.name} vs player {player.name}")
if __name__ == "__main__":
world = World(Interactions())
world.add(Player("Mario"))
world.add(Shot("Ice Bullet"))
world.add(Monster("Bowser"))
world.tick()
@rickardlindberg
Copy link
Author

Prints this:

player Mario vs shot Ice Bullet
monster Bowser vs player Mario
interaction monster_shot not defined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment