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)
class testPaddle(unittest.TestCase): def setUp(self): display = pygame.display.set_mode((400, 400)) self.testpaddle = Paddle(20, 50, 100, display) def testConstructor(self): self.assertEqual(self.testpaddle.x, 20) self.assertEqual(self.testpaddle.w, 50) self.assertEqual(self.testpaddle.h, 100) self.assertEqual(self.testpaddle.y, 400 // 2 - 100 // 2) def testMoveTo(self): self.testpaddle.moveTo(0) self.assertEqual(self.testpaddle.y, 0) self.testpaddle.moveTo(400) self.assertEqual(self.testpaddle.y, 300) def testSetChange(self): self.testpaddle.setChange(5) self.assertEqual(self.testpaddle.change, 5) def testUpdate(self): self.testpaddle.setChange(5) self.testpaddle.update() self.assertEqual(self.testpaddle.y, 155) self.testpaddle.moveTo(400) self.testpaddle.update() self.assertEqual(self.testpaddle.y, 300) def testReset(self): self.testpaddle.reset() self.assertTrue(self.testpaddle.isReset())
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 loopGame(self): clock = pygame.time.Clock() ball = Ball([100,100]) paddle = Paddle([width/2,395]) font = pygame.font.Font(None, 25) sound_collision = pygame.mixer.Sound("music/tick.mp3") vector = [] posRectx = 90 posRecty = 60 score = 0 for i in range(0, 50): if(i%5==0): posRecty = posRecty + 20 posRectx = 80 else: posRectx = posRectx + 80 rectColid = RectColid([posRectx,posRecty]) vector.append(rectColid) running_game = True while running_game: clock.tick(120) textoScore = font.render("Score: %d" % score, True, white) for event in pygame.event.get(): if event.type==QUIT: running_game = False keys = pygame.key.get_pressed() if keys[K_a]: paddle.imagerect.centerx -= 5 if keys[K_d]: paddle.imagerect.centerx += 5 if paddle.imagerect.colliderect(ball.imagerect): if ball.speed[1] > 0: ball.speed[1] = -ball.speed[1] for rect in vector: if rect.imagerect.colliderect(ball.imagerect): vector.remove(rect) ball.speed[1] = -ball.speed[1] sound_collision.play(1) score += 1 ball.update() paddle.update() screen.fill(black) screen.blit(ball.image, ball.imagerect) screen.blit(paddle.image, paddle.imagerect) #Coloca os objetos na tela for rect in vector: screen.blit(rect.image, rect.imagerect) screen.blit(textoScore, [10, 10]) pygame.display.flip()
def runGame(): pygame.init() pongSettings = Settings() screen = pygame.display.set_mode( (pongSettings.screenWidth, pongSettings.screenHeight)) pygame.display.set_caption("Pong 2") paddleTopBottom = Group() paddleLeftRight = Group() paddle = Paddle(pongSettings, screen, "player", "bottom") paddle3 = Paddle2(pongSettings, screen, "right") paddle5 = Paddle(pongSettings, screen, "player", "top") paddle2 = Paddle2(pongSettings, screen, "left") paddle4 = Paddle(pongSettings, screen, "AI", "top") paddle6 = Paddle(pongSettings, screen, "AI", "bottom") paddleTopBottom.add(paddle, paddle4, paddle5, paddle6) paddleLeftRight.add(paddle2, paddle3) ball = Ball(pongSettings, screen) divide = Divider(pongSettings, screen) play_button = Button(pongSettings, screen, "Play") sb = Scoreboard(pongSettings, screen) startScreen = Start(pongSettings, screen) while True: gf.checkEvents(pongSettings, paddle, paddle3, paddle5, play_button, sb) if pongSettings.gameActive: gf.checkPaddleBallCollision(ball, paddleTopBottom, paddleLeftRight, pongSettings) gf.checkOutOfBounds(ball, pongSettings, screen, sb) paddle.update(ball) paddle2.update(ball) paddle3.update(ball) paddle4.update(ball) paddle5.update(ball) paddle6.update(ball) ball.update() gf.updateScreen(pongSettings, screen, paddle, paddle2, paddle3, paddle4, paddle5, paddle6, ball, divide, sb) else: gf.startGame(play_button, startScreen)
def run_game(): # Initialize Game, settings and create a screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Pong") play_button = Button(ai_settings, screen, "Play") # Make a Paddle bottomPaddle = Paddle(ai_settings, screen, 1) topPaddle = Paddle(ai_settings, screen, 2) mainPaddle = Paddle(ai_settings, screen, 3) bottomPaddle_AI = PaddleAI(ai_settings, screen, 1) topPaddle_AI = PaddleAI(ai_settings, screen, 2) mainPaddle_AI = PaddleAI(ai_settings, screen, 3) ballPoint = Point(1,1) ball = Ball(ai_settings, screen, 600, 400, ballPoint) stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) #star1 = Star(ai_settings, screen) # Start the main loop for the game while True: # Watch for keyboard and mouse events gf.check_events(ai_settings, screen, stats, sb, play_button, topPaddle, bottomPaddle, mainPaddle, bottomPaddle_AI, topPaddle_AI, mainPaddle_AI) if stats.game_state is True: bottomPaddle.update() topPaddle.update() mainPaddle.update() bottomPaddle_AI.update(ball) topPaddle_AI.update(ball) mainPaddle_AI.update(ball) ball.update(mainPaddle,topPaddle, bottomPaddle, bottomPaddle_AI, topPaddle_AI, mainPaddle_AI, stats, sb) gf.update_screen(ai_settings, screen, bottomPaddle, topPaddle, mainPaddle, ball, bottomPaddle_AI, topPaddle_AI, mainPaddle_AI, stats, sb, play_button)
class Main: def __init__(self): pygame.init() #limits the speed of continuous key presses pygame.key.set_repeat(1, 1) random.seed() #initializes variables for game self.width = 800 self.height = 800 self.running = False self.level = "levels/level_test.csv" self.level_map = [] #state of the game self.game_state = "MENU" self.menu_objects = {} self.menu_objects["playButton"] = Button(self.width / 2 - 75, self.height - 255, 150, 50, "Play Game") self.menu_objects["selectLevelButton"] = Button( self.width / 2 - 75, self.height - 200, 150, 50, "Select Level") self.menu_objects["instructionsButton"] = Button( self.width / 2 - 75, self.height - 145, 150, 50, "Instructions") self.menu_objects["backButton"] = Button(5, self.height - 55, 150, 50, "Back") #initializes variables for bricks self.bricks = [] self.initPaddle() self.initBall() self.paddle = Paddle(self.paddleX, self.paddleY, self.paddleWidth, self.paddleHeight, self.paddleVelocity, self.width) self.ball = Ball(self.paddle, self.ballX, self.ballY, self.ballRadius, self.ballVelocityX, self.ballVelocityY, self.width, self.height) #initializes the screen self.screen = pygame.display.set_mode((self.width, self.height)) def initPaddle(self): #initializes variables for paddle self.paddleWidth = 200 self.paddleHeight = 20 self.paddleX = self.width / 2 - self.paddleWidth / 2 self.paddleY = self.height - self.paddleHeight - 10 self.paddleVelocity = 4 def initBall(self): #initializes variables for ball self.ballRadius = 15 self.ballX = self.width / 2 - self.ballRadius self.ballY = self.paddleY - self.ballRadius * 2 self.ballVelocityX = random.randint(4, 7) if random.randint(0, 1) == 0: self.ballVelocityX *= -1 self.ballVelocityY = random.randint(5, 7) * -1 def getInput(self): #loops through all of the events received events = pygame.event.get() for event in events: #quits the game if the 'X' button is clicked if event.type == pygame.QUIT: self.end() #tests which key on the keyboard is clicked if event.type == pygame.KEYDOWN: #updates paddle direction to left if event.key == pygame.K_a or event.key == pygame.K_LEFT: self.paddle.setDirection("left") #updates paddle direction to right if event.key == pygame.K_d or event.key == pygame.K_RIGHT: self.paddle.setDirection("right") #quits the game if escape is clicked if event.key == pygame.K_ESCAPE: self.end() def loadLevel(self): #opens the csv file containing the level file = open(self.level) reader = csv.reader(file) self.level_map = [] #loops through the file and adds each element to an array for row in reader: row_contents = [] for col in row: row_contents.append(col) self.level_map.append(row_contents) #loops through the array and loads the level for i in range(len(self.level_map)): for j in range(len(self.level_map[i])): #creates a new Brick object for every brick in the level if self.level_map[i][j] == 'b': brickX = j * 100 + 5 brickY = i * 50 + 5 brickTier = 1 self.bricks.append(Brick(brickX, brickY, brickTier)) def update(self): #tests which game state the game is in if self.game_state == "PLAYING": #updates the paddle position self.paddle.update() self.ball.update() if self.ball.getRunning() == False: self.game_state = "MENU" self.reset() for brick in self.bricks: if brick.isColliding(self.ball): self.bricks.remove(brick) self.paddle.setDirection("null") elif self.game_state == "MENU": #tests if buttons are clicked if self.menu_objects["playButton"].isClicked(): self.game_state = "PLAYING" elif self.menu_objects["selectLevelButton"].isClicked(): self.game_state = "SELECT LEVEL" elif self.menu_objects["instructionsButton"].isClicked(): self.game_state = "INSTRUCTIONS" elif self.game_state == "INSTRUCTIONS" or self.game_state == "SELECT LEVEL": if self.menu_objects["backButton"].isClicked(): self.game_state = "MENU" def render(self): #creates a background for the game self.screen.fill((0, 0, 0)) #tests which game state the game is in if self.game_state == "PLAYING": #loops through the bricks array and draws each brick to the screen for i in range(len(self.bricks)): pygame.draw.rect( self.screen, (200, 100, 100), (self.bricks[i].getX(), self.bricks[i].getY(), self.bricks[i].getWidth(), self.bricks[i].getHeight())) #draws the paddle to the screen self.paddle.render(self.screen) #draws the ball to the screen self.ball.render(self.screen) elif self.game_state == "MENU": #draws the menu elements to the screen self.menu_objects["playButton"].render(self.screen) self.menu_objects["selectLevelButton"].render(self.screen) self.menu_objects["instructionsButton"].render(self.screen) elif self.game_state == "INSTRUCTIONS": self.menu_objects["backButton"].render(self.screen) elif self.game_state == "SELECT LEVEL": self.menu_objects["backButton"].render(self.screen) #updates the screen pygame.display.update() def reset(self): self.loadLevel() self.initBall() self.initPaddle() self.ball.reset(self.ballX, self.ballY, self.ballVelocityX, self.ballVelocityY) self.paddle.reset(self.paddleX) def main(self): #loads the level and prints contents to the console self.loadLevel() #main game loop while self.running: self.getInput() self.update() self.render() #delays program time.sleep(0.01) #exits the program pygame.quit() sys.exit() def start(self): #starts the game self.running = True self.main() def end(self): #ends the game self.running = False
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 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])
class Player: def __init__(self, side, window_dims): self._score = 12345 self._side = side self._paddle = Paddle(side, window_dims) self._controller = Controller() self._is_serving = False self._serve_speed = window_dims[ 0] / 0.5 # "Should take roughly 3 seconds to cross the screen" def update(self, ball, window_height, dt): self._paddle.update(dt) # Position paddle based on controller input new_vert_pos = (self._paddle.size / 2) + self._controller.dial_position_0_1 * ( window_height - self._paddle.size) self._paddle.set_vertical_pos(new_vert_pos, window_height) # When serving, tie the ball's Y position to that of the paddle if (self._is_serving): # Left faces into court with +X, right with -X xDir = -1 if self._side == Side.RIGHT else 1 ball.position = np.array([ self._paddle.position[0] + (1 * xDir), self._paddle.position[1] ]) ball.velocity = np.array([0, 0]) # Release ball if (self._controller.is_button_down(Side.LEFT)): self._is_serving = False ball.velocity = np.array([50, self._paddle.vertical_velocity]) ball.velocity = np.array( [self._serve_speed, self._paddle.vertical_velocity]) # Paddle size boost if (self._controller.is_button_down(Side.RIGHT)): self._paddle.activate_double_size() def increment_score(self): self._score += 1 def update_controller_state(self, dial_pos_0_1, left_button_down, right_button_down): self._controller._dial_position_0_1 = dial_pos_0_1 self._controller._buttons_down[Side.LEFT] = left_button_down self._controller._buttons_down[Side.RIGHT] = right_button_down def set_as_serving(self): self._is_serving = True @property def side(self): return self._side @property def paddle(self): return self._paddle @property def score(self): return self._score @property def is_serving(self): return self._is_serving @property def controller(self): return self._controller
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()
class PongGame(object): def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.gameDisplay = pygame.display.set_mode( (constant.WIDTH, constant.HEIGHT)) self.text, self.text2, self.font, self.font2, self.textRect, self.text2Rect = None, None, None, None, None, None self.ball, self.paddle1, self.paddle2, self.player1, self.player2 = None, None, None, None, None self.initializeFont() self.initializeObject() self.paddlespeed = 5 self.terminate = False while not self.terminate: self.checkEvent() self.collisionCheck() self.checkScore() self.updateObject() self.updateText() self.renderText() self.renderObject() pygame.display.update() self.clock.tick(120) pygame.quit() def initializeFont(self): self.font = pygame.font.Font("freesansbold.ttf", 32) self.font2 = pygame.font.Font("freesansbold.ttf", 15) self.text = self.font.render("PONG", True, (255, 255, 255)) self.text2 = self.font2.render("press r to reset game", True, (255, 255, 255)) self.textRect = self.text.get_rect() self.text2Rect = self.text2.get_rect() self.text2Rect.center = (constant.WIDTH // 2, 80) self.textRect.center = (constant.WIDTH // 2, 40) def initializeObject(self): self.ball = Ball(constant.WIDTH // 2, constant.HEIGHT // 2, 10, 5, random.uniform(0, math.pi), self.gameDisplay) self.paddle1 = Paddle(30, 20, 150, self.gameDisplay) self.paddle2 = Paddle(constant.WIDTH - 50, 20, 150, self.gameDisplay) self.player1 = Player(self.paddle1) self.player2 = Player(self.paddle2) def resetGame(self): self.ball.reset() self.player1.reset() self.player2.reset() def checkEvent(self): for event in pygame.event.get(): # check events if event.type == pygame.QUIT: self.terminate = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: self.resetGame() if event.key == pygame.K_UP: if self.paddle2.y > 0: self.paddle2.setChange(-self.paddlespeed) if event.key == pygame.K_DOWN: if self.paddle2.y < constant.HEIGHT - self.paddle2.h: self.paddle2.setChange(self.paddlespeed) if event.key == pygame.K_w: if self.paddle1.y > 0: self.paddle1.setChange(-self.paddlespeed) if event.key == pygame.K_s: if self.paddle1.y < constant.HEIGHT - self.paddle1.h: self.paddle1.setChange(self.paddlespeed) if event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: self.paddle2.stop() elif event.key == pygame.K_w or event.key == pygame.K_s: self.paddle1.stop() print(event) def collisionCheck(self): if (self.ball.x >= self.paddle1.x + self.ball.r and self.ball.x <= self.paddle1.x + self.paddle1.w + self.ball.r ) and (self.ball.y >= self.paddle1.y and self.ball.y <= self.paddle1.y + self.paddle1.h): self.ball.a = random.uniform(math.pi * 7 / 4, math.pi * 9 / 4) self.ball.speed = random.randint(4, 8) #print(ball.a) self.ball.updateSpeeds() if (self.ball.x >= self.paddle2.x - self.ball.r and self.ball.x <= self.paddle2.x + self.paddle2.w - self.ball.r ) and (self.ball.y >= self.paddle2.y and self.ball.y <= self.paddle2.y + self.paddle2.h): self.ball.a = random.uniform(math.pi * 3 / 4, math.pi * 5 / 4) self.ball.speed = random.randint(4, 8) #print(ball.a) self.ball.updateSpeeds() def renderText(self): self.gameDisplay.fill((0, 0, 0)) self.gameDisplay.blit(self.text, self.textRect) self.gameDisplay.blit(self.text2, self.text2Rect) self.gameDisplay.blit(self.score1text, self.score1Rect) self.gameDisplay.blit(self.score2text, self.score2Rect) def updateText(self): self.score1text = self.font.render(str(self.player1.score), True, (255, 255, 255)) self.score2text = self.font.render(str(self.player2.score), True, (255, 255, 255)) self.score1Rect = self.score1text.get_rect() self.score1Rect.center = (40, 40) self.score2Rect = self.score2text.get_rect() self.score2Rect.center = (constant.WIDTH - 40, 40) def updateObject(self): self.paddle1.update() self.paddle2.update() self.ball.update() def checkScore(self): if self.ball.x <= self.ball.r: self.player2.winRound() self.ball.reset() self.paddle1.reset() elif self.ball.x >= constant.WIDTH - self.ball.r: self.player1.winRound() self.ball.reset() self.paddle2.reset() def renderObject(self): self.ball.render() self.paddle1.render() self.paddle2.render()
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)
done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: done = True x,y = ball1.pos if ball1.collidesIn(x+ball1.speed[0], y): ball1.bounceX() if ball1.collidesIn(x, y+ball1.speed[1]): ball1.bounceY() ball1.moveRelative(ball1.speed[0],ball1.speed[1]) paddle.update() if pygame.sprite.collide_rect(paddle, ball1): ball1.bounceY() ball1.speed = (5*(paddle.pos[0]/ball1.pos[0]), ball1.speed[1]) if ball1.pos[1] > paddle.pos[1] : offset = -20 else: offset = 20 paddle.recoil(offset) block_to_remove = None for block in blocks: if pygame.sprite.collide_rect(ball1,block): ball1.bounceAgainst(block) block_to_remove = block
def main(): global player1_points global player2_points global screensize global p1Control global p2Control global ball global screen global player1_paddle global player2_paddle global scoreLimit global myFont global messageScroll # Initialise PyGame and create screen object pygame.init() pygame.font.init() screensize = (height, width) myFont = pygame.font.SysFont("dotty", 20*scale) screen = pygame.display.set_mode((screensize)) pygame.display.set_caption('MMUARCADE2018') # set up grove input detection groveInitalRead() # limit and track FPS clock = pygame.time.Clock() # Create Ball and paddles ball = Ball(screensize, scale) player1_paddle = Paddle(screensize, screensize[0]-(2*scale)-2, scale) player2_paddle = Paddle(screensize, 2*scale+2, scale) running = True while running: # MAIN LOOP # FRAME SPEED LIMIT clock.tick(64) # EVENT HANDLING for event in pygame.event.get(): if event.type == QUIT: running = False; elif keyboardControl == True: keyboardHandler(event) # KEYBOARD CONTROLS if keyboardControl == False: groveControlsHandler() # GROVE CONTROLS # OBJECT UPDATING player1_paddle.update() player2_paddle.update() ball.update(player1_paddle, player2_paddle, scale) # AI CONTROLS if p2Control == False: paddleAI(player2_paddle) if p1Control == False: paddleAI(player1_paddle) # POINT SCORING if ball.hit_edge_left: pointScored("left") elif ball.hit_edge_right: pointScored("right") # RENDER - SEE BELOW render() pygame.quit() # executes when "running" is set to False
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
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)
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])