6.3 BallBox using button to control ball movement

We open (6.2) the completed BallBox.py and add the detection code for the push button input.

  • We use the query method to handle push button input
  • Exit the BallBox application with the button combination JOY_UP + SW_A
  • JOY_UP, JOY_DOWN, JOY_LEFT, JOY_RIGHT control the upper, lower, left and right movements of the ball respectively

The new code as follows:

from JMRPiFoundations.Skeleton.RPiSparkModule import RPiSparkModule
from Ball import Ball

class BallBox(RPiSparkModule):
    ball = None
    velocity = None

    def setup(self):
        self.velocity = 3
        self.ball = Ball(64, 32, 5)
        # setup all key buttons to query mode

    def run(self):

        while True:

            # Check exit key status ( JOY_UP + SW_A )
            if self.readExitButtonStatus():

            # Move the ball up
            if self.readKeyButton(self.RPiSparkConfig.BUTTON_JOY_UP):
                self.ball.move(0, -self.velocity)

            # Move the ball down
            if self.readKeyButton(self.RPiSparkConfig.BUTTON_JOY_DOWN):
                self.ball.move(0, self.velocity)

            # Move the ball left
            if self.readKeyButton(self.RPiSparkConfig.BUTTON_JOY_LEFT):
                self.ball.move(-self.velocity, 0)

            # Move the ball right
            if self.readKeyButton(self.RPiSparkConfig.BUTTON_JOY_RIGHT):
                self.ball.move(self.velocity, 0)

            # Drawing the ball on the screen
            self.RPiSpark.Screen.Canvas.ellipse( self.ball.getXY(), 1, 1 )

        print("BallBox is done.")

Type command in the terminal:

$> rspk BallBox -f

At this time you should be able to see a white solid circle appearing in the center of the OLED screen (we use a solid circle to represent the ball), and you can control the movement of the ball up, down, left, and right by the Joystick.


Was this article helpful?

YES     |     NO


Enjoying the project? Spotted a mistake? Any opinions on the website? Let us know!