def main(): start_time = time.time() ## Graphics class screen = Screen(constants.WIDTH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT / 2 - 1, constants.BLACK) player2 = Paddle(screen, constants.WIDTH - 4, constants.HEIGHT / 2 - 1, constants.BLACK) net = Net(screen, constants.BLACK) ball = Ball(screen, 0, 0, constants.BALL_COLOUR) # Dummy values ball.velocity = [8.0, 8.0] #Roughly 10 seconds to cross screen? ball._served = True while (True): end_time = time.time() frame_time = end_time - start_time start_time = end_time player1.update(frame_time) player2.update(frame_time) ball.update(frame_time) player1.draw() player2.draw() ball.draw() net.draw() screen.draw_num(*constants.SCORE1, score1, constants.SCORE_COLOUR) screen.draw_num(*constants.SCORE2, score2, constants.SCORE_COLOUR)
def main(): os.environ["SDL_VIDEO_WINDOW_POS"] = "15,30" pygame.display.init() size = 900, 600 screen = pygame.display.set_mode(size) ball = Ball(screen, (size[0] / 2, size[1] / 4 * 3), (1, 1)) ball.randomvel(3) grid = Grid(screen, size) paddle = Paddle(screen, size, (size[0] / 2, size[1] / 10 * 9)) running = True pygame.key.set_repeat(40) while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: paddle.move(-15) elif event.key == pygame.K_RIGHT: paddle.move(15) screen.fill((0, 0, 0)) grid.draw() ball.update() if not ball.collide(size, grid, paddle): running = False ball.draw() paddle.update() paddle.draw() pygame.display.update()
def main(): ## Graphics class screen = Screen(constants.WDITH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT / 2 - 1, constants.BLUE) player2 = Paddle(screen, constants.WDITH - 4, constants.HEIGHT / 2 - 1, constants.BLUE) net = Net(screen, constants.BLACK) sceen.clear() player1.draw() player2.draw() net.draw()
class Pong(arcade.Window): ''' Classic pong arcade game but with only one player. Focuses on keeping the ball on the right side. ''' ball: Ball paddle: Paddle score: int holding_up: bool holding_down: bool def __init__(self, width, height): ''' Init function begins the frame window and sets up the default values Parameters ---------- None Returns ------- None ''' super().__init__(width, height) self.ball = Ball() self.paddle = Paddle() self.score = 0 self.holding_up = False self.holding_down = False arcade.set_background_color(arcade.color.BLACK) def on_draw(self): ''' Function called automatically by the framework to render the game. Parameters ---------- None Returns ------- None ''' arcade.start_render() self.ball.draw() self.paddle.draw() self.draw_score() self.draw_ball_position() self.draw_paddle_position() def draw_score(self): ''' Draws the score of the player on the top left corner of the window. Parameters ---------- None Returns ------- None ''' score_text = f"Score: {self.score}" x: int = 10 y: int = 280 arcade.draw_text( text=score_text, start_x=x, start_y=y, font_size=12, color=arcade.color.GREEN ) def draw_ball_position(self): ''' Draws the position of the ball on the top right of the screen Parameters ---------- None Returns ------- None ''' x: int = self.ball.center.x y: int = self.ball.center.y text: str = f"Ball [X: {x} Y: {y}]" arcade.draw_text( text=text, start_x=280, start_y=280, font_size=12, color=arcade.color.GREEN ) def draw_paddle_position(self): ''' Draws the position of the paddle on the bottom right of the screen Parameters ---------- None Returns ------- None ''' x: int = self.paddle.center.x y: int = self.paddle.center.y text: str = f"Paddle [X: {x} Y: {y}]" arcade.draw_text( text=text, start_x=270, start_y=10, font_size=12, color=arcade.color.GREEN ) def update(self, delta_time): ''' Updates the screen based on the new values Parameters ---------- None Returns ------- None ''' self.ball.advance() self.check_keys() self.check_miss() self.check_hit() self.check_bounce() def check_bounce(self): ''' Checks to see if the ball is within the boundaries that it needs. If the ball is too close to the right or left side then it will reverse the delta_x of the ball. If the ball is too far up or down then it will reverse the delta_y of the ball. Parameters ---------- None Returns ------- None ''' if self.ball.center.x < 0: self.ball.bounce_horizontal() if self.ball.center.x > 400: self.ball.bounce_horizontal() if self.ball.center.y < 0: self.ball.bounce_vertical() if self.ball.center.y > 300: self.ball.bounce_vertical() def check_miss(self): ''' Checks to see if the ball has gone too far to the left, meaning that the player missed the ball. Parameters ---------- None Returns ------- None ''' if self.ball.center.x < 0: self.score -= SCORE_MISS self.ball.restart() def check_hit(self): ''' Check to see if the ball has hit the paddle on the x or y plane of the paddle. If it hits, it will increment the velocity by 1 and increase the score. Parameters ---------- None Returns ------- None ''' too_close_x: int = (PADDLE_WIDTH / 2) + BALL_RADIUS too_close_y: int = (PADDLE_HEIGHT / 2) + BALL_RADIUS ball_x: int = self.ball.center.x ball_y: int = self.ball.center.y paddle_x: int = self.paddle.center.x paddle_y: int = self.paddle.center.y if (abs(ball_x - paddle_x) < too_close_x and abs(ball_y - paddle_y) < too_close_y): self.ball.bounce_horizontal() self.score += SCORE_HIT self.ball.velocity.dx += 1 self.ball.velocity.dy += 1 def check_keys(self): ''' Checks if the up or down keys are being held down. If they are being held down, then move the paddle until it cannot move any further. Parameters ---------- None Returns ------- None ''' paddle_y: int = self.paddle.center.y upper_edge: int = SCREEN_HEIGHT - (PADDLE_HEIGHT / 2) - 5 if self.holding_up and paddle_y < upper_edge: self.paddle.move_up() if self.holding_down and paddle_y > 30: self.paddle.move_down() def on_key_press(self, key, key_modifers): ''' Detects if the key is being pressed, updates values accordingly. Parameters ---------- None Returns ------- None ''' if key == arcade.key.UP or key == arcade.key.W: self.holding_up = True if key == arcade.key.DOWN or key == arcade.key.S: self.holding_down = True def on_key_release(self, key, key_modifers): ''' Checks to see if the key has been released, and if it has then it will disengage the button. Parameters ---------- None Returns ------- None ''' if key == arcade.key.UP or key == arcade.key.W: self.holding_up = False if key == arcade.key.DOWN or key == arcade.key.S: self.holding_down = False
# If the ball is off the map, send it back down. if ball.y <= 0: ball.bounce(DIRECTION_DOWN) # Check if we are off the screen elif ball.y >= SCREEN_HEIGHT: # We need to take damage, and reset the ball player.takeLife() ball.reset() # Check to see if the ball is hitting the paddle elif ball.y + ball.radius >= paddle.y: # If so, then check to see if the x of the ball is within in the x_width of the paddle if ball.x > paddle.x and ball.x < paddle.x + paddle.width: # it is, so we need to reverse the course of the ball. ball.bounce(DIRECTION_UP) if tiles.hasBallHitTile(ball): ball.bounce(DIRECTION_DOWN) player.addScore(1) paddle.draw() ball.move(time_delta) ball.draw() tiles.draw(screen) player.displayScore() pygame.display.update()
def main(): score1 = 0 score2 = 0 server = 1 start_time = time.time() ## Graphics class screen = Screen(constants.WIDTH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT / 2 - 1, constants.PADDLE_COLOUR) player2 = Paddle(screen, constants.WIDTH - 4, constants.HEIGHT / 2 - 1, constants.PADDLE_COLOUR) net = Net(screen, constants.NET_COLOUR) ball = Ball(screen, 5, 20, constants.BALL_COLOUR) led = Led(5) net.draw() screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) # Dummy values ball.velocity = [10.0, 10.0] #Roughly 8 seconds to cross screen? while (True): end_time = time.time() frame_time = end_time - start_time start_time = end_time value1 = read_i2c(CHAN2) print(value1) value2 = read_i2c(CHAN3) if (GPIO.input(10) == 1): ball.served = True if (GPIO.input(9) == 1): player1.power_up() if (GPIO.input(17) == 0): ball.served = True if (GPIO.input(11) == 0): player2.power_up() # Lose condition if (ball.x >= screen.width - 1): score1 += 1 ball.served = False ball.x = player2.x - 1 ball.y = player2.y + player2.size[1] / 2 server = 2 screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) if (ball.x <= 1): score2 += 1 ball.served = False ball.x = player1.x + 1 ball.y = player1.y + player1.size[1] / 2 server = 1 screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) score1 %= 10 score2 %= 10 # TODO: Reduce noise; multiple reads before move? player1.move(value1) player2.move(value2) player1.update(frame_time) player2.update(frame_time) if (not ball.served): if (server == 1): ball.last_pos = [ball.roundx, ball.roundy] ball.y = player1.y + player1.size[1] / 2 ball.x = player1.x + 1 ball.roundx = int(round(ball.x)) ball.roundy = int(round(ball.y)) if (ball.last_pos != [ball.roundx, ball.roundy]): ball._moved = True if (server == 2): ball.last_pos = [ball.roundx, ball.roundy] ball.y = player2.y + player2.size[1] / 2 ball.x = player2.x - 1 ball.roundx = int(round(ball.x)) ball.roundy = int(round(ball.y)) if (ball.last_pos != [ball.roundx, ball.roundy]): ball._moved = True # Collision Detection if (ball.roundx == player1.x): rx = random.randint(5, 15) ry = random.randint(5, 15) if (ball.roundy >= player1.y and ball.roundy <= player1.y + player1.size[1] / 3): ball.velocity[1] = -ry ball.velocity[0] = rx if (ball.roundy >= player1.y + player1.size[1] / 3 and ball.roundy <= player1.y + player1.size[1] / 3 * 2): ball.velocity[1] = 0 ball.velocity[0] = rx if (ball.roundy >= player1.y + player1.size[1] / 3 * 2 and ball.roundy <= player1.y + player1.size[1]): ball.velocity[1] = ry ball.velocity[0] = rx if (ball.roundx == player2.x): rx = random.randint(5, 15) ry = random.randint(5, 15) if (ball.roundy >= player2.y and ball.roundy <= player2.y + player2.size[1] / 3): ball.velocity[1] = -ry ball.velocity[0] = -rx if (ball.roundy >= player2.y + player2.size[1] / 3 and ball.roundy <= player2.y + player2.size[1] / 3 * 2): ball.velocity[1] = 0 ball.velocity[0] = -rx if (ball.roundy >= player2.y + player2.size[1] / 3 * 2 and ball.roundy <= player2.y + player2.size[1]): ball.velocity[1] = ry ball.velocity[0] = -rx ball.update(frame_time) led.update(ball.x) player1.draw() player2.draw() ball.draw() net.spot_draw(ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1])
def main(): #initialize all imported pygame modules pygame.init() #create the main screen screen = Screen('Break it!', 'img/star.png', 'img/outerspace.png', 600, 600, Colors.WHITE) score = Score(450, 25, Colors.FIREBRICK, 1, "sounds/BonusChime.ogg", screen.Surface) #create a lives object' lives = Lives(50, 25, 3, "img/heart3.png", screen.Surface) level = Level(230, 25, Colors.AQUAMARINE, 40, screen.Surface) #create a ball object paddle = Paddle(160, 30, Colors.DEEPSKYBLUE, "sounds/beep4.ogg", screen.Surface) ball = Ball(40, 0, 0, 600, 600, "img/earth-icon.png", "sounds/BonusSymbol.ogg", screen.Surface) #list of colors for brick colors = [Colors.RED, Colors.BLUE, Colors.GREEN, Colors.YELLOW] values = [100, 75, 50, 25] #create bricks bricks = Brick.createBricks(17, 100, 4, 10, 2, colors, values, 55, 20, screen.Surface) #rate to increase speed speedLevel = 15 #initialize clock clock = pygame.time.Clock() #indicates if the game is paused paused = False #set the variable that controls the main game loop playing = True while playing: #maintain a frame rate of 100 fps clock.tick(100) #the events since last time for event in pygame.event.get(): #if the user clicks exit stop playing if event.type == QUIT: playing = False if event.type == KEYDOWN: if event.key == K_q: playing = False if event.key == K_p: paused = not paused if event.key == K_LEFT: #move left paddle.setMoveLeft() #move right if event.key == K_RIGHT: paddle.setMoveRight() if event.type == KEYUP: if event.key == K_LEFT or event.key == K_RIGHT: paddle.stop() #move and draw only if the pause feature is off if not paused: #update and move things ball.move() paddle.move() #check for paddle hit if ball.checkCollision(paddle.rect): paddle.playSound() score.addScore(100) #if ball leaves screen if ball.lost(): ball.reset() lives.subtractLives(1) if lives.getLives() == 0: if screen.restartPrompt("img/GameOver4.png"): lives.reset() score.resetScore() #loop through all the bricks for brick in bricks: #is there a collision? if (brick.checkBallCollision(ball)): if score.addScore(brick.value): lives.addLives(0) if brick.gone: bricks.remove(brick) if level.addPartialLevel(1): bricks = Brick.createBricks(17, 100, 4, 10, 2, colors, values, 55, 20, screen.Surface) ball.reset() #draw things #draw screen first so it does nor overwrite other objects #screen.draw screen.draw() score.draw() lives.draw() level.draw() paddle.draw() ball.draw() #loops through all the bricks for brick in bricks: brick.draw() #update the changes to show on the main screen pygame.display.update() #Uninialize all pygame modules that have previously beeen inialized pygame.quit()
def main(): #initialize all imported pygame modules pygame.init() #create the main screen screen = Screen('Break IT', 'img/star.png', 'img/outerspace.png',600, 600,Colors.WHITE) #Create a score object score = Score(450, 25,Colors.GOLD , 2500, "sounds/BonusChime.ogg", screen.surface) #Create a lives object lives = Lives(50, 25, 3,"img/heart3.png", screen.surface) #Create a level object level = Level(230, 25,Colors.GOLD, 40, screen.surface) #Create a paddle object paddle = Paddle(80, 20, Colors.AQUAMARINE, "sounds/beep1.ogg", screen.surface) #Create Ball here ball = Ball(40, 0, 0, 600, 600,"img/star.png", "sounds/beep4.ogg", screen.surface) #Initialize clock clock = pygame.time.Clock() #indicates if the game is paused paused = False #set the variable that controls the main game loop playing = True #start the game loop while playing: #maintain a frame rate of 100 fps clock.tick(100) #get all the events since last time #the events were checked for event in pygame.event.get(): #if the user click exit stop playing if event.type == QUIT: playing = False #if this is a keydown (pressing down of a key) if event.type == KEYDOWN: if event.key == K_q: playing = False #switch the pause feature on or off if event.key == K_ESCAPE: paused = not paused #set the paddle to move to the left if event.key == K_LEFT: paddle.setMoveLeft() #set the paddle to move to the right if event.key == K_RIGHT: paddle.setMoveRight() #if this is a keyup (the player release #the key so it is no longer down) if event.type == KEYUP: #since the player released the key #the paddle should be stationary if event.key == K_LEFT or event.key == K_RIGHT: paddle.stop() #move and draw only #if pause feature off if not paused: #update and move things ball.move() paddle.move() #Check for paddle hit if ball.checkCollision(paddle.rect): paddle.playSound() score.addScore(10) #if the ball leaves the screen if ball.lost(): ball.reset() lives.subtractLives(1) if lives.getLives() == 0: #we are out of lives check for restart if screen.restartPrompt("img/GameOver4.png"): lives.reset() score.reset() else: playing = False #draw things #draw screen first so it does not #overwrite other objects screen.draw() score.draw() lives.draw() level.draw() ball.draw() paddle.draw() #update the changes to #show on the main screen pygame.display.update() #Uninitialized all pygame modules that #have previously been initialized pygame.quit()
class Game: def __init__(self) -> None: self.inputHandler = InputHandler() self.board = Board(size=Vector2(BOARD_WIDTH, BOARD_HEIGHT)) self.brickHandler = BrickHandler(self.board) self.paddle = None self.balls = [] self.powerUps = [] self.activePowerUps = [] self.score = 0 self.lives = 5 self.isRunning = True def start(self) -> None: self.score = 0 self.balls = [] self.powerUps = [] self.paddle = Paddle(Vector2(BOARD_WIDTH // 2, BOARD_HEIGHT - 3), 10) self.balls.append( Ball(Vector2(BOARD_WIDTH // 2 + 1, BOARD_HEIGHT - 4), Vector2(-1, 1))) self.brickHandler = BrickHandler(self.board) def over(self) -> None: print('{:<80}'.format("GAME OVER !")) self.inputHandler.exit() print("\x1b[?25h") self.isRunning = False def getState(self) -> tuple: return (self.score, self.lives, self.powerUps) def update(self) -> None: bs = self.brickHandler.getBricks() for power in self.powerUps: power.update(self.paddle, self.balls) for ball in self.balls: ball.move(bs, self.paddle) for bk in bs: if not bk.active: if randint(0, 5) == 1: self.powerUps.append( spawnRandom((bk.position + bk.size / 2))) self.balls = [bl for bl in self.balls if bl.active] self.score += self.brickHandler.update() self.powerUps = [power for power in self.powerUps if power.active] if (len(self.balls) <= 0): self.lives -= 1 if self.lives < 1: self.over() else: self.start() if (len(bs) <= 0): self.over() if self.inputHandler.getKey('q'): self.over() elif self.inputHandler.getKey('a'): self.paddle.move(Vector2(-2, 0), self.balls) elif self.inputHandler.getKey('d'): self.paddle.move(Vector2(2, 0), self.balls) elif self.inputHandler.getKey(' '): self.paddle.release(self.balls) elif self.inputHandler.getKey('x'): self.over() def render(self) -> None: self.board.refresh() self.brickHandler.draw(self.board) waste = [power.draw(self.board) for power in self.powerUps] self.paddle.draw(self.board) waste = [ball.draw(self.board, ball.dir) for ball in self.balls] self.board.print() # print(self.brickHandler.gridSize, self.score, self.lives) def clearWithHUD(self) -> None: print("\033[F" * (BOARD_HEIGHT + 4)) def clearWithoutHUD(self) -> None: print("\033[F" * (BOARD_HEIGHT + 2))
paddle = Paddle(canvas, 'blue') # Creates an object named 'ball' of the Ball class that we created in Ball.py ball = Ball(canvas, paddle, 'red') current_score = 0 # Creates the label for the score score = Tkinter.Label(canvas, text= ball.score()) # Displays that window canvas.create_window(10, 20, window=score, anchor='w') # Tells the canvas to not loop through the listed command until the user close the window while 1: # Calls the draw function on the ball as long as hit_bottom is False ball.draw() # Calls the draw function on the paddle as long as hit_bottom is False paddle.draw() # Updates the score score['text'] = (ball.score()) # Both of these update the canvas top.update_idletasks() top.update() #Tells the loop to sleep for 1/100th of a second before looping again time.sleep(0.01)
class BreakoutGame: def setup(self, startWindow=None, playerName=None): self.params = GameParams() # To be filled by user input # Set up scorekeeping self.score = 0 self.scoreKeeper = ScoreKeeper() self.scoreKeeper.setFile('breakoutScore.txt') # Set up window width = 800 height = 600 font = sf.Font.from_file("rust.ttf") self.params.setFont(font) if startWindow is None: # startWindow is None unless this is a restart startWindow = sf.RenderWindow(sf.VideoMode(width, height), "Breakout") startWindow.framerate_limit = 60 startWindow.clear(sf.Color.BLACK) #Display Welcome welcomeText = utils.drawText(startWindow, string="Breakout", size=60, font=font, position='center') startWindow.display() # Wait for any input while (True): setup = False for event in startWindow.events: if type(event) is sf.CloseEvent: exit() elif (type(event) is sf.MouseButtonEvent or type(event) is sf.KeyEvent): setup = True if setup: break # Select Player Name if playerName is None: playerName = utils.textInput(startWindow, "Enter Name:", font, maxLength=10) self.params.setPlayerName(playerName.lower()) #Choose Difficulty #difficulty = utils.selectOptions(startWindow, ["Easy", "Medium", "Hard"], [0, 1, 2], font) #self.params.setDifficulty(difficulty) # Set up Board self.board = Board(title="Breakout", width=1000, height=500) # Set up Paddle self.paddle = Paddle(boundary=self.board.getBoundary(), width=75, height=15) self.paddle.setMoveSpeed(10) # Gameplay parameters self.maxLayers = 5 self.level = 1 startWindow.close() def endGame(self): gameOverText = utils.drawText(self.board.window, string="Game Over", font=self.params.font, size=60, position='center', color=sf.Color.RED) oldScore = self.scoreKeeper.checkScore(self.params.playerName, self.params.getDifficulty()) scoreTextYPosition = gameOverText.position[ 1] + gameOverText.local_bounds.height + 10 if self.score > oldScore: # display a "New Highscore" screen self.scoreKeeper.setScore(self.params.playerName, self.score, self.params.getDifficulty()) utils.drawText(self.board.window, string="New High Score! {}".format(self.score), font=self.params.font, size=30, position='center', yposition=scoreTextYPosition, color=sf.Color.GREEN) else: # Display the old highscore utils.drawText(self.board.window, string="High Score: {}".format(oldScore), font=self.params.font, size=30, position='center', yposition=scoreTextYPosition, color=sf.Color.WHITE) utils.drawText(self.board.window, string="Press ENTER to Relplay", font=self.params.font, size=15, position='center', yposition=self.board.window.height - 20, color=sf.Color.WHITE) self.board.window.display() while (True): for event in self.board.window.events: if (type(event) is sf.CloseEvent or (type(event) is sf.KeyEvent and event.code is sf.Keyboard.ESCAPE)): exit() if (type(event) is sf.KeyEvent and event.code is sf.Keyboard.RETURN): # Reset self.board.window.clear(sf.Color.BLACK) self.setup(self.board.window, self.params.getPlayerName()) self.playGame() def playLevel(self, level): self.board.window.clear(sf.Color.BLACK) self.paddle.draw(self.board.window) self.board.displayBoard() play = False while not play: for event in self.board.window.events: if type(event) is sf.CloseEvent: exit() elif (type(event) is sf.KeyEvent): play = True ballManager = ObjectManager(cleanSize=10) screenWidth = self.board.getBoundary()[0] screenHeight = self.board.getBoundary()[1] # Calculate BrickWall difficulty parameters wallDepth = min(self.maxLayers, self.level) wallLength = 10 + 2 * (self.level // 5 ) # increase by 2 width every 5 levels boundary = ((0, 25), (screenWidth, 25 + min(20 * wallDepth, screenHeight / 3))) brickWall = BrickWall(boundary=boundary) brickWall.setWallDepth(wallDepth) brickWall.setWallWidth(wallLength) if self.level < self.maxLayers: # Set all bricks health = 1 brickWall.setAllLayerHealth(1) else: minHealth = 1 + (self.level // 3) maxHealth = self.maxLayers + (self.level // 3) brickWall.setLayerHealthGradient(minHealth, maxHealth) brickWall.createBricks() ballSpeed = 4.5 + 0.2 * self.level ball = Ball(position=(100, screenHeight / 2), speed=ballSpeed, direction=45) ballManager.addObject(ball) while (True): self.board.window.clear(sf.Color.BLACK) # Input handler for event in self.board.window.events: if type(event) is sf.CloseEvent: exit() if type(event) is sf.KeyEvent and event.pressed and ( event.code is sf.Keyboard.RETURN): self.level += 1 self.playLevel(self.level) if sf.Keyboard.is_key_pressed(sf.Keyboard.RIGHT): self.paddle.moveRight() if sf.Keyboard.is_key_pressed(sf.Keyboard.LEFT): self.paddle.moveLeft() # Move and draw balls for i in range(ballManager.getLength()): ball = ballManager.getItem(i) ball.move() ball.draw(self.board.window) # Draw bricks brickWall.drawBricks(self.board.window) # Draw Paddle self.paddle.draw(self.board.window) # Check for Ball-Brick Collisions for i in range(ballManager.getLength()): ball = ballManager.getItem(i) brick = brickWall.checkCollision(ball) if brick: ball.rectangleBounce(brick.getShape()) if (brick.getHealth() == 0): self.score += 1 # Check for Ball Collisions for i in range(ballManager.getLength()): ball = ballManager.getItem(i) position = ball.getPosition() size = ball.getSize() if self.paddle.didCollide(ball): ball.rectangleBounce(self.paddle.getShape()) # Check for Ball-Wall Collision if (position[0] <= 0 or position[0] + size[0] >= self.board.getBoundary()[0]): ball.bounceHorizontal() if (position[1] <= 0): ball.bounceVertical() # Remove Dead Balls deadBalls = [] if (position[1] >= self.board.getBoundary()[1]): deadBalls.append(i) ballManager.removeItems(deadBalls) # Check if any balls left if ballManager.getLength() == 0: self.endGame() # Check if any bricks left if brickWall.getNumBricks() == 0: self.level += 1 self.playLevel(self.level) self._drawScore(self.board.window) self.board.window.display() def playGame(self): self.playLevel(self.level) def _drawScore(self, window): if hasattr(self, 'scoreText'): self.scoreText.string = str(self.score) else: self.scoreText = utils.drawText(window, size=25, font=self.params.font, string=str(self.score)) window.draw(self.scoreText)
def main(): score1 = 0 score2 = 0 start_time = time.time() bus = smbus.SMBus(1) ## Graphics class screen = Screen(constants.WIDTH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT/2-1, constants.BLACK) player2 = Paddle(screen, constants.WIDTH-4, constants.HEIGHT/2-1, constants.BLACK) net = Net(screen, constants.BLACK) ball = Ball(screen, 5, 20, constants.BALL_COLOUR) # Dummy values ball.velocity = [10.0,10.0] #Roughly 10 seconds to cross screen? ball._served = True while (True): end_time = time.time() frame_time = end_time - start_time start_time = end_time bus.write_byte( I2CADDR, 0x10 ) tmp1 = bus.read_word_data( I2CADDR, 0x00 ) tmp1 = ((tmp1 & 0xff00) >> 8) | ((tmp1 & 0x00ff) << 8) tmp1 = tmp1 & 0x0fff value1 = tmp1>>2 bus.write_byte( I2CADDR, 0x80 ) tmp2 = bus.read_word_data( I2CADDR, 0x00 ) tmp2 = ((tmp2 & 0xff00) >> 8) | ((tmp2 & 0x00ff) << 8) tmp2 = tmp2 & 0x0fff value2 = tmp2>>2 if (ball.x >= screen.width): score1 += 1 if (ball.x <= 0): score2 += 1 if (score1 > 9): score1 = 0 if (score2 > 9): score2 = 0 player1.move(value1) player2.move(value2) player1.update(frame_time) player2.update(frame_time) if (int(round(ball.x)) == int(round(player1.x))+1): if (int(round(ball.y)) >= int(round(player1.y)) and int(round(ball.y)) <= int(round(player1.y)) + 2): ball.velocity[0] *= -1 if (int(round(ball.x)) == int(round(player2.x))-1): if (int(round(ball.y)) >= int(round(player2.y)) and int(round(ball.y)) <= int(round(player2.y)) + 2): ball.velocity[0] *= -1 ball.update(frame_time) player1.draw() player2.draw() ball.draw() ''' net.draw() screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) ''' time.sleep(0.01)
#this appends to the created bricklist-which is then turned black in the brick_obj.update_bricks() function print(brick, ball_obj.ball) game_brick_list.append(brick) # print(len(game_brick_list)) brick_obj.brick_list.remove(brick) #------------------------------------------------------------------- #--Loop will run forever unless disrupted while True: event_handler() game_display.fill(Config['colors']['black']) #--Deals with paddle paddle_obj.draw() paddle_obj.movement(x_change) #--------------------------------------------------------------------- #--Deals with bricks brick_obj.create_bricks() brick_obj.update_bricks(game_brick_list) #------------------------------------------------------------------------ #--Deals with the ball ball_obj.draw() #--Updating the display with the ball pygame.display.update() clock.tick(Config['game']['fps'])
from Screen import Screen from Paddle import Paddle from Net import Net import constants import time ## Graphics class screen = Screen(constants.WIDTH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT/2-1, constants.BLACK) player2 = Paddle(screen, constants.WIDTH-4, constants.HEIGHT/2-1, constants.BLACK) net = Net(screen, constants.BLACK) screen.clear() player1.draw() player2.draw() net.draw() screen.drawScore(5, 9) time.sleep(2) player1.move(1500) player1.draw()
def main(): score1 = 9 score2 = 0 server = 1 won = 0 gameover = False effects_timer = 0 effects_count = 0 effects_colour = '' effect = False start = True start_time = time.time() ## Graphics class screen = Screen(constants.WIDTH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT / 2 - 1, constants.PLAYER1_COLOUR) player2 = Paddle(screen, constants.WIDTH - 4, constants.HEIGHT / 2 - 1, constants.PLAYER2_COLOUR) net = Net(screen, constants.NET_COLOUR) ball = Ball(screen, 5, 20, constants.BALL_COLOUR) pyglow = PyGlow() led = Led(5) net.draw() screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) # Initial value ball.velocity = [10.0, 10.0] #Roughly 8 seconds to cross screen? screen.draw_str(25, 20, 'START', constants.WHITE) screen.draw_str(25, 26, 'GAME!', constants.WHITE) while (True): end_time = time.time() frame_time = end_time - start_time start_time = end_time if (effect): effects_timer += frame_time if ((effects_timer) % 0.4 > 0.2 and (effects_timer - frame_time) % 0.4 <= 0.2): pyglow.all(0) effects_count += 1 elif ((effects_timer) % 0.4 <= 0.2 and (effects_timer - frame_time) % 0.4 > 0.2): pyglow.color(effects_colour, 150) if (effects_count >= 5): effect = False effects_count = 0 #noise reduction value1 = 0 value2 = 0 for i in range(20): value1 += read_i2c(CHAN2) value2 += read_i2c(CHAN3) value1 /= 20 value2 /= 20 if (won == 0): # Hardware debounce # Player1 Serve if (GPIO.input(10) == 1): if (start): start = False screen.draw_str(25, 20, 'START', constants.BACKGROUND_COLOUR) screen.draw_str(25, 26, 'GAME!', constants.BACKGROUND_COLOUR) net.draw() if (server == 1): ball.served = True # Player1 Power up if (GPIO.input(9) == 1): player1.power_up() # Software debounce # Player2 Serve if (debounce(0, 17)): if (server == 2): ball.served = True # Player2 Power up if (debounce(1, 11)): player2.power_up() # Lose condition if (ball.x >= screen.width - 1): score1 += 1 ball.served = False screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) pyglow.color('blue', 150) effects_timer = 0 effects_colour = 'blue' effect = True if ((score1 + score2) % 10 >= 5): server = 2 ball.x = player2.x - 1 ball.y = player2.y + player2.size[1] / 2 ball.velocity = [-10, 10] else: ball.x = player1.x + 1 ball.y = player1.y + player1.size[1] / 2 ball.velocity = [10, 10] if (ball.x <= 1): score2 += 1 ball.served = False ball.x = player1.x + 1 ball.y = player1.y + player1.size[1] / 2 screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) pyglow.color('red', 150) effects_timer = 0 effects_colour = 'red' effect = True if ((score1 + score2) % 10 >= 5): server = 2 ball.x = player2.x - 1 ball.y = player2.y + player2.size[1] / 2 ball.velocity = [-10, 10] else: ball.x = player1.x + 1 ball.y = player1.y + player1.size[1] / 2 ball.velocity = [10, 10] if (score1 >= 10): won = 1 elif (score2 >= 10): won = 2 # TODO: Reduce noise; multiple reads before move? player1.move(value1) player2.move(value2) player1.update(frame_time) player2.update(frame_time) if (not ball.served): if (server == 1): ball.last_pos = [ball.roundx, ball.roundy] ball.y = player1.y + player1.size[1] / 2 ball.x = player1.x + 1 ball.roundx = int(round(ball.x)) ball.roundy = int(round(ball.y)) if (ball.last_pos != [ball.roundx, ball.roundy]): ball._moved = True if (server == 2): ball.last_pos = [ball.roundx, ball.roundy] ball.y = player2.y + player2.size[1] / 2 ball.x = player2.x - 1 ball.roundx = int(round(ball.x)) ball.roundy = int(round(ball.y)) if (ball.last_pos != [ball.roundx, ball.roundy]): ball._moved = True # Collision Detection if (ball.roundx == player1.x): rx = random.randint(5, 15) ry = random.randint(5, 15) if (ball.roundy >= player1.y and ball.roundy <= player1.y + player1.size[1] / 3): ball.velocity[1] = -ry ball.velocity[0] = rx if (ball.roundy >= player1.y + player1.size[1] / 3 and ball.roundy <= player1.y + player1.size[1] / 3 * 2): ball.velocity[1] = 0 ball.velocity[0] = rx if (ball.roundy >= player1.y + player1.size[1] / 3 * 2 and ball.roundy <= player1.y + player1.size[1]): ball.velocity[1] = ry ball.velocity[0] = rx # Redraw paddle player1._moved = True if (ball.roundx == player2.x): rx = random.randint(5, 15) ry = random.randint(5, 15) if (ball.roundy >= player2.y and ball.roundy <= player2.y + player2.size[1] / 3): ball.velocity[1] = -ry ball.velocity[0] = -rx if (ball.roundy >= player2.y + player2.size[1] / 3 and ball.roundy <= player2.y + player2.size[1] / 3 * 2): ball.velocity[1] = 0 ball.velocity[0] = -rx if (ball.roundy >= player2.y + player2.size[1] / 3 * 2 and ball.roundy <= player2.y + player2.size[1]): ball.velocity[1] = ry ball.velocity[0] = -rx # Redraw paddle player2._moved = True ball.update(frame_time) led.update(ball.x) ball.draw() player1.draw() player2.draw() net.spot_draw(ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1]) if (won > 0 and not gameover): screen.draw_str(15, 20, 'PLAYER ' + str(won), constants.WHITE) screen.draw_str(25, 26, 'WINS!', constants.WHITE) gameover = True
def main(): score1 = 0 score2 = 0 server = 1 won = 0 gameover = False effects_timer = 0 effects_count = 0 effects_colour = '' effect = False sound_timer = 0 start = True start_time = time.time() ## Graphics class screen = Screen(constants.WIDTH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT/2-1, constants.PLAYER1_COLOUR) player2 = Paddle(screen, constants.WIDTH-4, constants.HEIGHT/2-1, constants.PLAYER2_COLOUR) net = Net(screen, constants.NET_COLOUR) ball = Ball(screen, 5, 20, constants.BALL_COLOUR) pyglow = PyGlow() led = Led(5) net.draw() screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) # Initial value ball.velocity = [10.0,10.0] #Roughly 8 seconds to cross screen? screen.draw_str(25, 20, 'START', constants.WHITE) screen.draw_str(25, 26, 'GAME!', constants.WHITE) Buzzer.startMusic() while (True): # Calculate time since last frame end_time = time.time() frame_time = end_time - start_time start_time = end_time # Pyglow effects if (effect): effects_timer += frame_time if (won == 0): if ((effects_timer)%0.4 > 0.2 and (effects_timer - frame_time)%0.4 <= 0.2): pyglow.all(0) effects_count += 1 elif ((effects_timer)%0.4 <= 0.2 and (effects_timer - frame_time)%0.4 > 0.2): pyglow.color(effects_colour, 150) if (effects_count >= 5): effect = False effects_count = 0 else: if (effects_timer < 0.2): pyglow.color('white', 150) elif (effects_timer < 0.4): pyglow.color('blue', 150) elif (effects_timer < 0.6): pyglow.color('green', 150) elif (effects_timer < 0.8): pyglow.color('yellow', 150) elif (effects_timer < 1.0): pyglow.color('orange', 150) elif (effects_timer < 1.2): pyglow.color('red', 150) elif (effects_timer < 1.4): pyglow.all(0) pyglow.color('white', 150) effects_timer = 0 sound_timer += frame_time if (sound_timer / 0.15 >= 1): Buzzer.stopSound() sound_timer = 0 # Noise reduction for ADC value1 = 0 value2 = 0 for i in range(20): value1 += read_adc(CHAN2) value2 += read_adc(CHAN3) value1 /= 20 value2 /= 20 # Button inputs if (won == 0): # Hardware debounce # Player1 Serve if (GPIO.input(10) == 1): if (start): start = False screen.draw_str(25, 20, 'START', constants.BACKGROUND_COLOUR) screen.draw_str(25, 26, 'GAME!', constants.BACKGROUND_COLOUR) net.draw() time.sleep(0.2) ball.served = True start_time = time.time()-0.01 continue if (server == 1): ball.served = True # Player1 Power up if (GPIO.input(9) == 1 and not start): player1.power_up() # Software debounce # Player2 Serve if (read_adc(CHAN4) < 100): if (server == 2): ball.served = True # Player2 Power up if (debounce(1, 11) and not start): player2.power_up() # Lose condition if (ball.x >= screen.width-1): score1 += 1 ball.served = False # Draw new score screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) pyglow.color('blue', 150) effects_timer = 0 effects_colour = 'blue' effect = True # Work out who's turn to serve if ((score1+score2)%10 >= 5): server = 2 ball.x = player2.x-1 ball.y = player2.y + player2.size[1]/2 ball.velocity = [-10, 10] else: ball.x = player1.x+1 ball.y = player1.y + player1.size[1]/2 ball.velocity = [10, 10] # Lose condition if (ball.x <= 1): score2 += 1 ball.served = False # Draw new score screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) pyglow.color('red', 150) effects_timer = 0 effects_colour = 'red' effect = True # Work out who's turn to serve if ((score1+score2)%10 >= 5): server = 2 ball.x = player2.x-1 ball.y = player2.y + player2.size[1]/2 ball.velocity = [-10, 10] else: ball.x = player1.x+1 ball.y = player1.y + player1.size[1]/2 ball.velocity = [10, 10] # Has someone won? if (score1 >= 10): won = 1 elif (score2 >= 10): won = 2 # Move player paddles player1.move(value1) player2.move(value2) # Update paddles; if powerup player1.update(frame_time) player2.update(frame_time) # Move ball with paddle if not served if (not ball.served): if (server == 1): ball.last_pos = [ball.roundx, ball.roundy] ball.y = player1.y + player1.size[1] / 2 ball.x = player1.x + 1 ball.roundx = int(round(ball.x)) ball.roundy = int(round(ball.y)) if (ball.last_pos != [ball.roundx, ball.roundy]): ball._moved = True if (server == 2): ball.last_pos = [ball.roundx, ball.roundy] ball.y = player2.y + player2.size[1] / 2 ball.x = player2.x - 1 ball.roundx = int(round(ball.x)) ball.roundy = int(round(ball.y)) if (ball.last_pos != [ball.roundx, ball.roundy]): ball._moved = True # Collision Detection if (ball.roundx == player1.x): # Random speed rx = random.randint(5,15) ry = random.randint(5,15) # Different trajectories, depending on where the paddle was hit if (ball.roundy >= player1.y and ball.roundy <= player1.y + player1.size[1]/3): ball.velocity[1] = -ry ball.velocity[0] = rx Buzzer.hitSound() if (ball.roundy >= player1.y + player1.size[1]/3 and ball.roundy <= player1.y + player1.size[1]/3*2): ball.velocity[1] = 0 ball.velocity[0] = rx Buzzer.hitSound() if (ball.roundy >= player1.y + player1.size[1]/3*2 and ball.roundy <= player1.y + player1.size[1]): ball.velocity[1] = ry ball.velocity[0] = rx Buzzer.hitSound() # Redraw paddle player1._moved = True if (ball.roundx == player2.x): rx = random.randint(5,15) ry = random.randint(5,15) if (ball.roundy >= player2.y and ball.roundy <= player2.y + player2.size[1]/3): ball.velocity[1] = -ry ball.velocity[0] = -rx Buzzer.hitSound() if (ball.roundy >= player2.y + player2.size[1]/3 and ball.roundy <= player2.y + player2.size[1]/3*2): ball.velocity[1] = 0 ball.velocity[0] = -rx Buzzer.hitSound() if (ball.roundy >= player2.y + player2.size[1]/3*2 and ball.roundy <= player2.y + player2.size[1]): ball.velocity[1] = ry ball.velocity[0] = -rx Buzzer.hitSound() # Redraw paddle player2._moved = True # Update ball's position ball.update(frame_time) led.update(ball.x) # Draw ball ball.draw() # Draw player paddles player1.draw() player2.draw() # Draw net and score if ball was over them if (ball. last_pos != [ball.roundx, ball.roundy]): net.spot_draw(ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1]) # Print winner once if (won > 0 and not gameover): screen.draw_str(17, 20, 'PLAYER ' + str(won), constants.WHITE) screen.draw_str(25, 26, 'WINS!', constants.WHITE) gameover = True
def main(): score1 = 0 score2 = 0 start_time = time.time() bus = smbus.SMBus(1) ## Graphics class screen = Screen(constants.WIDTH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT/2-1, constants.BLACK) player2 = Paddle(screen, constants.WIDTH-4, constants.HEIGHT/2-1, constants.BLACK) net = Net(screen, constants.BLACK) ball = Ball(screen, 5, 20, constants.BALL_COLOUR) net.draw() screen.draw_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR) screen.draw_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR) # Dummy values ball.velocity = [10.0,10.0] #Roughly 8 seconds to cross screen? ball.served = True while (True): end_time = time.time() frame_time = end_time - start_time start_time = end_time value1 = read_i2c(CHAN1) value2 = read_i2c(CHAN4) # Lose condition if (ball.x >= screen.width-3): score1 += 1 ball.served = False ball.x = player2.x-1 ball.y = player2.y + player2.size[1]/2 server = 2 if (ball.x <= 3): score2 += 1 ball.served = False ball.x = player1.x+1 ball.y = player1.y + player1.size[1]/2 server = 1 score1 %= 10 score2 %= 10 # TODO: Reduce noise; multiple reads before move? player1.move(value1) player2.move(value2) player1.update(frame_time) player2.update(frame_time) # Collision Detection if (ball.roundx == player1.x + 1): if (ball.roundy >= player1.y and ball.roundy <= player1.y + player1.size[1]): # TODO: Actual trajectory stuff v = [1, ball.velocity[1]/ball.velocity[0]] r = random.randint(0, 2) tmp = ((8 + 3*r)**2)/2 tmp = math.sqrt(tmp) v[0] *= tmp v[1] *= tmp if (ball.roundx == player2.x - 1): if (ball.roundy >= player2.y and ball.roundy <= player2.y + player2.size[1]): ball.velocity[0] *= -1 ball.update(frame_time) player1.draw() player2.draw() ball.draw() net.spot_draw(ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE1[0], constants.SCORE1[1], score1, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1]) screen.spot_num(constants.SCORE2[0], constants.SCORE2[1], score2, constants.SCORE_COLOUR, ball.last_pos[0], ball.last_pos[1])
class GameplayState(State): def __init__(self): super(GameplayState, self).__init__() self.next_state = "GameOver" # We start at level 0 but you can just cheat and change it self.level = 0 self.creator = LevelCreator() # List with all bricks in the current map/level self.layout = self.creator.create_level(self.level) # Used for level starting sequence (or after dying) - Round -> Ready -> bounce ball # Look at round_start() method self.phase = 0 self.time = 0 self.w = pg.display.get_surface().get_width() self.font = pg.font.Font("Assets/Fonts/ARCADE_N.TTF", 20) self.round = self.font.render("round " + str(self.level+1), True, (255, 255, 255)) self.ready = self.font.render("ready", True, (255, 255, 255)) self.ready_pos = self.ready.get_rect(center=(self.w/2, 580)) self.display_round = False self.display_ready = False # Text showcasing current score self.score_font = pg.font.Font("Assets/Fonts/ARCADE_N.TTF", 25) self.score_count = 0 self.score = self.score_font.render("score:" + str(self.score_count), True, (255, 255, 255)) self.background = pg.image.load("Assets/Textures/Backgrounds.png") self.background = pg.transform.scale(self.background, (1152*3, 496*3)) # Ball cannot fall below bottom boundary self.bottom_boundary = pg.display.get_surface().get_height() self.start = True # Objects denoting number of lives (max is 6) self.hp_count = 3 self.hp = [] for i in range(5): self.hp.append(pg.image.load("Assets/Textures/Backgrounds.png")) self.hp[i] = pg.transform.scale(self.hp[i], (1152*3, 496*3)) self.paddle = Paddle() self.ball = Ball() def startup(self, data): self.data = data # Places ball on the paddle def position_ball(self): self.ball.x = self.paddle.x + self.paddle.sprite_rect[2]/2 - self.ball.sprite_rect[2]/2 self.ball.y = self.paddle.y - self.ball.sprite_rect[3] # Level starting sequence def round_start(self, dt): if self.phase == 0: self.round = self.font.render("round " + str(self.level+1), True, (255, 255, 255)) self.round_pos = self.round.get_rect(center=(self.w/2, 530)) self.display_round = True self.position_ball() self.time += dt if self.time >= 1.5: self.phase += 1 elif self.phase == 1: self.display_ready = True self.position_ball() self.time += dt if self.time >= 3: self.phase += 1 elif self.phase == 2: self.display_round = False self.display_ready = False self.ball.is_moving = True self.phase = 0 self.time = 0 self.start = False # Checks if two objects are colliding with each other def are_colliding(self, object_a, object_b): if object_a.x < object_b.x + object_b.sprite_rect[2] and object_a.x + object_a.sprite_rect[2] > object_b.x and object_a.y < object_b.y + object_b.sprite_rect[3] and object_a.y + object_a.sprite_rect[3] > object_b.y: return True else: return False # Handles collisions of def handle_collisions(self): # Collision of ball with bricks for index, brick in enumerate(self.layout): if self.are_colliding(self.ball, brick): collision_side = brick.collision_side(self.ball.x + self.ball.sprite_rect[2]/2, self.ball.y + self.ball.sprite_rect[3]/2) self.ball.reflect(collision_side) brick.hp -= 1 if brick.hp <= 0: self.score_count += brick.points self.score = self.score_font.render("score:" + str(self.score_count), True, (255, 255, 255)) del self.layout[index] # Collision of ball with paddle if self.are_colliding(self.ball, self.paddle): collision_side = self.paddle.collision_side(self.ball.x + self.ball.sprite_rect[2]/2, self.ball.y + self.ball.sprite_rect[3]/2) self.ball.reflect_paddle(collision_side) # Collision of ball with the floor if self.ball.y - 10*3 > self.bottom_boundary and self.ball.is_moving: self.hp_count -= 1 self.ball.is_moving = False self.start = True # Resets objects and data def reset_gameplay(self): self.hp_count = 3 self.level = 0 self.start = True self.score_count = 0 self.score = self.score_font.render("score:" + str(self.score_count), True, (255, 255, 255)) self.paddle.reset_position() self.position_ball() self.layout = self.creator.create_level(0) self.ball.is_moving = False def check_state_of_game(self, dt): if self.start: # If player runs out of lives - lose if self.hp_count <= 0: self.data["victory"] = False self.reset_gameplay() self.done = True # If not else: self.round_start(dt) # If player breaks all the bricks (except golden ones) elif len(self.layout) == self.creator.golden_bricks: self.level += 1 # Next level if not self.creator.return_layout(self.level): self.data["victory"] = True self.reset_gameplay() self.done = True # If it's the last level else: self.layout = self.creator.create_level(self.level) self.start = True self.ball.is_moving = False def get_event(self, event): if event.type == pg.QUIT: self.quit = True if event.type == pg.KEYDOWN: if event.key == pg.K_LEFT: self.paddle.move_left = True elif event.key == pg.K_RIGHT: self.paddle.move_right = True elif event.key == pg.K_p: self.position_ball() self.ball.is_moving = True if event.type == pg.KEYUP: if event.key == pg.K_LEFT: self.paddle.move_left = False elif event.key == pg.K_RIGHT: self.paddle.move_right = False def update(self, dt): self.check_state_of_game(dt) self.paddle.update(dt) self.ball.update(dt) self.handle_collisions() def draw(self, surface): surface.fill((0, 0, 0)) surface.blit(self.background, (0, 16*3), self.creator.get_background_rect(self.level)) for i in range(self.hp_count - 1): surface.blit(self.hp[i], (10*3 + i*16*3, 740), self.creator.get_hp_rect(self.level)) for brick in self.layout: brick.draw(surface) self.paddle.draw(surface) self.ball.draw(surface) surface.blit(self.score, (220, 15)) if self.display_round: surface.blit(self.round, self.round_pos) if self.display_ready: surface.blit(self.ready, self.ready_pos)
class Breakout(object): def __init__(self): # Initilaize pygame and the display/window pygame.init() self.width, self.height = 600, 800 self.screen = pygame.display.set_mode((self.width, self.height)) #, pygame.FULLSCREEN) pygame.display.set_caption('Breakout') # background = pygame.image.load("PiInvaders/background.png").convert(); # Create the game objects self.ball = Ball(self.width / 2, self.height - 32) self.paddle = Paddle(self.width / 2, self.height - 16, 80, 16) def new_game(self): """Start a new game of Breakout Resets all game level parameters, and starts a new round.""" self.game_over = False self.round = 0 self.new_round() def new_round(self): """Start a new round in a Breakout game Resets all round level parameters, increments the round counter, and puts the ball on the paddle, centering both.""" self.round += 1 self.ball_is_moving = False self.ball.x_velocity = random.randint(-3, 3) self.paddle.x = self.width / 2 self.ball.y = self.height - 32 def play(self): """Start Breakout game New game is started and game loop is entered. The game loop checks for events, updates all objects, and then draws all the objects.""" self.new_game() while not self.game_over: # Game loop for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.MOUSEBUTTONDOWN: self.game_over = True break if event.type == pygame.KEYDOWN: if not self.ball_is_moving and event.key == pygame.K_SPACE: self.ball_is_moving = True if event.key == pygame.K_LEFT: self.paddle.x_velocity = -4 elif event.key == pygame.K_RIGHT: self.paddle.x_velocity = 4 # This starts a new round, it's only here for debugging purposes if event.key == pygame.K_r: self.new_round() # This starts a new game, it's only here for debugging purposes if event.key == pygame.K_g: self.new_game() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and self.paddle.x_velocity < 0: self.paddle.x_velocity = 0 if event.key == pygame.K_RIGHT and self.paddle.x_velocity > 0: self.paddle.x_velocity = 0 else: self.paddle.update() if self.ball_is_moving: self.ball.update() else: self.ball.x = self.paddle.x self.screen.fill((0, 0, 0)) self.paddle.draw(pygame, self.screen) self.ball.draw(pygame, self.screen) pygame.display.flip() pygame.quit()