def make_balls(self, event): """Creates balls.""" ball_coords = [np.array(event.pos)] self.balls.append(objects.Ball(self.all_sprites, 10, ball_coords[0])) self.length.append([]) self.angles.append([]) for i in range(self.ball_number * 10): if len(self.balls) < self.ball_number: color = pygame.Color(np.random.randint(0, 255), np.random.randint(0, 255), np.random.randint(0, 255)) coords = ball_coords[0] + self.d_coord * (np.random.rand(2) - 0.5 * np.ones(2)) new_ball = objects.Ball(self.all_sprites, 10, coords, color=color) collide = False for obstacle in self.obstacles: if obstacle.collide(new_ball)[0]: collide = True break if not collide: self.balls.append(new_ball) self.length.append([]) self.angles.append([]) else: break
def subTest(): global ball1, ball2, mySys, fig, ax reload(objects) reload(system) ball1 = objects.Ball() ball2 = objects.Ball(pos=[-4, 0, 0], vel=[1, 0, 0]) cont = objects.Container(12) mySys = system.System([ball1, ball2], cont) fig = plt.figure() ax = plt.axes(xlim=(-20, 20), ylim=(-20, 20)) ax.axes.set_aspect('equal') mySys.init_system(ax) plt.show()
def __init__(self, surface): Setup.__init__(self, surface) ballX = random.randint(params.WIDTH * 0.1, params.WIDTH * 0.9) ballY = params.HEIGHT * 0.95 - objects.BALL_RADIUS dotAngle = 0.0 ball = objects.Ball(surface=self.surface, color=objects.BALL_COLOR, x=ballX, y=ballY, radius=objects.BALL_RADIUS, dotAngle=dotAngle, obstacles=[None]) diamondX = random.randint(2 * objects.DIAMOND_RADIUS, params.WIDTH - objects.DIAMOND_RADIUS) ## Initial diamond x diamondY = random.randint( params.HEIGHT * 0.5 + 2 * objects.DIAMOND_RADIUS, params.HEIGHT - objects.DIAMOND_RADIUS) ## Initial diamond y diamond = objects.Diamond(surface=self.surface, color=objects.DIAMOND_COLOR, x=diamondX, y=diamondY, radius=objects.DIAMOND_RADIUS) self.obstacles, self.ball, self.diamonds = ([None], ball, [diamond]) self.maxCollectTime = 3 ## Ideal max completion time in seconds to collect all diamond
def add_powers(power): flag = 0 if power != 3: for i in global_var.powers: if i[0] == power: i[1] = time() flag = 1 if flag == 0: if power == 1: global_var.paddle.expand() elif power == 2: global_var.paddle.shrink() elif power == 3: tempballs = global_var.balls.copy() for ball in tempballs: global_var.balls.append( objects.Ball(config.ball, ball.xget(), ball.yget(), 0, -ball._xspeed, -ball._yspeed)) elif power == 4: for ball in global_var.balls: ball.inc_speed() elif power == 5: global_var.paddle.set_thru(1) elif power == 6: global_var.paddle.set_grab(1) elif power == 7: global_var.paddle.set_laser(1) global_var.powers.append([power, time()])
def __init__(self, game): self.game = game # INITIALISE GRAPHICS: self.background = LoadInGraphics(constants.BACKGROUND_MENU, [0, 0]) # INITIALISE IN-GAME OBJECTS: self.ball = objects.Ball() self.right_paddle = objects.Paddle(265, 598, False) self.left_paddle = objects.Paddle(105, 598, True) self.playfield = objects.Playfield() self.spring = objects.Spring() self.deadzone = objects.Deadzone() self.point1 = objects.Point(50, 200) self.point2 = objects.Point(200, 230) self.point3 = objects.Point(190, 320) self.point4 = objects.Point(320, 450) self.point5 = objects.Point(238, 100) # list of object that feeds into the Ball's update method. Every object in this list is checked for collision # with the Ball. self.objects_list = [self.playfield, self.right_paddle, self.left_paddle, self.spring, self.deadzone, self.point1, self.point2, self.point3, self.point4, self.point5]
def __init__(self): print 'Initializing game.' #using pygame pygame.init() self.clock = pygame.time.Clock() self.paddle = o.Paddle() self.ball = o.Ball() self.block_container = o.BlockContainer() self.screen = s.Screen(pygame) self.input = i.Input(pygame)
def __init__(self, surface): Setup.__init__(self, surface) platformW = int(params.WIDTH * 0.10) platformH = int(params.HEIGHT * 0.30) platformX = int(params.WIDTH * 0.3 - platformW * 0.5) platformY = int(params.HEIGHT - platformH) platform1 = objects.Obstacle(surface=self.surface, color=objects.OBSTACLE_COLOR, rect=(platformX, platformY, platformW, platformH)) self.diamondX = platformX - objects.DIAMOND_RADIUS ## Initial diamond x self.diamondY = params.HEIGHT - objects.DIAMOND_RADIUS ## Initial diamond y diamond1 = objects.Diamond(surface=self.surface, color=objects.DIAMOND_COLOR, x=self.diamondX, y=self.diamondY, radius=objects.DIAMOND_RADIUS) platformW = int(params.WIDTH * 0.10) platformH = int(params.HEIGHT * 0.30) platformX = int(params.WIDTH * 0.7 - platformW * 0.5) platformY = int(params.HEIGHT - platformH) platform2 = objects.Obstacle(surface=self.surface, color=objects.OBSTACLE_COLOR, rect=(platformX, platformY, platformW, platformH)) self.diamondX = platformX + platformW + objects.DIAMOND_RADIUS ## Initial diamond x self.diamondY = params.HEIGHT - objects.DIAMOND_RADIUS ## Initial diamond y diamond2 = objects.Diamond(surface=self.surface, color=objects.DIAMOND_COLOR, x=self.diamondX, y=self.diamondY, radius=objects.DIAMOND_RADIUS) obstacles = [platform1, platform2] ballX = random.randint(params.WIDTH * 0.5, params.WIDTH * 0.55) ballY = params.HEIGHT * 0.95 - objects.BALL_RADIUS dotAngle = 0.0 ball = objects.Ball(surface=self.surface, color=objects.BALL_COLOR, x=ballX, y=ballY, radius=objects.BALL_RADIUS, dotAngle=dotAngle, obstacles=obstacles) diamonds = [diamond1, diamond2] self.obstacles, self.ball, self.diamonds = (obstacles, ball, diamonds) self.maxCollectTime = 9 ## Ideal max completion time in seconds to collect all diamond
def default(): global_var.powers = [] global_var.balls = [ objects.Ball(config.ball, global_var.paddle.xget(), config.rows - 4, 1, 0, 1) ] if global_var.paddle.get_width() != 9: global_var.paddle.set_width(9) global_var.paddle.set_thru(0) global_var.paddle.set_grab(0) global_var.paddle.set_laser(0)
def update_world(t, world): """updates the world t: time in seonds since world started world: list of objects """ last_time = world["time"] delta_t = t - last_time objs = world["objects"] new_world = {} for obj in objs: obj.move(delta_t) new_objects = list(filter(lambda x: x.alive, objs)) if random.random() > 0.99: print("new Ball") new_object = objects.Ball() new_object.init_random(world["boundary"]) new_objects.append(new_object) if random.random() > 0.99: print("new Glider") new_object = objects.Glider() new_object.init_random(world["boundary"]) new_objects.append(new_object) if random.random() > 0.99: print("new Grower") new_object = objects.Grower() new_object.init_random(world["boundary"]) new_object.size = 0.1 new_object.max_size = 0.6 new_objects.append(new_object) if random.random() > 0.99: print("new Ring") new_object = objects.Ring() new_object.init_random(world["boundary"]) new_objects.append(new_object) if random.random() > 0.99: print("new Color") new_object = objects.Color() new_object.ttl = 1.0 new_object.random_color() new_objects.append(new_object) new_world["time"] = t new_world["objects"] = new_objects new_world["boundary"] = world["boundary"] return new_world
def __init__(self, player, confile=".pong.conf"): self.confy = Configuration(confile) self.ball = objects.Ball(self.confy) self.player = player self.borders = objects.Borders(self.confy) self.paddle_1 = objects.Paddle(self.confy, 1) self.paddle_2 = objects.Paddle(self.confy, 2) self.game_functions = functions.Game(self.confy, self.paddle_1, self.paddle_2, self.ball, self.player) self.score_1 = objects.Score(self.confy, self.ball, True) self.score_2 = objects.Score(self.confy, self.ball, False) # Init game screen pygame.init() pygame.display.set_caption("Object Oriented Pong") self.surface = pygame.display.set_mode( (self.confy.width, self.confy.height))
def basicTest(): """Animate a single ball in a container""" global ball1, ball2, mySys, fig, ax reload(objects) reload(system) # ball1 does circular motion because it looks cool # ball1 = objects.Ball(pos=[-10.99, 0, 0], vel=[0, 6, 0]) ball2 = objects.Ball(pos=[-4, 0, 0], vel=[5, 1, 0]) cont = objects.Container(12) # mySys = system.System([ball1], cont) mySys = system.System([ball2], cont) fig = plt.figure() ax = plt.axes(xlim=(-20, 20), ylim=(-20, 20)) ax.axes.set_aspect('equal') mySys.init_system(ax) anim = animation.FuncAnimation(fig, mySys.next_frame, interval=20, blit=True) plt.show()
def make_map(self, level): """ Creates all game objects. Then calls draw_on_field method to blit them to field. After that calls save_map function to save the map. """ self.ball = objects.Ball(self.all_sprites, 10, self.map_data[0]) self.cue = objects.Cue(self.all_sprites, self.ball.pos, max_vel=15) self.pocket = objects.Pocket(self.all_sprites, 10, self.map_data[1]) # edges of the field self.obstacles = [ objects.Obstacle(self.all_sprites, WINDOW_SIZE, self.map_data[2]) ] # obstacles on the field for i, obstacle in enumerate(self.map_data[3]): self.obstacles.append( objects.Obstacle(self.all_sprites, WINDOW_SIZE, self.map_data[3][i], fill_color=pygame.Color("white"))) self.draw_on_field() data.save_map(self.field.subsurface(self.obstacles[0].polygon_rect), level)
def play_game(surface): move_up, move_down, move_left, move_right = False, False, False, False ball_image = pygame.image.load('images/ball.png') vertical_paddle_image = pygame.image.load('images/vertical_paddle.png') horizontal_paddle_image = pygame.image.load('images/horizontal_paddle.png') ball = objects.Ball(x=400, y=250, velocity=(5, 0), image=ball_image) player = objects.Score() computer = objects.Score() player_paddles = [] player_paddles.append( objects.Paddle(SCR_WIDTH - vertical_paddle_image.get_rect().right, 250, vertical_paddle_image)) computer_paddles = [] computer_paddles.append(objects.Paddle(0, 250, vertical_paddle_image)) no_winner = True while no_winner: # Check for winner if player.game_point == 3 or computer.game_point == 3: no_winner = False # Display winner # Play again draw_text(surface, 'Play again? (Press Y or N)', SCR_WIDTH / 2 - 136, SCR_HEIGHT / 2 - 40) pygame.display.update() play_again = False while not play_again: for event in pygame.event.get(): if event.type == KEYUP: if event.key == K_y: player.reset() computer.reset() no_winner = True play_again = True break elif event.key == K_n: pygame.quit() sys.exit() # Check game score if player.point >= 11 and player.point - computer.point >= 2: player.game_point += 1 player.point, computer.point = 0, 0 if computer.point >= 11 and computer.point - player.point >= 2: computer.game_point += 1 player.point, computer.point = 0, 0 ball.update() if ball.y < 0 or ball.y + ball.image_rect.bottom >= SCR_HEIGHT - SCORES_HEIGHT: if ball.x + ball.image_rect.centerx <= SCR_WIDTH / 2: player.point += 1 else: computer.point += 1 reset_ball(ball) if ball.x < 0: player.point += 1 reset_ball(ball) if ball.x + ball.image_rect.right > SCR_WIDTH: computer.point += 1 reset_ball(ball) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_UP: move_up = True if event.key == K_DOWN: move_down = True if event.type == KEYUP: if event.key == K_UP: move_up = False if event.key == K_DOWN: move_down = False # Move paddles if move_up: for paddle in player_paddles: if paddle.vertical: if paddle.y > 0: paddle.y -= 10 if move_down: for paddle in player_paddles: if paddle.vertical: if paddle.y + paddle.image_rect.bottom < SCR_HEIGHT - SCORES_HEIGHT: paddle.y += 10 # Check for collision ball_rect = pygame.Rect(ball.x, ball.y, ball.image_rect.right, ball.image_rect.bottom) for paddle in player_paddles: paddle_rect = pygame.Rect(paddle.x, paddle.y, paddle.image_rect.right, paddle.image_rect.bottom) if ball_rect.colliderect(paddle_rect): if paddle.vertical: ball.velocity.x *= -1 for paddle in computer_paddles: paddle_rect = pygame.Rect(paddle.x, paddle.y, paddle.image_rect.right, paddle.image_rect.bottom) if ball_rect.colliderect(paddle_rect): if paddle.vertical: ball.velocity.x *= -1 print((ball.x, ball.y)) print((ball_rect.x, ball_rect.y)) surface.fill(BLACK) pygame.draw.line(surface, WHITE, (0, SCR_HEIGHT - SCORES_HEIGHT), (SCR_WIDTH, SCR_HEIGHT - SCORES_HEIGHT)) pygame.draw.line(surface, WHITE, (SCR_WIDTH / 2, 0), (SCR_WIDTH / 2, SCR_HEIGHT - SCORES_HEIGHT)) draw_text(surface, 'Player: {}'.format(player.point), x=SCR_WIDTH / 2, y=SCR_HEIGHT - SCORES_HEIGHT) draw_text(surface, 'Game point: {}'.format(player.game_point), x=SCR_WIDTH / 2, y=SCR_HEIGHT - SCORES_HEIGHT + 40) draw_text(surface, 'Computer: {}'.format(computer.point), x=0, y=SCR_HEIGHT - SCORES_HEIGHT) draw_text(surface, 'Game point: {}'.format(computer.game_point), x=0, y=SCR_HEIGHT - SCORES_HEIGHT + 40) surface.blit(ball_image, (ball.x, ball.y)) for paddle in computer_paddles: surface.blit(paddle.image, (paddle.x, paddle.y)) for paddle in player_paddles: surface.blit(paddle.image, (paddle.x, paddle.y)) pygame.display.update() time.sleep(0.017)
def game_start(): global run, scene, lawrence, sc, ents, clock, lag, restart restart = False scene = scenery.Scenery() lawrence = person.Person() for x in xrange(6, 500): if x % 2 == 0: if x < 100: y = random.randint(0, 7) if y == 1: ents.append(objects.Bird((x * 90) + random.randint(0, 40))) elif y == 2: ents.append(objects.Ball((x * 90) + random.randint(0, 40))) elif y == 3: ents.append(objects.Cone((x * 90) + random.randint(0, 40))) elif y == 4: ents.append( objects.Hurdle((x * 90) + random.randint(0, 40))) elif y == 5: z = random.randint(1, 3) if z == 1: ents.append( objects.Pizza((x * 90) + random.randint(0, 40))) elif z == 2: ents.append( objects.Hamburger((x * 90) + random.randint(0, 40))) elif z == 3: ents.append( objects.Cheesecake((x * 90) + random.randint(0, 40))) elif y == 6: z = random.randint(1, 3) if z == 1: ents.append( objects.Celery((x * 90) + random.randint(0, 40))) elif z == 2: ents.append( objects.Carrot((x * 90) + random.randint(0, 40))) elif z == 3: ents.append( objects.Apple((x * 90) + random.randint(0, 40))) elif x >= 100 and x < 300: y = random.randint(0, 7) if y == 1: ents.append(objects.Bird((x * 85) + random.randint(0, 40))) elif y == 2: ents.append(objects.Ball((x * 85) + random.randint(0, 40))) elif y == 3: ents.append(objects.Cone((x * 85) + random.randint(0, 40))) elif y == 4: ents.append( objects.Hurdle((x * 85) + random.randint(0, 40))) elif y == 5: ents.append(objects.Cone(x * 85)) ents.append(objects.Cone((x * 85) + 20)) elif y == 6: z = random.randint(1, 3) if z == 1: ents.append( objects.Pizza((x * 85) + random.randint(0, 40))) elif z == 2: ents.append( objects.Hamburger((x * 85) + random.randint(0, 40))) elif z == 3: ents.append( objects.Cheesecake((x * 85) + random.randint(0, 40))) elif y == 7: z = random.randint(1, 3) if z == 1: ents.append( objects.Celery((x * 85) + random.randint(0, 40))) elif z == 2: ents.append( objects.Carrot((x * 85) + random.randint(0, 40))) elif z == 3: ents.append( objects.Apple((x * 85) + random.randint(0, 40))) elif x >= 300: y = random.randint(0, 6) if y == 1: ents.append(objects.Bird((x * 80) + random.randint(0, 40))) elif y == 2: ents.append(objects.Ball((x * 80) + random.randint(0, 40))) elif y == 3: ents.append(objects.Cone((x * 80) + random.randint(0, 40))) elif y == 4: ents.append( objects.Hurdle((x * 80) + random.randint(0, 40))) elif y == 5: ents.append(objects.Cone(x * 80)) ents.append(objects.Cone((x * 80) + 20)) elif y == 6: ents.append(objects.Cone(x * 80)) ents.append(objects.Cone((x * 80) + 20)) ents.append(objects.Cone((x * 80) + 40)) elif y == 7: z = random.randint(1, 3) if z == 1: ents.append( objects.Pizza((x * 80) + random.randint(0, 40))) elif z == 2: ents.append( objects.Hamburger((x * 80) + random.randint(0, 40))) elif z == 3: ents.append( objects.Cheesecake((x * 80) + random.randint(0, 40))) elif y == 8: z = random.randint(1, 3) if z == 1: ents.append( objects.Celery((x * 80) + random.randint(0, 40))) elif z == 2: ents.append( objects.Carrot((x * 80) + random.randint(0, 40))) elif z == 3: ents.append( objects.Apple((x * 80) + random.randint(0, 40))) graphics.register(scene) graphics.register(lawrence) graphics.register(sc) for e in ents: graphics.register(e) clock = pygame.time.Clock() lag = 0 if con.audio_support: pygame.mixer.music.play(-1) audio.yay_sound.play()
# bomb=objects.Bomb(config.Bombo,boss._posx+3, paddle_ground-33) a = 10 Thru_Ball = objects.thruball(config.powerup_Thru_Ball, 10, 6) b = 20 exp_paddle = objects.expand(config.powerup_ExpandPaddle, 20, 6) shoot_paddle = objects.shoot(config.powerup_ShootPaddle, 45, 17) c = 55 shrink_paddle = objects.shrink(config.powerup_ShrinkPaddle, 55, 16) d = 65 fast_ball = objects.fastball(config.powerup_fastball, 65, 16) e = 75 paddle_grab = objects.grab(config.powerup_grab, 75, 16) # multiplier=objects.multiplier(config.powerup_multiplier,75,16) ball = objects.Ball(config.ball, paddle.xget() + 4, paddle.yget() - 1) redbricks = [] bluebricks = [] greenbricks = [] rainbowbricks = [] graybricks = [] magentabricks = [] ########## LEVEL1 ############ j = 5 for i in range(0, 9): brck = objects.RedBricks(j, 6) redbricks.append(brck) j += 10
def update(self, events): """Handles the events.""" for event in events: if event.type == pygame.MOUSEMOTION: if self.stage == 0: if len(self.obstacles) > self.obstacle_number \ and len(self.obstacles[self.obstacle_number].vertices) > 0: start_pos = [ self.obstacles[self.obstacle_number].vertices[-1], self.obstacles[self.obstacle_number].vertices[0] ] self.line_pos = [[start_pos[0], event.pos], [start_pos[1], event.pos]] if event.type == pygame.MOUSEBUTTONDOWN: if event.pos[1] < WINDOW_HEIGHT - 50 * 3 // 2: if event.button == 1: if self.stage == 0: if len(self.obstacles) <= self.obstacle_number: self.obstacles.append( objects.Obstacle( self.all_sprites, WINDOW_SIZE, np.array(event.pos, ndmin=2))) else: if self.obstacle_number: fill_color = pygame.Color("white") else: fill_color = pygame.Color("#0060ff") new_vertices = np.concatenate( (self.obstacles[self.obstacle_number]. vertices, np.array(event.pos, ndmin=2)), axis=0) self.obstacles[ self.obstacle_number] = objects.Obstacle( self.all_sprites, WINDOW_SIZE, new_vertices, fill_color=fill_color) elif self.stage == 1: self.pocket = objects.Pocket( self.all_sprites, 10, event.pos) elif self.stage == 2: self.ball = objects.Ball(self.all_sprites, 10, event.pos) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: if self.stage == 0 and len(self.obstacles) > 0 or \ self.stage == 1 and self.pocket is not None or\ self.stage == 2 and self.ball is not None: self.stage += 1 elif event.key == pygame.K_LEFT: if self.stage >= 1: self.stage -= 1 elif event.key == pygame.K_SPACE: if self.stage == 0 and len( self.obstacles) > self.obstacle_number: if len(self.obstacles[self.obstacle_number].vertices ) > 2: # if obstacle is at least a line self.obstacle_number += 1 self.line_pos = [] else: self.obstacles.pop() if self.stage == 3: data.save_level_data(self) data.save_map( self.field.subsurface(self.obstacles[0].polygon_rect), self.level) data.make_level_button_theme(self.level)
max_z = 0.0 for coord in coordinates: x, y, z = coord min_x = min(x, min_x) min_y = min(y, min_y) min_z = min(z, min_z) max_x = max(x, max_x) max_y = max(y, max_y) max_z = max(z, max_z) min_coord = (min_x, min_y, min_z) max_coord = (max_x, max_y, max_z) bound = (min_coord, max_coord) red_ball = objects.Ball((0, 0, 0), (0.0, 0, -0.0), (1, 0, 0), 0.3, 20) blue_ball = objects.Ball((2, 0, 0), (-0.3, 0, 0.05), (0, 0, 1), 0.4, 20) green_ball = objects.Ball((0, 0, 0), (-0.02, 0, 0.1), (0, 1, 0), 0.5, 20) glider = objects.Glider((min_x, 0, max_z), (1.5, 0, 0), (0.8, 0.8, 0.8), 0.2, 4) ring = objects.Ring((min_x, 0, max_z), (1.5, 0, 0), (0.8, 0.8, 0.8), 0.2, 4) world = {"time": 0, "boundary": bound, "objects": [ring]} while True: t = time.time() - start_time world = update_world(t, world) pixels = [ pixel_color(t, coord, ii, n_pixels, world, bound) for ii, coord in enumerate(coordinates) ]
def play_game(surface): main_clock = pygame.time.Clock() move_up, move_down, move_left, move_right = False, False, False, False # Set up images and ball ball_image = pygame.image.load('images/ball.png') vertical_paddle_image = pygame.image.load('images/vertical_paddle.png') horizontal_paddle_image = pygame.image.load('images/horizontal_paddle.png') cpu_vertical_paddle_image = pygame.image.load( 'images/cpu_vertical_paddle.png') cpu_horizontal_paddle_image = pygame.image.load( 'images/cpu_horizontal_paddle.png') ball = objects.Ball(image=ball_image) reset_ball(ball) # Set up paddles player = objects.Score() computer = objects.Score() player_paddles = [ objects.Paddle(SCR_WIDTH - vertical_paddle_image.get_rect().right, 250, vertical_paddle_image), objects.Paddle(round(SCR_WIDTH * 0.75), 0, horizontal_paddle_image, vertical=False), objects.Paddle(round(SCR_WIDTH * 0.75), SCR_HEIGHT - SCORES_HEIGHT - horizontal_paddle_image.get_rect().bottom, horizontal_paddle_image, vertical=False) ] computer_paddles = [ objects.Paddle(0, 250, cpu_vertical_paddle_image), objects.Paddle(round(SCR_WIDTH * 0.25), 0, cpu_horizontal_paddle_image, vertical=False), objects.Paddle(round(SCR_WIDTH * 0.25), SCR_HEIGHT - SCORES_HEIGHT - cpu_horizontal_paddle_image.get_rect().bottom, cpu_horizontal_paddle_image, vertical=False) ] # Set up sounds ball_sound = pygame.mixer.Sound('audio/pickup.wav') game_over = pygame.mixer.Sound('audio/gameover.wav') game_win = pygame.mixer.Sound('audio/game_win.wav') game_lose = pygame.mixer.Sound('audio/game_lose.wav') no_winner = True while no_winner: pygame.mixer.music.stop() # Check for winner if player.game_point == 3 or computer.game_point == 3: no_winner = False # Display winner if player.game_point == 3: draw_text(surface, 'YOU WON!!!', SCR_WIDTH / 2 - 120, SCORES_HEIGHT, size=50) pygame.mixer.music.load('audio/victory.mid') pygame.mixer.music.play() elif computer.game_point == 3: draw_text(surface, 'YOU LOST!!!', SCR_WIDTH / 2 - 130, SCORES_HEIGHT, size=50) game_over.play() # Play again draw_text(surface, 'Play again? (Press Y or N)', SCR_WIDTH / 2 - 136, SCR_HEIGHT / 2 - 40) pygame.display.update() play_again = False while not play_again: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYUP: if event.key == K_y: player.reset() computer.reset() no_winner = True play_again = True reset_ball(ball) break elif event.key == K_n: pygame.quit() sys.exit() # Check game score if player.point >= 11 and player.point - computer.point >= 2: player.game_point += 1 if player.game_point < 3: game_win.play() time.sleep(0.7) player.point, computer.point = 0, 0 if computer.point >= 11 and computer.point - player.point >= 2: computer.game_point += 1 if computer.game_point < 3: game_lose.play() time.sleep(0.7) player.point, computer.point = 0, 0 # Update ball ball.move() if ball.rect.y + ball.image_rect.centery < 0 \ or ball.rect.y + ball.image_rect.centery >= SCR_HEIGHT-SCORES_HEIGHT: if ball.rect.x + ball.image_rect.centerx <= SCR_WIDTH / 2: player.point += 1 else: computer.point += 1 reset_ball(ball) if ball.rect.x + ball.image_rect.centerx < 0: player.point += 1 reset_ball(ball) if ball.rect.x + ball.image_rect.centerx > SCR_WIDTH: computer.point += 1 reset_ball(ball) # Get input for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_UP: move_up = True if event.key == K_DOWN: move_down = True if event.key == K_RIGHT: move_right = True if event.key == K_LEFT: move_left = True if event.type == KEYUP: if event.key == K_UP: move_up = False # player.point += 1 if event.key == K_DOWN: # computer.point += 1 move_down = False if event.key == K_RIGHT: move_right = False if event.key == K_LEFT: move_left = False # Move player's paddles if move_up: for paddle in player_paddles: if paddle.vertical: if paddle.rect.y > 0: paddle.rect.y -= MOVESPEED else: paddle.rect.y = 0 if move_down: for paddle in player_paddles: if paddle.vertical: if paddle.rect.y + paddle.image_rect.bottom < SCR_HEIGHT - SCORES_HEIGHT: paddle.rect.y += MOVESPEED else: paddle.rect.y = SCR_HEIGHT - SCORES_HEIGHT - paddle.image_rect.bottom if move_left: for paddle in player_paddles: if not paddle.vertical: if paddle.rect.x > SCR_WIDTH / 2: paddle.rect.x -= MOVESPEED else: paddle.rect.x = SCR_WIDTH / 2 if move_right: for paddle in player_paddles: if not paddle.vertical: if paddle.rect.x + paddle.image_rect.right < SCR_WIDTH: paddle.rect.x += MOVESPEED else: paddle.rect.x = SCR_WIDTH - paddle.image_rect.right # Move computer's paddles for paddle in computer_paddles: if paddle.vertical: if ball.rect.y + ball.image_rect.centery < paddle.rect.y + paddle.image_rect.centery - 12: if paddle.rect.y > 0: paddle.rect.y -= (MOVESPEED - 1.5) else: paddle.rect.y = 0 elif ball.rect.y + ball.image_rect.centery > paddle.rect.y + paddle.image_rect.centery + 12: if paddle.rect.y + paddle.image_rect.bottom < SCR_HEIGHT - SCORES_HEIGHT: paddle.rect.y += (MOVESPEED - 1.5) else: paddle.rect.y = SCR_HEIGHT - SCORES_HEIGHT - paddle.image_rect.bottom else: if ball.rect.x + ball.image_rect.centerx < paddle.rect.x + paddle.image_rect.centerx - 12: if paddle.rect.x > 0: paddle.rect.x -= (MOVESPEED - 1.5) else: paddle.rect.x = 0 elif ball.rect.x + ball.image_rect.centerx > paddle.rect.x + paddle.image_rect.centerx + 12: if paddle.rect.x + paddle.image_rect.right < SCR_WIDTH / 2: paddle.rect.x += (MOVESPEED - 1.5) else: paddle.rect.x = SCR_WIDTH / 2 - paddle.image_rect.right # Check for collision for paddle in player_paddles: # player's paddles if ball.rect.colliderect(paddle.rect): if paddle.vertical: # Adjust the ball before bouncing back ball.rect.x = paddle.rect.x - ball.image_rect.right ball.velocity.x *= -1 else: # Adjust the ball before bouncing back if paddle.rect.y < 1: # upper horizontal paddle ball.rect.y = paddle.rect.y + paddle.image_rect.bottom else: # lower horizontal paddle ball.rect.y = paddle.rect.y - ball.image_rect.bottom ball.velocity.y *= -1 ball_sound.play() for paddle in computer_paddles: # computer's paddles if ball.rect.colliderect(paddle.rect): if paddle.vertical: # Adjust the ball before bouncing back ball.rect.x = paddle.rect.x + paddle.image_rect.right ball.velocity.x *= -1 else: # Adjust the ball before bouncing back if paddle.rect.y < 1: # upper horizontal paddle ball.rect.y = paddle.rect.y + paddle.image_rect.bottom else: # lower horizontal paddle ball.rect.y = paddle.rect.y - ball.image_rect.bottom ball.velocity.y *= -1 ball_sound.play() # Draw the screen surface.fill(BLACK) pygame.draw.line(surface, WHITE, (0, SCR_HEIGHT - SCORES_HEIGHT), (SCR_WIDTH, SCR_HEIGHT - SCORES_HEIGHT)) pygame.draw.line(surface, WHITE, (SCR_WIDTH / 2, 0), (SCR_WIDTH / 2, SCR_HEIGHT - SCORES_HEIGHT)) # Draw the scores # Calculate points to win current game point_to_win_game = [ 11, 11 ] # 1st element is player's point to win game, 2nd element is computer's point_to_win_game[0] = 2 + computer.point if ( computer.point >= 10) else 11 point_to_win_game[1] = 2 + player.point if (player.point >= 10) else 11 # Player's scores draw_text(surface, 'Player: {} ({} to win game)'.format(player.point, point_to_win_game[0]), x=SCR_WIDTH / 2, y=SCR_HEIGHT - SCORES_HEIGHT) draw_text(surface, 'Game point: {} (3 to win match)'.format(player.game_point), x=SCR_WIDTH / 2, y=SCR_HEIGHT - SCORES_HEIGHT + 40) # Computer's score draw_text(surface, 'Computer: {} ({} to win game)'.format( computer.point, point_to_win_game[1]), x=0, y=SCR_HEIGHT - SCORES_HEIGHT) draw_text(surface, 'Game point: {} (3 to win match)'.format( computer.game_point), x=0, y=SCR_HEIGHT - SCORES_HEIGHT + 40) # Draw the ball and paddles surface.blit(ball_image, (ball.rect.x, ball.rect.y)) for paddle in computer_paddles: surface.blit(paddle.image, (paddle.rect.x, paddle.rect.y)) for paddle in player_paddles: surface.blit(paddle.image, (paddle.rect.x, paddle.rect.y)) pygame.display.update() main_clock.tick(60)
s.set_alpha(colour[3]) # alpha level s.fill(colour[:3]) # this fills the entire surface surface.blit(s, (x, y)) # (0,0) are the top-left coordinates # Initiate player variables score = 0 maxLives = 2 lives = 2 # Initialize game objects bat = objects.Bat( centreX, windowHeight - 25, pygame, surface, 100, 15) # Will make this wider when more complex bouncing is added ball = objects.Ball(pygame, surface, 15, bat) # Initialise buttons resumeButton = objects.Button(pygame, surface, colours.black, colours.white, (100, 200, 100, 50), "Resume", ubuntuFontSmall) def loseLife(): global lives lives -= 1 if lives < 0: setState(gameOver) else: ball.setSpeed() setState(onBat)
def main_game(difficulty): ''' This method contains the main game. You should give it one parameter; the difficulty, as a number counting from 1 up to and including 3. ''' # Create blocks s.total_layers = 2**difficulty s.blocksspace = s.BOTTOM_MARGIN-s.TOP_MARGIN s.blockheight = s.blocksspace/s.total_layers s.blockwidth = int(s.WIDTH/(10*difficulty-6)) blocks = [] blocktops, blockbottoms, blocklefts, blockrights = [], [], [], [] for row in range(s.total_layers): for collunm in range(s.WIDTH//s.blockwidth): blocks.append(objects.Block(collunm*s.blockwidth, (row*s.blockheight) + s.TOP_MARGIN, s.blockwidth, s.blockheight, row, s.total_layers)) blocktops.append(blocks[len(blocks)-1].top) blockbottoms.append(blocks[len(blocks)-1].bottom) blocklefts.append(blocks[len(blocks)-1].left) blockrights.append(blocks[len(blocks)-1].right) begin_blockscount = len(blocks) # Create a paddle and ball paddle = objects.Paddle((s.WIDTH/2)-(s.PADDLE_WIDTH/2), s.HEIGHT-50, s.PADDLE_WIDTH, 15, s.paddle_image) ball = objects.Ball(s.WIDTH/2, s.BOTTOM_MARGIN+s.HEIGHT/10, s.BALL_SPEED, 10, s.ball_image, s.bounce_sound) start = time.time() # Main loop run = True while run: s.fpsClock.tick(60) s.win.fill(s.BLACK) score = int(begin_blockscount-len(blocks)-((time.time()-start)/(difficulty*10))) + 1 score_text = s.normal_font.render(str(score), True, s.WHITE) s.win.blit(score_text, (s.WIDTH-score_text.get_width()-10, s.HEIGHT-score_text.get_height()-10)) # Paddle control if pygame.mouse.get_pos()[0] > 0+(s.PADDLE_WIDTH/2) and pygame.mouse.get_pos()[0] < s.WIDTH-(s.PADDLE_WIDTH/2): paddle.control((difficulty-1)*50, (time.time()-start)) elif pygame.mouse.get_pos()[0] < 0+(s.PADDLE_WIDTH/2): paddle.x = 0 elif pygame.mouse.get_pos()[0] > s.WIDTH-(s.PADDLE_WIDTH/2): paddle.x = s.WIDTH-paddle.width paddle.draw() # Block control if len(blocks) == 0: scenes.win(score) return for block in blocks: block.draw() # Ball control if ball.rect.collidelist(blocks) != -1: ball.collided_block = ball.rect.collidelist(blocks) if blocks[ball.collided_block].layer == 0: ball.speed = s.BALL_SPEED+difficulty*2 elif ball.speed != s.BALL_SPEED+difficulty: ball.speed = s.BALL_SPEED+difficulty + (ball.speed-s.BALL_SPEED)*0.5 if blocktops[ball.collided_block].colliderect(ball.rect): ball.bounce_top() elif blockbottoms[ball.collided_block].colliderect(ball.rect): ball.bounce_bottom() elif blocklefts[ball.collided_block].colliderect(ball.rect): ball.bounce_left() elif blockrights[ball.collided_block].colliderect(ball.rect): ball.bounce_right() del blocks[ball.collided_block] del blocktops[ball.collided_block] del blockbottoms[ball.collided_block] del blocklefts[ball.collided_block] del blockrights[ball.collided_block] # Reset ball position if pygame.key.get_pressed()[pygame.K_r]: ball = objects.Ball(s.WIDTH/2, s.BOTTOM_MARGIN+s.HEIGHT/10, s.BALL_SPEED, 10, s.ball_image, s.bounce_sound) # Ball and paddle collide if pygame.sprite.collide_rect(ball, paddle): ball.alpha = np.random.uniform(0, -np.pi) if ball.rect.colliderect(paddle.leftrect): ball.bounce_left() elif ball.rect.colliderect(paddle.rightrect): ball.bounce_right() if (ball.rect.y+(ball.radius*2)) >= s.HEIGHT: scenes.death(score) return ball.update() ball.draw() if pygame.key.get_pressed()[pygame.K_ESCAPE]: pause = scenes.pause(pygame.display.get_surface()) if pause: return s.check_closed() pygame.display.update()
import game_screen import objects import config import random import utilities from time import time mp = game_screen.Map() last_bomb = 0 last_laser = 0 cd = 1 level = 1 pause = 0 breakable_bricks = [11, 12, 15] bosses = [] bombs = [] lasers = [] balls = [] bricks = [] powers = [] power_ups = [] paddle = objects.Paddle(config.paddle, 5, config.rows - 3) ball = objects.Ball(config.ball, 5, config.rows - 4, 1, 0, 1) balls.append(ball)
TIME_START = 0 TIME_TOTAL = 180 TIME_POWERUP = 10 lvl1bricks = [] lvl2bricks = [] lvl3bricks = [] lvl4bricks = [] #temp pu = 5 bricks = 0 powerups = [] #game map mp = board.Map() paddle = objects.Paddle(config.paddle, int(int(config.columns) / 2) - 3, mp.height - 2, 0) ball = objects.Ball(config.ball, int(int(config.columns) / 2), mp.height - 3, 0, 0) balls = [] #game play # gp = objects.GamePlay() gp = objects.GamePlay(0, 3)