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 game_loop(): player = Paddle((20, SH - 18, 6, 36), inputs) computer = Paddle((SCREEN_WIDTH - 20, SH - 18, 6, 36), inputs) ball = Ball((SW - 3, SH - 3, 6, 6), inputs) state = 'start' running = True while running: running = game_exit() screen.fill(BLACK) keys = pygame.key.get_pressed() update_and_draw(player, computer, ball, keys) print_to_screen(str(player.score), score_font, SW/2, 36) print_to_screen(str(computer.score), score_font, 0.75*SCREEN_WIDTH, 36) if state == 'start': state = start_state(keys) elif state == 'serve': state = serve_state(ball, player, computer) elif state == 'play': state = play_state(ball, player, computer) elif state == 'over': state = over_state(ball, player, computer, keys) pygame.display.update() #pygame.display.flip() clock.tick(60)
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 __init__(self, drawable=True): self.drawable = drawable self.left_point = 0 self.right_point = 0 self.x = parameters.WINDOW_WIDTH self.y = parameters.WINDOW_HEIGHT self.window = pygame.display.set_mode( (parameters.WINDOW_WIDTH, parameters.WINDOW_HEIGHT)) paddle_l_strategy = SimpleAIStrategy() self.left_paddle = Paddle(parameters.PADDLE_1_X, parameters.PADDLE_1_Y, parameters.PADDLE_1_WIDTH, parameters.PADDLE_1_HEIGHT, parameters.PADDLE_1_V, parameters.PADDLE_1_COLOR, paddle_l_strategy, self.window, image_name=parameters.PLAYER_1_IMAGE, paddle_type="L") paddle_r_strategy = ReinforcementLearningStrategy() self.right_paddle = Paddle(parameters.PADDLE_2_X, parameters.PADDLE_2_Y, parameters.PADDLE_2_WIDTH, parameters.PADDLE_2_HEIGHT, parameters.PADDLE_2_V, parameters.PADDLE_2_COLOR, paddle_r_strategy, self.window, image_name=parameters.PLAYER_2_IMAGE, paddle_type="R") self.collusion_strategy = PositionCollusionStrategy( self.left_paddle, self.right_paddle) self.ball = Ball(self.collusion_strategy, self.window) paddle_l_strategy.set_ball(self.ball) paddle_r_strategy.set_ball(self.ball) self.collusion_strategy.set_environment(self) self.paddles = [self.left_paddle, self.right_paddle] for p in self.paddles: p.strategy.set_env(self) if drawable: pygame.init() self.window = pygame.display.set_mode( (parameters.WINDOW_WIDTH, parameters.WINDOW_HEIGHT)) os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 0) self.font_size = parameters.WINDOW_HEIGHT * 0.1 self.font = pygame.font.SysFont("monospace", int(self.font_size)) self.surface_point = self.font.render( str(self.left_point) + " - " + str(self.right_point), False, parameters.TEXT_COLOR) self.surface_point_area = self.surface_point.get_rect() self.surface_point_area.center = (parameters.WINDOW_WIDTH / 2, 50) else: pygame.quit() self.done = False
def game_on(): screen.tracer(0) screen.listen() scoreboard = ScoreBoard() scoreboard.print_score() lP = Paddle(-360, 0) rP = Paddle(360, 0) ball = Ball() screen.onkeypress(lP.up, "w") screen.onkeypress(lP.down, "s") screen.onkeypress(rP.up, "Up") screen.onkeypress(rP.down, "Down") winsound.PlaySound(resource_path("sound/winner.wav"), winsound.SND_ASYNC) time.sleep(4) game_over = False while not game_over: time.sleep(0.03) screen.update() ball.move() # detect collision with walls if ball.ycor() > upper_bound or ball.ycor() < lower_bound: ball.bouncing_wall() # detect miss the ball if ball.xcor() > right_bound: winsound.PlaySound(resource_path("sound/correct.wav"), winsound.SND_ASYNC) ball.refresh() scoreboard.increase_left() if scoreboard.lScore == 3: game_over = True time.sleep(1) if ball.xcor() < left_bound: winsound.PlaySound(resource_path("sound/correct.wav"), winsound.SND_ASYNC) ball.refresh() scoreboard.increase_right() if scoreboard.rScore == 3: game_over = True time.sleep(1) # detect collision with paddle if ball.distance(rP) < 50 and ball.xcor() > 340 or ball.distance( lP) < 50 and ball.xcor() < -340: ball.bouncing_paddle() winsound.PlaySound(resource_path("sound/bouncing.wav"), winsound.SND_ASYNC) scoreboard.print_final() winsound.PlaySound(resource_path("sound/happynes.wav"), winsound.SND_ASYNC)
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()
def start_game(rows, columns): global ball, blocks_list, starting_vy, ball_starting_vx, paddle, game_start, lives_left, game_over, score, game_won blocks_list = [] #clear list of blocks ball_starting_vx = randomize( -1 * MAX_START_SPEED, MAX_START_SPEED, -1 * MIN_SPEED, MIN_SPEED) #create random initial x-direction for ball #draw number of blocks specified for i in range(columns): for j in range(rows): #randomize colors r = uniform(0, 1) g = uniform(0, 1) b = uniform(0, 1) brick = Brick(i * BLOCK_LENGTH, j * BLOCK_WIDTH, r, g, b, BLOCK_LENGTH, BLOCK_WIDTH) blocks_list.append(brick) #add the block to the list #create ball and paddle ball = Ball(BALL_STARTING_X, BALL_STARTING_Y, BALL_RADIUS, uniform(0, 1), uniform(0, 1), uniform(0, 1), ball_starting_vx, ball_starting_vy) paddle = Paddle(paddle_X, paddle_Y, uniform(0, 1), uniform(0, 1), uniform(0, 1), PADDLE_LENGTH, PADDLE_HEIGHT, paddle_vx) game_start = False game_over = False game_won = False score = 0 lives_left = 3
def __init__(self, game): super().__init__(game) self.paddle_1 = Paddle() self.paddle_2 = Paddle() self.paddle_2.SetControlScheme(pygame.K_UP, pygame.K_DOWN) self.paddle_2.rect.right = self.game.screen_width self.paddle_2.pos.UpdatePositionX() self.paddles = [self.paddle_1, self.paddle_2] self.ball = Ball(30, self.game.screen_width / 2, 0) self.top_border = ZedLib.CollisionObject(self.game.screen_width, 10, 0, -10) self.bottom_border = ZedLib.CollisionObject(self.game.screen_width, 10, 0, self.game.screen_height) self.borders = [self.top_border, self.bottom_border]
def __init__(self): self.window = Window() self.paddle = Paddle(self.window) self.bricks = Bricks(self.window) self.ball = Ball(self.window) self.running = True self.check = True
def test_go_up_keyboard_binding(): screen = turtle.Screen() screen.setup(width=1000, height=600) pad = Paddle() pad.paddle() snakehead = Snake() sk = snakehead.snakehead() snake = Bindings(screen, sk, pad) snake.go_up() assert snake.GetsnakeheadDirection() == "up" snake.go_right() assert snake.GetsnakeheadDirection() == "right" snake.go_down() assert snake.GetsnakeheadDirection() == "down" snake.go_left() assert snake.GetsnakeheadDirection() == "left" #snake should not go left if it is going right snake.go_left() snake.go_right() #should still be going left assert snake.GetsnakeheadDirection() == "left" snake.go_up() snake.go_down() #snake should still go up assert snake.GetsnakeheadDirection() == "up"
def __init__(self): w = 500 h = 500 self.pWin = GraphWin("Pong", w, h) myIMG = Image(Point(250, 250), "linesfinished.gif") myIMG.draw(self.pWin) self.b = Ball(self.pWin) self.p = Paddle(self.pWin) self.hits = 0 self.score = 0 self.level = 1 self.scoreTitle = Text(Point(350, 25), "Score:") self.scoreTitle.setTextColor("white") self.scoreTitle.setSize(25) self.userScore = Text(Point(405, 25), self.score) self.userScore.setTextColor("white") self.userScore.setSize(25) self.levelTitle = Text(Point(100, 25), "Level:") self.levelTitle.setTextColor("white") self.levelTitle.setSize(25) self.userLevel = Text(Point(150, 25), self.level) self.userLevel.setTextColor("white") self.userLevel.setSize(25) self.scoreTitle.draw(self.pWin) self.userScore.draw(self.pWin) self.levelTitle.draw(self.pWin) self.userLevel.draw(self.pWin)
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 add_players(self): paddle_w = 50 paddle_h = 200 paddle_y = self.window.centery - (paddle_h // 2) paddle_1 = Paddle(pygame.rect.Rect(100, paddle_y, paddle_w, paddle_h), (pygame.K_w, pygame.K_s)) paddle_1.set_reset(paddle_1.right) paddle_2 = Paddle(pygame.rect.Rect(self.window.right - 100 - paddle_w, paddle_y, paddle_w, paddle_h), (pygame.K_i, pygame.K_k)) paddle_2.set_reset(paddle_2.left - (self.ball.radius * 2)) for paddle in [paddle_1, paddle_2]: self.handlers[pygame.KEYDOWN].append(paddle.move_handler) self.handlers[pygame.KEYUP].append(paddle.stop_moving) player_1 = PongPlayer(paddle_1, score=0, name="Player 1") player_2 = PongPlayer(paddle_2, score=-1, name="Player 2") self.players += [player_1, player_2]
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 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 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)
def make_left_side(self): self.paddles = [] self.set_label("Left Player") # Left paddle paddle_left = Paddle(self, self.settings, self.screen) paddle_left.make_left_side() self.paddles.append(paddle_left) # Top paddle paddle_top = Paddle(self, self.settings, self.screen) paddle_top.make_top_left_side() self.paddles.append(paddle_top) # Bottom paddle paddle_bottom = Paddle(self, self.settings, self.screen) paddle_bottom.make_bottom_left_side() self.paddles.append(paddle_bottom)
def make_right_side(self): self.paddles = [] self.set_label("Right Player") # Right paddle paddle_right = Paddle(self, self.settings, self.screen) paddle_right.make_right_side() self.paddles.append(paddle_right) # Top paddle paddle_top = Paddle(self, self.settings, self.screen) paddle_top.make_top_right_side() self.paddles.append(paddle_top) # Bottom paddle paddle_bottom = Paddle(self, self.settings, self.screen) paddle_bottom.make_bottom_right_side() self.paddles.append(paddle_bottom)
def resetGame(): global player1_points global player2_points global screensize global p1Control global p2Control global ball global screen global player1_paddle global player2_paddle print("Game Reset") player1_points = 0 player2_points = 0 groveInitalRead() p1Control = False p2Control = False player1_paddle = Paddle(screensize, screensize[0]-(2*scale)-2, scale) player2_paddle = Paddle(screensize, 2*scale+2, scale)
def __init__(self, x, y, ball, surface): if surface != None: self.paddle = Paddle(x, y, math.floor(surface.get_width() * 0.2), math.floor(surface.get_height() * 0.05), surface) else: self.paddle = None self.ball = ball self.score = 0 self.fitness_score = 1 self.network = NeuralNetwork(2, [4, 4, 1]) self.x_accumulator = 0.0
def __init__(self): super(PaddleEnv, self).__init__() self.game = Paddle() # Actions: left right hold self.action_space = spaces.Discrete(3) # Observation: paddle x coordinates, ball location and ball direction self.observation_space = spaces.Box(low=-1, high=1, shape=(1, 6), dtype=np.float16)
def initChoice(self, player, hadesrect, poseidonrect, zeusrect, arrowrect): mousepos = pygame.mouse.get_pos() margin = 50 if hadesrect.collidepoint(mousepos): if player == 1: self.player1 = Paddle("redlightning.jpg", 1, self.gameHeight, margin, self.width, "Hades") return True elif self.player1.god != "Hades": self.player2 = Paddle("redlightning.jpg", 2, self.gameHeight, margin, self.width, "Hades") return True if poseidonrect.collidepoint(mousepos): if player == 1: self.player1 = Paddle("bluelightning.jpg", 1, self.gameHeight, margin, self.width, "Poseidon") return True elif self.player1.god != "Poseidon": self.player2 = Paddle("bluelightning.jpg", 2, self.gameHeight, margin, self.width, "Poseidon") return True if zeusrect.collidepoint(mousepos): if player == 1: self.player1 = Paddle("yellowlightning.jpg", 1, self.gameHeight, margin, self.width, "Zeus") return True elif self.player1.god != "Zeus": self.player2 = Paddle("yellowlightning.jpg", 2, self.gameHeight, margin, self.width, "Zeus") return True return False
def __init__(self): # Construct the principal Screen self.wn = turtle.Screen() self.wn.title("PONG GAME HERNANDEZ X.A") # self.wn.bgcolor("black") self.wn.bgpic("bg_game.gif") self.wn.setup(width=800, height=600) self.wn.tracer(0) # Construct Threads self.threadMusic = Thread(target=self.playMusicBack) self.threadMusic.start() # construct Paddles self.paddle_a = Paddle("A", PongPlayer.__SPEED_PLADDE) self.paddle_b = Paddle("B", PongPlayer.__SPEED_PLADDE) # Construrct the Score fo the players self.score = Score() self.score.printScore() # Construct of Ball self.ball = Ball(PongPlayer.__SPEED_BALL, self.score)
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 __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 __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 __init__(self): self.win = GraphWin("Pong", 300, 300) self.ball = Ball(self.win) self.paddle = Paddle(self.win, 50, Point(290, 150)) self.fixedX = 280 self.ballMid = self.ball.getCenter() self.ballMidX = self.ballMid.getX() self.ballMidY = self.ballMid.getY() self.instructions = "Click space to either side of the paddle" instructions = Text(Point(150, 20), self.instructions) self.instruct = instructions self.hits = 0 self.level = 0 self.printtowin = "Hits:", self.hits, "Level:", self.level printscore = Text(Point(150, 20), self.printtowin) self.score = printscore self.printtowin2 = "Game Over" printendgame = Text(Point(150, 35), self.printtowin2) self.endgame = printendgame
import sys, pygame, time from MCTSPlayer import MCTSPlayer from Paddle import Paddle from Ball import Ball from Driver import Driver from Game import Game, Winner from Paddle import Direction, move_map from SimplePlayer import SimplePlayer from config import * pygame.init() screen = pygame.display.set_mode(size) b = Ball(pos=(width//2, height//2)) p1 = Paddle(rect=(p1_left_x, p1_top_y, paddle_width, paddle_height)) p2 = Paddle(rect=(p2_left_x, p2_top_y, paddle_width, paddle_height)) d = Driver(p1, p2, b, screen) g = Game(p1, p2, b, size) def draw(): screen.fill(black) d.draw() last_p1 = Direction.NONE last_p2 = Direction.NONE m_player = MCTSPlayer(1, 0.1, g) s_player = SimplePlayer(g) k = 0 while 1: for event in pygame.event.get():
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