Extending Robot Class - jetstreamc/PySimbot GitHub Wiki

The purpose of this example is for creating your own Robot class and override the robot's logic to reach the objective.

By running this example, the default simulation will be shown up with the robots of your implementations. The robots will move based on your logic.

By default, the robot will not have the logic of moving to the objective. You have to extend the Robot Class and override the update(self) method to implement your robot's logic.

To do this, you can follow the below code.

from pysimbotlib.core import PySimbotApp, Robot

class MyRobot(Robot):
    def update(self):
        distance = self.distance()
        if distance[0] < 10 or distance[1] < 10 or distance[-1] < 10:
            self.turn(-30)

        angle = self.smell()
        if angle < 0:
            self.turn(-2)
        elif angle > 0:
            self.turn(2)

        self.move(1)

MyRobot is the class that extends from pysimbotlib.core.Robot class. The logic of movement is wrapped in the update(self) method. The sensor values are retrieved by the instance's methods: self.distance() and self.smell(). The robot then checks for three distance sensors at front, front-right, and front-left of the robot as well as the smell sensor. The robot actions such as self.turn() and self.move() are performed based on these sensor values.

Based on MyRobot class, PySimbot can create the robot by your robot class. To do this, pass the MyRobot class to the PySimbotApp constructor.

if __name__ == '__main__':
    app = PySimbotApp(robot_cls=MyRobot)
    app.run()

Combining all the code fragments, you will get

from pysimbotlib.core import PySimbotApp, Robot

class MyRobot(Robot):
    def update(self):
        distance = self.distance()
        if distance[0] < 10 or distance[1] < 10 or distance[-1] < 10:
            self.turn(-30)

        angle = self.smell()
        if angle < 0:
            self.turn(-2)
        elif angle > 0:
            self.turn(2)

        self.move(1)

if __name__ == '__main__':
    app = PySimbotApp(robot_cls=MyRobot)
    app.run()

You may save & run the given code and see the result. In case that you save as main.py, you can run by enter the command

python main.py

There are many examples that extend the Robot class such as example 2, 3, 4, 5, 6, 10, 11, and 12. Let's try running them.