from myro import * __AUTHOR__ = "Lisa Meeden" __VERSION__ = "1.0.0" class Game: """ A simple example of using a game pad to create a video game. This is a one-sided Pong-like game where the user controls a racquet by moving it vertically to contact a ball that is bouncing against the walls. If the ball gets beyond the racquet the game ends. """ def __init__(self): """ Initializes the graphics window, draws the racquet, draws the ball, and randomly determines the balls motion. """ self.w = GraphWin("Game", 400, 300) self.ball = Circle(Point(150,150), 15) self.ball.setFill("red") self.ball.draw(self.w) self.ballDx = (pickOne(25) + 150) / 100.0 self.ballDy = (pickOne(25) + 150) / 100.0 self.racquet = Rectangle(Point(370,100), Point(380,150)) self.racquet.setFill("black") self.racquet.draw(self.w) self.hits = 0 self.level = 0 def checkRacquet(self): """ Checks if the ball is contacting the racquet. If so, it moves the ball in the opposite direction until the ball is no longer touching the racquet. Every 5 times the ball is hit, increase the ball's speed slightly. """ ballPos = self.ball.getCenter() ballRad = self.ball.getRadius() racquetP1 = self.racquet.getP1() racquetP2 = self.racquet.getP2() ballRightEdge = ballPos.getX() + ballRad if racquetP1.getX() <= ballRightEdge <= racquetP2.getX(): if racquetP1.getY()-ballRad<=ballPos.getY()<=racquetP2.getY()+ballRad: self.hits += 1 self.ballDx *= -1 while self.ball.getCenter().getX() + ballRad >= racquetP1.getX(): self.ball.move(self.ballDx, self.ballDy) if self.hits % 5 == 0: self.ballDx *= 1.1 self.ballDy *= 1.1 self.level += 1 print "Level:", self.level def checkWalls(self): """ Checks if the ball is contacting a wall. If so, it moves the ball in the opposite direction. """ ballPos = self.ball.getCenter() ballRad = self.ball.getRadius() if ballPos.getY() - ballRad <= 0 or \ ballPos.getY() + ballRad >= self.w.getHeight(): self.ballDy *= -1 if ballPos.getX() - ballRad <= 0: self.ballDx *= -1 self.ball.move(self.ballDx, self.ballDy) def racquetAtBottom(self): """ Checks if the racquet is at the bottom of the window. """ return self.racquet.getP2().getY() >= self.w.getHeight() def racquetAtTop(self): """ Checks if the racquet is at the top of the window. """ return self.racquet.getP1().getY() <= 0 def gameOver(self): """ Checks if the ball has passed to the right of the racquet. """ return self.ball.getCenter().getX() > self.racquet.getP2().getX() def play(self): """ As long as the ball is still to the left of the racquet, allow the user to move the racquet, then update the balls position. """ while not self.gameOver(): racquetDx, racquetDy = getGamepadNow("axis") if self.racquetAtBottom() and racquetDy > 0: pass elif self.racquetAtTop() and racquetDy < 0: pass else: self.racquet.move(0, racquetDy * 5) self.checkWalls() self.checkRacquet() wait(0.01) self.w.close() print "You hit the ball", self.hits, "times." if __name__ == '__main__': g = Game() g.play()