def move_ball(self): if self.ball.y == 10 or self.ball.y == 490: self.ball.bounce_off_wall() self.hit_wall_sound.play() if self.ball.x == 30 and abs(self.leftPaddle.y - self.ball.y) < self.leftPaddle.size / 2: self.ball.bounce_off_paddle() self.hit_paddle_sound.play() if self.ball.x == 970 and abs(self.rightPaddle.y - self.ball.y) < self.rightPaddle.size / 2: self.ball.bounce_off_paddle() self.hit_paddle_sound.play() if self.ball.x < 0: self.ball = Ball(Config.ball_left_start_x, Config.ball_left_start_y, Config.ball_size, 0, 0) self.serve = self.serve_left self.score.increment_right() if self.ball.x > 1000: self.ball = Ball(Config.ball_right_start_x, Config.ball_right_start_y, Config.ball_size, 0, 0) self.serve = self.serve_right self.score.increment_left() self.ball.move()
def test_bounce_ball_against_bottom_wall(self): hit_wall = pygame.mixer.Sound('../sounds/pong_wall.wav') hit_paddle = pygame.mixer.Sound('../sounds/pong_wall.wav') pong = Pong(hit_wall, hit_paddle) pong.ball = Ball(Config.ball_left_start_x, 500 - 20, 5, 5) pong.move_ball() self.assertEqual(pong.ball.vx, 5) self.assertEqual(pong.ball.vy, -5)
def test_bounce_ball_against_right_paddle(self): hit_wall = pygame.mixer.Sound('../sounds/pong_wall.wav') hit_paddle = pygame.mixer.Sound('../sounds/pong_wall.wav') pong = Pong(hit_wall, hit_paddle) pong.ball = Ball(960, 250, 5, 5) pong.move_ball() self.assertEqual(pong.ball.vx, -5) self.assertEqual(pong.ball.vy, 5)
def __init__(self): self.ball_in_pallet = True self.clock = pygame.time.Clock() self.point: Point = Point() self.live: Live = Live() self.ball: Ball = Ball() self.pallet: Pallet = Pallet() self.wall: Wall = Wall() self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
def test_ball_missed_on_left(self): hit_wall = pygame.mixer.Sound('../sounds/pong_wall.wav') hit_paddle = pygame.mixer.Sound('../sounds/pong_wall.wav') pong = Pong(hit_wall, hit_paddle) pong.ball = Ball(-5, 250, -5, -5) pong.move_ball() self.assertEqual(pong.ball.x, Config.ball_left_start_x) self.assertEqual(pong.ball.y, Config.ball_left_start_y) self.assertEqual(pong.ball.vx, 0) self.assertEqual(pong.ball.vy, 0)
def main(): arena = Arena(surf=DISPLAY_SURF) player_1 = Player(name=settings.PLAYER_ONE, surf=DISPLAY_SURF, pos=get_player_default_pos(num=settings.PLAYER_ONE)) player_2 = Player(name=settings.PLAYER_TWO, surf=DISPLAY_SURF, pos=get_player_default_pos(num=settings.PLAYER_TWO)) ball = Ball(surf=DISPLAY_SURF, pos=get_ball_default_pos(), speed=settings.EASY) clock = Clock(surf=DISPLAY_SURF) clock.start() # Stack used to maintain render order game_objects = [ arena, player_1, player_2, ball, clock, ] # Main loop while True: # Events for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() elif event.type == pygame.MOUSEMOTION: player_1.move((0, event.pos[1] - player_1.y)) # Logic game_over = check_point_scored(ball) if game_over: SoundController.play_game_over() clock.stop() elapsed = clock.get_elapsed_seconds() show_game_over_screen(DISPLAY_SURF, FPS_CLOCK, elapsed) clock.reset() clock.start() ball.reset_velocity() ball.reposition(get_ball_default_pos()) handle_ball_movement(ball, player_1, player_2) handle_player_movement(player_2, ball) # Rendering render_game_objects(game_objects) pygame.display.update() FPS_CLOCK.tick(settings.FPS)
def serve_right(self): self.ball = Ball(Config.ball_right_start_x, Config.ball_right_start_y, Config.ball_size, Config.ball_serve_right_vx, Config.ball_serve_right_vy)
def serve_left(self): self.ball = Ball(Config.ball_left_start_x, Config.ball_left_start_y, Config.ball_size, Config.ball_serve_left_vx, Config.ball_serve_left_vy)
from config import Config # Set up Pygame pygame.init() hit_wall = pygame.mixer.Sound('sounds/pong_wall.wav') hit_paddle = pygame.mixer.Sound('sounds/pong_wall.wav') screen = pygame.display.set_mode((Config.width, Config.height)) clock = pygame.time.Clock() # Set up Models leftPaddle = Paddle(Config.paddle_left_start_x, Config.paddle_left_start_y, Config.paddle_upper_limit, Config.paddle_lower_limit) rightPaddle = Paddle(Config.paddle_right_start_x, Config.paddle_right_start_y, Config.paddle_upper_limit, Config.paddle_lower_limit) ball = Ball(Config.ball_left_start_x, Config.ball_left_start_y, Config.ball_size) score = Score() pong = Pong(leftPaddle, rightPaddle, ball, score, hit_wall, hit_paddle, Config.color) # Game Loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_q]: pong.move_left_up() if keys[pygame.K_a]:
from enums.size import Size from models.ball import Ball from models.car import Car from models.doll import Doll from models.figures import Figures from models.child import Child from enums.age_group import AgeGroup manager = GameRoomManager() game_room = GameRoom(money_available=12000, age_group=AgeGroup.SCHOOL_AGE_UNDER_12, playground_area=124) # Checking sorting ball = Ball(price=100, size=Size.SMALL) car = Car(price=80, size=Size.SMALL) doll = Doll(price=140, size=Size.SMALL) figures = Figures(price=90, size=Size.SMALL) manager.buy_toy(game_room, ball) manager.buy_toy(game_room, car) manager.buy_toy(game_room, doll) manager.buy_toy(game_room, figures) toys = game_room.toys print("\there are all toys in game room:") for toy in toys: print(str(toys.index(toy) + 1) + ". " + str(toy)) print("\n")
def main(): pygame.init() WIDTH = 800 HEIGHT = 600 WALL_WIDTH = 20 PADDING = 10 BALL_VELOCITY = 0.2 PADDLE_VELOCITY = 0.2 BLOCK_COLS = 5 BLOCK_ROWS = 10 screen = pygame.display.set_mode((WIDTH, HEIGHT)) walls = { 'top': Wall(0, 0, WIDTH, WALL_WIDTH), 'left': Wall(0, 0, WALL_WIDTH, HEIGHT), 'bottom': Wall(0, HEIGHT - WALL_WIDTH, WIDTH, WALL_WIDTH), } lose_wall = Wall(WIDTH, 0, WALL_WIDTH, HEIGHT) # behind the paddle, hit this wall to lose paddle = Paddle(WIDTH - WALL_WIDTH, HEIGHT / 2) ball = Ball(WIDTH / 2, HEIGHT / 2, BALL_VELOCITY, 0) blocks = [] block_width = 20 block_height = (HEIGHT - (2 * WALL_WIDTH) - PADDING) / BLOCK_ROWS for nx in range(BLOCK_COLS): for ny in range(BLOCK_ROWS): x = WALL_WIDTH + PADDING + (nx * (block_width + PADDING)) y = WALL_WIDTH + PADDING + (ny * block_height) blocks.append(Block(x, y, block_width, block_height - PADDING)) done = False while not done: # event handling for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # keyboard handling pressed = pygame.key.get_pressed() if pressed[pygame.K_UP] and paddle.detectCollision( walls['top']) == Side.NONE: paddle.y -= PADDLE_VELOCITY if pressed[pygame.K_DOWN] and paddle.detectCollision( walls['bottom']) == Side.NONE: paddle.y += PADDLE_VELOCITY # physics stuff ball.update() paddle.update() # wall collisions for wall in walls: side = ball.detectCollision(walls[wall]) if side != Side.NONE: ball.bounce(side) # paddle collision side = ball.detectCollision(paddle) if side != Side.NONE: ball.bounce(side) offset_normalized = (ball.y - paddle.y - (paddle.height / 2)) / ( paddle.height / 2) # -1 to 1, offset from center of paddle ball.vy = offset_normalized * BALL_VELOCITY # steer ball by hitting off-center # block collisions for i in range(len(blocks) - 1, -1, -1): block = blocks[i] side = block.detectCollision(ball) if side != Side.NONE: ball.bounce(side) # block.alive = False del blocks[i] # lose condition if ball.detectCollision(lose_wall) != Side.NONE: # reset ball position ball.x = WIDTH / 2 ball.y = HEIGHT / 2 ball.vx = BALL_VELOCITY ball.vy = 0 # win condition if len(blocks) == 0: print("win yey") # clear screen screen.fill((0, 0, 0)) # draw walls for side in walls: walls[side].draw(screen) # draw paddle paddle.draw(screen) # draw ball ball.draw(screen) # draw blocks for block in blocks: block.draw(screen) pygame.display.flip()
def data_to_match(filename): ''' Convert YAML T20/ODI data to Match object ''' global WIDE_EXTRAS with open(filename, 'r') as stream: match_data = yaml.load(stream) # Get Match Info team_1 = match_data['info']['teams'][0] team_2 = match_data['info']['teams'][1] gender = match_data['info']['gender'] date = match_data['info']['dates'][0] season = date.year comp = match_data['info']['competition'] venue = match_data['info']['venue'] city = match_data['info']['city'] toss_winner = match_data['info']['toss']['winner'] toss_decision = match_data['info']['toss']['decision'] if toss_decision == 'field': batting_team, bowling_team = team_1 if team_1 != toss_winner else team_2, toss_winner else: bowling_team, batting_team = team_1 if team_1 != toss_winner else team_2, toss_winner pom = match_data['info']['player_of_match'][0] umpire_1 = match_data['info']['umpires'][0] umpire_2 = match_data['info']['umpires'][1] winner = match_data['info']['outcome']['winner'] balls_1, balls_2 = [], [] # 1st innings ball information for delivery in match_data['innings'][0]['1st innings']['deliveries']: for d in delivery.items(): over = Over(str(d[0])) batsman_runs = d[1]['runs']['batsman'] batsman = Batsman(d[1]['batsman'], batting_team) bowler = Bowler(d[1]['bowler'], '', bowling_team) extras = d[1]['runs']['extras'] if extras > 0: method_of_extras = d[1]['extras'].keys()[0] else: method_of_extras = '' # Reset the wides if over.first_ball(): WIDE_EXTRAS = 0 # Repeat ball due to wides for i in range(WIDE_EXTRAS): over = over.prev() if extras > 0 and method_of_extras == 'wides': WIDE_EXTRAS += 1 non_striker = Batsman(d[1]['non_striker'], batting_team) # If a wicket took place if 'wicket' in d[1].keys(): method_of_out = d[1]['wicket']['kind'] out_batsman = d[1]['wicket']['player_out'] else: method_of_out = None out_batsman = None balls_1.append( Ball(1, over, batting_team, batsman, non_striker, bowler, batsman_runs, extras, method_of_extras, method_of_out, out_batsman)) # 2nd innings ball information for delivery in match_data['innings'][1]['2nd innings']['deliveries']: for d in delivery.items(): over = Over(str(d[0])) batsman_runs = d[1]['runs']['batsman'] batsman = Batsman(d[1]['batsman'], bowling_team) bowler = Bowler(d[1]['bowler'], '', batting_team) extras = d[1]['runs']['extras'] if extras > 0: method_of_extras = d[1]['extras'].keys()[0] else: method_of_extras = '' # Reset the wides if over.first_ball(): WIDE_EXTRAS = 0 # Repeat ball due to wides for i in range(WIDE_EXTRAS): over = over.prev() if extras > 0 and method_of_extras == 'wides': WIDE_EXTRAS += 1 non_striker = Batsman(d[1]['non_striker'], batting_team) # If a wicket took place if 'wicket' in d[1].keys(): method_of_out = d[1]['wicket']['kind'] out_batsman = d[1]['wicket']['player_out'] else: method_of_out = None out_batsman = None balls_2.append( Ball(1, over, batting_team, batsman, non_striker, bowler, batsman_runs, extras, method_of_extras, 0, method_of_out, out_batsman)) # Get batter and bowler information now balls_1, batsmen_1 = balls_to_batsmen(balls_1) balls_2, batsmen_2 = balls_to_batsmen(balls_2) balls_1, bowlers_1 = balls_to_bowlers(balls_1) balls_2, bowlers_2 = balls_to_bowlers(balls_2) return Match(team_1, team_2, season, date, comp, venue, city, toss_winner, toss_decision, pom, umpire_1, umpire_2, winner, balls={ batting_team: balls_1, bowling_team: balls_2 }, batsmen={ batting_team: batsmen_1, bowling_team: batsmen_2 }, bowlers={ batting_team: bowlers_2, bowling_team: bowlers_1 })
def game(): """Main game function. Initializes and loads game assets and handles events.""" # Initialize screen pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption('Breakout') # Initialize background background_path = os.path.join('assets', 'backgrounds', 'space.png') background = load_png(background_path) # Initialize player Paddle paddle = Paddle() paddle_sprite = pygame.sprite.Group(paddle) # Initialize the ball ball = Ball() ball_sprite = pygame.sprite.Group(ball) # Initialize the bricks bricks = Brick.init_bricks() brick_sprites = pygame.sprite.Group(bricks) # Blit everything onto the screen screen.blit(background, (0, 0)) pygame.display.flip() # Initialize c**k clock = pygame.time.Clock() # Event loop while True: # Make sure the game doesn't run at more than 60 fps clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: paddle.move_left() elif event.key == pygame.K_RIGHT: paddle.move_right() if event.key == pygame.K_SPACE: ball.fire() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: paddle.stop(event.key) # Blit all objects onto background. screen.blit(background, paddle.rect, paddle.rect) screen.blit(background, ball.rect, ball.rect) for brick in bricks: screen.blit(background, brick.rect, brick.rect) screen.blit(background, (0, 0)) # Update all sprites. paddle_sprite.update() ball_sprite.update(paddle, bricks) brick_sprites.update() # Check for win if len(bricks) == 0: game_over(background, paddle, ball, bricks, 'You Win!') # Check for loss if ball.state == 'deleted': game_over(background, paddle, ball, bricks, 'Game Over.') # Draw all sprites. paddle_sprite.draw(screen) ball_sprite.draw(screen) brick_sprites.draw(screen) # Flip the display. pygame.display.flip()
def setUp(self): super(BallTestCase, self).setUp() self.ball = Ball(surf=self.display_surface, pos=self.default_pos, speed=settings.DEFAULT_SPEED)
class BallTestCase(ModelTestCase): def setUp(self): super(BallTestCase, self).setUp() self.ball = Ball(surf=self.display_surface, pos=self.default_pos, speed=settings.DEFAULT_SPEED) def test_hits_top_edge_returns_true(self): self.ball.top = settings.TOP_EDGE self.assertTrue(self.ball.hits_top_edge()) def test_hits_top_edge_returns_false(self): self.ball.top = settings.TOP_EDGE + 1 self.assertFalse(self.ball.hits_top_edge()) def test_hits_bottom_edge_returns_true(self): self.ball.bottom = settings.BOTTOM_EDGE self.assertTrue(self.ball.hits_bottom_edge()) def test_hits_bottom_edge_returns_false(self): self.ball.bottom = settings.BOTTOM_EDGE - 1 self.assertFalse(self.ball.hits_bottom_edge()) def test_reset_velocity_sets_to_default_speed(self): self.ball.velocity = (200, 200) self.ball.reset_velocity() default_velocity = [settings.DEFAULT_SPEED, settings.DEFAULT_SPEED] self.assertEqual(self.ball.velocity, default_velocity) def test_is_moving_left_when_velocity_x_less_than_zero(self): self.ball.velocity[0] = -1 self.assertTrue(self.ball.is_moving_left()) def test_not_moving_left_when_velocity_x_zero_or_greater(self): self.ball.velocity[0] = 0 self.assertFalse(self.ball.is_moving_left()) self.ball.velocity[0] = 1 self.assertFalse(self.ball.is_moving_left()) def test_is_moving_left_after_velocity_reset(self): self.ball.reset_velocity() self.assertTrue(self.ball.is_moving_left()) def test_is_moving_right_when_velocity_x_greater_than_zero(self): self.ball.velocity[0] = 1 self.assertTrue(self.ball.is_moving_right()) def test_not_moving_right_when_velocity_x_less_than_zero(self): self.ball.velocity[0] = 0 self.assertFalse(self.ball.is_moving_right()) self.ball.velocity[0] = -1 self.assertFalse(self.ball.is_moving_right()) @mock.patch('pygame.draw.rect') def test_render_draws_rectangle(self, mock_draw): self.ball.render() mock_draw.assert_called_with(self.ball.surf, self.ball.color, self.ball.rect)
class Pong: def __init__(self, leftPaddle, rightPaddle, ball, score, hit_wall_sound, hit_paddle_sound, color): self.color = color self.score = score self.leftPaddle = leftPaddle self.rightPaddle = rightPaddle self.ball = ball self.serve = self.serve_left self.hit_wall_sound = hit_wall_sound self.hit_paddle_sound = hit_paddle_sound def move_left_up(self): self.leftPaddle.move_up() def move_left_down(self): self.leftPaddle.move_down() def move_right_up(self): self.rightPaddle.move_up() def move_right_down(self): self.rightPaddle.move_down() def serve_left(self): self.ball = Ball(Config.ball_left_start_x, Config.ball_left_start_y, Config.ball_size, Config.ball_serve_left_vx, Config.ball_serve_left_vy) def serve_right(self): self.ball = Ball(Config.ball_right_start_x, Config.ball_right_start_y, Config.ball_size, Config.ball_serve_right_vx, Config.ball_serve_right_vy) def move_ball(self): if self.ball.y == 10 or self.ball.y == 490: self.ball.bounce_off_wall() self.hit_wall_sound.play() if self.ball.x == 30 and abs(self.leftPaddle.y - self.ball.y) < self.leftPaddle.size / 2: self.ball.bounce_off_paddle() self.hit_paddle_sound.play() if self.ball.x == 970 and abs(self.rightPaddle.y - self.ball.y) < self.rightPaddle.size / 2: self.ball.bounce_off_paddle() self.hit_paddle_sound.play() if self.ball.x < 0: self.ball = Ball(Config.ball_left_start_x, Config.ball_left_start_y, Config.ball_size, 0, 0) self.serve = self.serve_left self.score.increment_right() if self.ball.x > 1000: self.ball = Ball(Config.ball_right_start_x, Config.ball_right_start_y, Config.ball_size, 0, 0) self.serve = self.serve_right self.score.increment_left() self.ball.move() def draw(self, screen): def clear_screen(screen): screen.fill((0, 0, 0)) def draw_court(screen): rectangle = (495, 0, 10, 500) pygame.draw.rect(screen, self.color, rectangle) clear_screen(screen) draw_court(screen) self.ball.draw(screen, self.color) self.leftPaddle.draw(screen, self.color) self.rightPaddle.draw(screen, self.color) self.score.draw(screen, self.color) pygame.display.update()
tk = Tk() tk.title('Game') tk.resizable(0, 0) # window always in top position tk.wm_attributes('-topmost', 1) # main canvas of the game 500X400 canvas = Canvas(tk, width=500, height=400, bg='lightblue') canvas.pack() # update the main window with the canvas tk.update() score = Score(canvas, 'green') paddle = Paddle(canvas, 'white') ball = Ball(canvas, paddle, score, 'yellow') # while the ball doesn't hit bottom while not ball.hit_bottom: # if game started and paddle can move if paddle.started: # move the ball ball.draw() # move the paddle paddle.draw() # update the main window after drawing tk.update_idletasks() tk.update()