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 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 __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 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 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 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 on_init(self): Engine.on_init(self) self.winner_text = Text(self.width/4, 80, str(""), 30) self.add(self.winner_text) self.start_game_text = Text(self.width/3, 120, str("Press START"), 30) self.add(self.start_game_text) self.scoreP1_text = Text(self.width/4, 30, str(self.scoreP1), 50) self.scoreP2_text = Text(self.width - self.width/4, 30, str(self.scoreP2), 50) self.add(self.scoreP1_text) self.add(self.scoreP2_text) self.fps_text = Text(280, 220, "30") self.add(self.fps_text) self.ball = Ball(self.width/2, self.height/2, "ball.png") self.add(self.ball) self.playerOne = Paddle(20, self.height/2, "paddle.png") self.add(self.playerOne) self.playerTwo = Paddle(320 - 20, self.height/2, "paddle.png") self.add(self.playerTwo) self.sfx_padOne = soundEffect("blip1.wav") self.sfx_padTwo = soundEffect("blip2.wav") self.music_bg = musicPlayer("UGH1.wav", -1) self.music_bg.play() self.start_game(False)
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 __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 end(self, paddle: Paddle, balls: list[Ball]) -> None: paddle.size = Vector2(paddle.size.x - 10, paddle.size.y) paddle.image = '#' * paddle.size.x paddle.makeSprite() for ball in balls: if ball.grabbed: ball.position.x = min(ball.position.x, paddle.position.x + paddle.size.x - 2)
def start(self, paddle: Paddle, balls: list[Ball]) -> None: if paddle.size.x + 10 < 50: paddle.size = Vector2(paddle.size.x + 10, paddle.size.y) else: self.active = False return paddle.image = '#' * paddle.size.x paddle.makeSprite() self.timer = 100
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 __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 __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 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)
class DumbComputerPlayer: def __init__(self, x, y, ball, surface): self.paddle = Paddle(x, y, math.floor(surface.get_width() * 0.2), math.floor(surface.get_height() * 0.05), surface) self.ball = ball self.score = 0 def play(self): if self.paddle.rect.centerx < self.ball.x: self.paddle.move(1) elif self.paddle.rect.centerx > self.ball.x: self.paddle.move(-1) def collide(self): return
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): 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 __init__(self): #creates the window, the ball, the two paddles, and draws the background and the scoreboard. self.win = GraphWin("Pong", 800, 400) self.background = Image(Point(400,200),"pingpong.gif") self.background.draw(self.win) self.ball=Ball(self.win) self.paddle = Paddle(self.win,740,150,750,250,"red") self.paddle1 = Paddle(self.win, 60, 150,70,250,"blue") self.radius = self.ball.getRadius() self.scoreboard = Text(Point(400, 50), "") self.scoreboard.setSize(12) self.scoreboard.setTextColor("white") self.scoreboard.draw(self.win) y = 200 self.middle = self.paddle.move(self.win, y) self.middle1 = self.paddle1.move(self.win,y)
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 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): # 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)
class PaddleEnv(gym.Env): 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 _next_observation(self): # Get the state of the environment p_xcor = self.game.paddle.xcor() b_xcor = self.game.ball.xcor() b_ycor = self.game.ball.ycor() # normalize the state to -1 to 1 state = [ p_xcor / 300, b_xcor / 300, b_ycor / 300, (p_xcor - b_xcor) / 600, self.game.ball.dx / 4, self.game.ball.dy / 3 ] state = np.reshape(state, (1, 6)) return state def reset(self): # Reset the state of the environment to an initial state self.game.reset() return self._next_observation() def step(self, action): # Execute one time step within the environment reward = 0 if action == 0: self.game.movement(action='left') reward -= 0.01 elif action == 2: self.game.movement(action='right') reward -= 0.01 hit, done = self.game.run_frame() if (hit): reward += 10 elif (done): reward -= 10 state = self._next_observation() return state, reward, done, {} def render(self): pass def close(self): pass
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 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): # initialization pygame.init() self.size = SCREEN_WIDTH, SCREEN_HEIGHT self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption("3D Pongbreaker Host") # create game objects self.background = self.create_background() self.paddle_1 = Paddle(PADDLE_BUFFER, 'host', self) self.paddle_2 = Paddle((HALLWAY_DEPTH - PADDLE_BUFFER), 'client', self) self.bc = BrickCreator(self) self.bricks = self.bc.get_bricks(BRICK_POS_FN) self.balls = set() self.balls.add(Ball(self.paddle_1.rect.center, (self.paddle_1.z_pos + 1), 1, self)) self.balls.add(Ball(self.paddle_2.rect.center, (self.paddle_2.z_pos - 1), 2, self)) self.title_font = pygame.font.Font(None, TITLE_FONT_SIZE) self.paddle_1_title_text = self.title_font.render('Player 1', False, TEXT_COLOR) self.paddle_2_title_text = self.title_font.render('Player 2', False, TEXT_COLOR) self.paddle_1_title_rect = self.paddle_1_title_text.get_rect() self.paddle_2_title_rect = self.paddle_2_title_text.get_rect() self.score_font = pygame.font.Font(None, SCORE_FONT_SIZE)
class Engine: 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 run(self): while self.running: # --- Inputs --- # self.window.getEvents() # --- Processing --- # self.ball.bounce() self.paddle.move(self.window.getKeyPressed()) self.ball.getBallPaddleCollision(self.paddle) for brick in self.bricks.getBricks( ): #Checks collision for all the brick if self.ball.getBallBrickCollision(brick): self.check = False self.bricks.getBricks().pop(self.check) self.ball.updateScore() print("Score:%s" % (self.ball.getScore())) if len(self.bricks.getBricks()) == 0: self.check = False exit() # --- Outputs --- # self.window.clearScreen() self.window.blitSprite(self.ball) self.window.blitSprite(self.paddle) self.bricks.blitBricks() self.window.updateScreen()
def main(): ## Graphics class screen = Screen(constants.WDITH, constants.HEIGHT) player1 = Paddle(screen, 3, constants.HEIGHT / 2 - 1, constants.BLUE) player2 = Paddle(screen, constants.WDITH - 4, constants.HEIGHT / 2 - 1, constants.BLUE) net = Net(screen, constants.BLACK) sceen.clear() player1.draw() player2.draw() net.draw()
class NeuralNetPlayer: 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 @classmethod def empty(cls): player = cls(0, 0, None, None) return player @classmethod def from_other(cls, other): player = cls(other.paddle.surface.get_width() // 2, other.paddle.rect.y, other.ball, other.paddle.surface) player.network = NeuralNetwork.from_other_network(other.network) return player @classmethod def crossover(cls, first, second): child = cls(first.paddle.surface.get_width() // 2, first.paddle.rect.y, first.ball, first.paddle.surface) child.network = NeuralNetwork.crossover(first.network, second.network) return child def collide(self): self.fitness_score += 3 def get_fitness_score(self): return self.fitness_score def mutate(self): self.network.mutate() def play(self): target_x = self.ball.x self_x = self.paddle.rect.x outputs = self.network.feed_forward([self_x, target_x]) if self.x_accumulator > 1: self.x_accumulator = 1 elif self.x_accumulator < -1: self.x_accumulator = -1 self.x_accumulator += outputs[0] * 3 if self.paddle.rect.left > self.paddle.surface.get_width(): self.paddle.move(-1) elif self.paddle.rect.right < 0: self.paddle.move(1) else: self.paddle.move(self.x_accumulator)
class Player: def __init__(self, no, name): self.no = no self.name = name self.score = 0 self.createPaddle() self.setKeys() self.setScorepos() def setScorepos(self): self.namepos = (30, 0) if self.no == 1 else (WIDTH - 100, 0) self.scorepos = (30, 50) if self.no == 1 else (WIDTH - 100, 50) def createPaddle(self): self.paddle = Paddle(10) if self.no == 1 else Paddle(WIDTH - 2 * 10) def setKeys(self): self.upKey = pygame.K_w if self.no == 1 else pygame.K_UP self.downKey = pygame.K_s if self.no == 1 else pygame.K_DOWN def movePaddle(self): keys = pygame.key.get_pressed() self.paddle.moveUp() if keys[self.upKey] else '' self.paddle.moveDown() if keys[self.downKey] else '' def usePaddle(self, ball): self.movePaddle() self.paddle.show() self.paddle.checkforBall(ball) self.paddle.checkforEdges() def showName(self): nameLabel = gameFont.render(str(self.name), True, WHITE, BLACK) SCREEN.blit(nameLabel, self.namepos) def showScore(self): scoreLabel = gameFont.render(str(self.score), True, WHITE, BLACK) SCREEN.blit(scoreLabel, self.scorepos)
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 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): 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
class PlayingState(ZedLib.GameState): 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 Update(self): for paddle in self.paddles: if paddle.ai_controlled: paddle.AIControl(None) else: paddle.HandleInput() paddle.UpdateMovement(self.borders + [self.ball]) self.ball.UpdateMovement(self.borders + self.paddles) self.CheckBallOffScreen() def DrawSprites(self): for paddle in self.paddles: self.game.screen.blit(paddle.image, paddle.rect) self.game.screen.blit(self.ball.image, self.ball.rect) def HandleKeyDownEvent(self, key): if key == pygame.K_ESCAPE: self.Pause() def CheckBallOffScreen(self): if ((self.ball.rect.right > self.game.screen_width) or (self.ball.rect.left < 0)): self.GameOver() def Pause(self): self.game.ChangeState(self.game.pause_state) def GameOver(self): self.game.ChangeState(self.game.game_over_state)
# Sets the window so that it isn't resizable top.resizable(0, 0) # Places the window on top of all other windows top.wm_attributes("-topmost", 1) # Creates the canvas and passes it several parameters: # bd = 0 and highlightthickness = 0 make sure that there isn't a border around the screen canvas = Tkinter.Canvas(top, width=500, height=400, bd=0, highlightthickness=0) # Tells the canvas to size itself according to the width and height parameters we pass in line 17 canvas.pack() # Tells Tkinter to initialize itself top.update() # Creates an object named 'paddle' of the Paddle class that we created in Paddle.py paddle = Paddle(canvas, 'blue') # Creates an object named 'ball' of the Ball class that we created in Ball.py ball = Ball(canvas, paddle, 'red') current_score = 0 # Creates the label for the score score = Tkinter.Label(canvas, text= ball.score()) # Displays that window canvas.create_window(10, 20, window=score, anchor='w') # Tells the canvas to not loop through the listed command until the user close the window while 1:
def run(): CENTER = [COMMONS.WINDOWWIDTH/2, COMMONS.WINDOWHEIGHT/2] DISK_HOLE = 10 RADIUS = 15 PADDLE_SPEED = 7 PADDLE_HEIGHT = 100 PADDLE_WIDTH = 10 BALL_VELS = [[3,1], [2,1], [-3,1], [3,-1], [-3,-1], [-2,-2], [-2,1], [2,2]] BALL_VEL = random.choice(BALL_VELS) WIN_BANNER_POS = {'left': [100, 50], 'right': [458, 50]} ball = Ball(CENTER, RADIUS, BALL_VEL, DISK_HOLE, COMMONS.REDDISH) paddle_1 = Paddle(0, 150, PADDLE_WIDTH, PADDLE_HEIGHT, COMMONS.BLUEISH, PADDLE_SPEED, ball) paddle_2 = Paddle(COMMONS.WINDOWWIDTH - PADDLE_WIDTH, 150, PADDLE_WIDTH, PADDLE_HEIGHT, COMMONS.BLUEISH, PADDLE_SPEED, ball) ball_copy = copy.deepcopy(ball) scoreLeft = 0 scoreRight = 0 pygame.init() pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) spaces = " " # hack to display both scores at once (avoid double blitting the score Font objects) score_Font = pygame.font.SysFont("Verdana", 35) windowSurface = pygame.display.set_mode((COMMONS.WINDOWWIDTH, COMMONS.WINDOWHEIGHT), DOUBLEBUF, 32) pygame.display.set_caption('Pong') pygame.draw.circle(windowSurface, ball.color, (ball.x, ball.y), ball.radius) pygame.draw.circle(windowSurface, COMMONS.WHITE, (ball.x, ball.y), ball.radius + 2, ball.radius - DISK_HOLE) pygame.display.update() time.sleep(1) while max(scoreLeft, scoreRight) < 3: in_game = True paddle_1_down = paddle_1_up = paddle_2_down = paddle_2_up = False mainCLock = pygame.time.Clock() while in_game == True: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_DOWN: paddle_2_down = True elif event.key == K_UP: paddle_2_up = True elif event.key == ord('s'): paddle_1_down = True elif event.key == ord('w'): paddle_1_up = True elif event.key == ord('r'): scoreRight = scoreLeft = 0 ball.x = COMMONS.WINDOWWIDTH/2 ball.y = COMMONS.WINDOWHEIGHT/2 ball.vel = random.choice(BALL_VELS) in_game = True elif event.key == ord('q'): pygame.quit() sys.exit() elif event.type == KEYUP: if event.key == K_DOWN: paddle_2_down = False elif event.key == K_UP: paddle_2_up = False elif event.key == ord('s'): paddle_1_down = False elif event.key == ord('w'): paddle_1_up = False elif event.type == QUIT: pygame.quit() sys.exit() if paddle_1_down: paddle_1.move(1) elif paddle_1_up: paddle_1.move(-1) if paddle_2_down: paddle_2.move(1) elif paddle_2_up: paddle_2.move(-1) ball.check_board_bounce() ball.move() if ball.x - ball.radius <= 0: if ball.y >= paddle_1.y and ball.y <= paddle_1.y + paddle_1.height: ball.vel[0] = -int(math.floor(1.1*ball.vel[0])) else: scoreRight += 1 in_game = False elif ball.x + ball.radius >= COMMONS.WINDOWWIDTH: if ball.y >= paddle_2.y and ball.y <= paddle_2.y + paddle_2.height: ball.vel[0] = int(math.floor(-1.1*ball.vel[0])) else: scoreLeft += 1 in_game = False windowSurface.fill(COMMONS.BLACK) windowSurface.lock() pygame.draw.line(windowSurface, COMMONS.WHITE, (COMMONS.WINDOWWIDTH/2, 0), (COMMONS.WINDOWWIDTH/2, COMMONS.WINDOWHEIGHT), 2) pygame.draw.line(windowSurface, COMMONS.WHITE, (paddle_1.width, 0), (paddle_1.width, COMMONS.WINDOWHEIGHT), 1) pygame.draw.line(windowSurface, COMMONS.WHITE, (COMMONS.WINDOWWIDTH - paddle_2.width, 0), (COMMONS.WINDOWWIDTH - paddle_2.width, COMMONS.WINDOWHEIGHT), 1) pygame.draw.circle(windowSurface, ball.color, (ball.x, ball.y), ball.radius) pygame.draw.circle(windowSurface, COMMONS.WHITE, (ball.x, ball.y), ball.radius + 2, ball.radius - DISK_HOLE) pygame.draw.rect(windowSurface, paddle_1.color, pygame.Rect(paddle_1.x, paddle_1.y + 2, paddle_1.width, paddle_1.height - 4)) pygame.draw.rect(windowSurface, paddle_2.color, pygame.Rect(paddle_2.x, paddle_2.y + 2, paddle_2.width, paddle_2.height - 4)) windowSurface.unlock() scoreSurface = score_Font.render(str(scoreLeft)+spaces+str(scoreRight), False, COMMONS.WHITE) windowSurface.blit(scoreSurface, (150,80)) pygame.display.update() mainCLock.tick(110) ball.x = ball_copy.x ball.y = ball_copy.y ball.vel[0] = -(abs(ball.vel[0]) % 2 + 1) pygame.time.wait(500) win_Surface = pygame.font.SysFont("Verdana", 30).render("You win", False, COMMONS.WHITE) if scoreLeft > scoreRight: winner = 'left' else: winner = 'right' windowSurface.blit(win_Surface, WIN_BANNER_POS[winner]) pygame.display.update()
class Pong: def __init__(self): #creates the window, the ball, the two paddles, and draws the background and the scoreboard. self.win = GraphWin("Pong", 800, 400) self.background = Image(Point(400,200),"pingpong.gif") self.background.draw(self.win) self.ball=Ball(self.win) self.paddle = Paddle(self.win,740,150,750,250,"red") self.paddle1 = Paddle(self.win, 60, 150,70,250,"blue") self.radius = self.ball.getRadius() self.scoreboard = Text(Point(400, 50), "") self.scoreboard.setSize(12) self.scoreboard.setTextColor("white") self.scoreboard.draw(self.win) y = 200 self.middle = self.paddle.move(self.win, y) self.middle1 = self.paddle1.move(self.win,y) def checkContact(self): #gets the values for the top and bottom of the paddles self.top = self.paddle.getMiddle()- (self.paddle.getHeight()/2) self.bot = self.paddle.getMiddle() +(self.paddle.getHeight()/2) self.top1 = self.paddle1.getMiddle() - (self.paddle1.getHeight()/2) self.bot1 = self.paddle1.getMiddle() + (self.paddle1.getHeight()/2) #gets the values of the left and right edges of the ball right = self.ball.getCenter().getX()+self.radius left = self.ball.getCenter().getX()-self.radius ballHeight = self.ball.getCenter().getY() touch = right - self.frontedge touch1 = self.frontedge1 - left #if the ball touches either paddle it returns true if (0 <= touch <= 10) or (0<= touch1 <= 10): if(self.top < ballHeight <self.bot) and self.ball.moveRight(): return True elif (self.top1 < ballHeight < self.bot1) and self.ball.moveLeft(): return True else: return False def gameOver(self): self.frontedge = self.paddle.getEdge() self.frontedge1 = self.paddle1.getEdge() ballWidth = self.ball.getCenter().getX() #returns true if the ball passes either of the paddles if (ballWidth > self.frontedge): return True elif(ballWidth < self.frontedge1): return True else: return False def play(self): click = self.win.getMouse() y = click.getY() end = self.gameOver() contact = self.checkContact() self.hits = 0 self.level = 1 while not end: #moves the paddles based on the user's click point #if the ball is moving right the right paddle moves #if the ball is moving left the left paddle moves click = self.win.checkMouse() if click != None and self.ball.moveRight(): y = click.getY() self.paddle.move(self.win, y) elif click != None and self.ball.moveLeft(): y = click.getY() self.paddle1.move(self.win, y) #moves the ball and reverses the X direction of the ball self.ball.move(self.win) sleep(0.025) contact = self.checkContact() if contact == True : self.ball.reverseX() self.hits = self.hits+1 #increases ball speed after every 5 hits if self.hits%5==0: self.ball.goFaster() self.level=self.level+1 self.scoreboard.setText(("Hits:",self.hits, "Level:", self.level)) end = self.gameOver() self.scoreboard = Text(Point(400, 100),"You Lost") self.scoreboard.setSize(12) self.scoreboard.setTextColor("white") self.scoreboard.draw(self.win) self.win.getMouse() self.win.close()
pygame.init() screen = pygame.display.set_mode(screen_size) pygame.display.set_caption('Arkanoid') background = pygame.Surface(screen_size) background = background.convert() background.fill((250, 250, 250)) score_font = pygame.font.Font(None, 36) score = 0 done = False ball1 = Ball() paddle = Paddle() blocks = [] powerups = [] for i in range(10): for j in range(10): blocks.append(Block(resources['verde'],(i*48 +100 , j*24 +100))) clock = pygame.time.Clock() last_key = None while not done: pressed = pygame.key.get_pressed() if pressed[pygame.K_LEFT]: paddle.moveLeft()
class Game: # This function initializes properties of the game. def __init__(self): self.menu = True self.play = False self.width = 1250 self.height = 750 self.gameHeight = 675 self.state = True self.screen = pygame.display.set_mode([self.width, self.height]) self.difficultylevel = 1 self.weaponsinit() self.superweaponsinit() self.superx1 = 0 self.superx2 = 0 self.supery = 0 self.num1 = random.randint(0,4) self.num2 = random.randint(0,4) self.options() def weaponsinit(self): self.weaponsinit1() self.weaponsinit2() def weaponsinit1(self): vchange1 = VerticalChange() hchange1 = HorizontalChange() sup1 = SpeedUp() sdown1 = SpeedDown() reverse1 = Reverse() self.weaponlist1 = [vchange1, hchange1, sup1, sdown1, reverse1] self.collide1 = False self.collidegreen1 = False def weaponsinit2(self): vchange2 = VerticalChange() hchange2 = HorizontalChange() sup2 = SpeedUp() sdown2 = SpeedDown() reverse2 = Reverse() self.weaponlist2 = [vchange2, hchange2, sup2, sdown2, reverse2] self.collide2 = False self.collidegreen2 = False def superweaponsinit(self): self.hades = [False, None, None, 0] self.zeus = [False, None, None, 0, 0] self.poseidon = [False, None, None, 0] # This function chooses the state of the game. def options(self): pygame.init() while self.state == True: if self.menu == True: self.gameMenu() while self.play == True: self.run() def gameMenu(self): pygame.init() inumber = 2 while self.menu == True: for event in pygame.event.get(): if (event.type == QUIT): self.menu = False self.state = False self.play = False pygame.event.pump() mouse = pygame.mouse.get_pressed() doneChoice = False if mouse[0]: doneChoice = self.choice(mouse) if doneChoice: return self.menuDraw(inumber) inumber += 1 def choice(self, mouse): mousepos = pygame.mouse.get_pos() if self.playrect.collidepoint(mousepos): return self.playerchoice() if self.instructionsrect.collidepoint(mousepos): self.instruction() return False if self.difficultyrect.collidepoint(mousepos): self.chooseDifficulty() if self.quitrect.collidepoint(mousepos): self.menu = False self.state = False self.play = False def chooseDifficulty(self): diff = True arrow = pygame.image.load(os.path.join("images", "pages", "pagearrowleft.jpg")) arrowrect = arrow.get_rect() arrowrect.center = 50, 50 while diff: for event in pygame.event.get(): if (event.type == QUIT): self.menu = False self.state = False self.play = False diff = False elif (event.type == pygame.MOUSEBUTTONDOWN): mousepos = pygame.mouse.get_pos() if arrowrect.collidepoint(mousepos): diff = False return False elif leftrect.collidepoint(mousepos): if self.difficultylevel > 1: self.difficultylevel -= 1 elif rightrect.collidepoint(mousepos): if self.difficultylevel < 3: self.difficultylevel += 1 rightrect, leftrect = self.drawDifficultyPage() self.screen.blit(arrow, arrowrect) pygame.display.update() def drawDifficultyPage(self): black = (0,0,0) self.screen.fill(black) rightrect, leftrect = self.drawDiffArrows() self.drawDiffTitle() self.drawNumber() return rightrect, leftrect def drawNumber(self): imageName = str(self.difficultylevel) + ".jpg" image = pygame.image.load(os.path.join("images", imageName)) rect = image.get_rect() rect.center = self.width/2.0, self.height/2.0 self.screen.blit(image, rect) def drawDiffTitle(self): diffimage = pygame.image.load(os.path.join("images", "diff.jpg")) diffrect = diffimage.get_rect() diffrect.center = self.width/2.0, 150 self.screen.blit(diffimage, diffrect) def drawDiffArrows(self): right = pygame.image.load(os.path.join("images", "diffarrowright.jpg")) rightrect = right.get_rect() left = pygame.image.load(os.path.join("images", "diffarrowleft.jpg")) leftrect = left.get_rect() rightrect.center = self.width * 3.0/4, self.height/2.0 leftrect.center = self.width * 1.0/4, self.height/2.0 self.screen.blit(right, rightrect) self.screen.blit(left, leftrect) return rightrect, leftrect # This function displays the choice of paddles for the player. def playerchoice(self): playBool = True top = 2.0/10 * self.height arrow = pygame.image.load(os.path.join("images", "pages", "pagearrowleft.jpg")) arrowrect = arrow.get_rect() arrowrect.center = 50, 50 image = pygame.image.load(os.path.join("images", "presst.jpg")) rectt = image.get_rect() rectt.left = 50 rectt.top = self.height - 75 player1img = pygame.image.load(os.path.join("images", "player1.jpg")) player2img = pygame.image.load(os.path.join("images", "player2.jpg")) player1imgrect = player1img.get_rect() player2imgrect = player2img.get_rect() player1imgrect.center = self.width/2 , 1.0/10 * self.height player2imgrect.center = self.width/2, 1.0/10 * self.height hades = pygame.image.load(os.path.join("images", "godimages", "hades.jpg")) hadesrect = hades.get_rect() hadesrect.centerx = self.width * 1.0/4 hadesrect.top = top poseidon = pygame.image.load(os.path.join("images", "godimages", "poseidon.jpg")) poseidonrect = poseidon.get_rect() poseidonrect.centerx = self.width * 2.0/4 poseidonrect.top = top zeus = pygame.image.load(os.path.join("images", "godimages", "zeus.jpg")) zeusrect = zeus.get_rect() zeusrect.centerx = self.width * 3.0/4 zeusrect.top = top player = 1 black = (0,0,0) while playBool: for event in pygame.event.get(): if (event.type == QUIT): self.menu = False self.state = False self.play = False playBool = False elif (event.type == pygame.MOUSEBUTTONDOWN): mousepos = pygame.mouse.get_pos() if arrowrect.collidepoint(mousepos): playBool = False return False chose = self.initChoice(player, hadesrect,poseidonrect,zeusrect, arrowrect) if chose: player += 1 #if playBool == False: # print "i art here" # return False if player == 3: self.play = True playBool = False return True self.screen.fill(black) self.screen.blit(arrow, arrowrect) self.screen.blit(hades, hadesrect) self.screen.blit(poseidon, poseidonrect) self.screen.blit(zeus, zeusrect) self.screen.blit(image, rectt) if player == 1: self.screen.blit(player1img, player1imgrect) else: self.screen.blit(player2img, player2imgrect) pygame.display.update() # This function initializes the paddles 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 instruction(self): page = 1 pygame.display.set_caption("Greek Pong") black = (0,0,0) instruct = True while instruct: self.screen.fill(black) rightrect, leftrect = self.drawArrows(page) for event in pygame.event.get(): if (event.type == QUIT): self.menu = False self.state = False self.play = False instruct = False elif (event.type == pygame.MOUSEBUTTONDOWN): mousepos = pygame.mouse.get_pos() if rightrect.collidepoint(mousepos): if page < 4: page += 1 else: page = 1 if leftrect.collidepoint(mousepos): page -= 1 if page == 0: instruct = False if page == 1: self.drawPage1() elif page == 2: self.drawPage2() elif page == 3: self.drawPage3() elif page == 4: self.drawPage4() pygame.display.update() def drawArrows(self, page): right = pygame.image.load(os.path.join("images", "pages", "pagearrowright.jpg")) rightrect = right.get_rect() left = pygame.image.load(os.path.join("images", "pages", "pagearrowleft.jpg")) leftrect = left.get_rect() leftrect.center = 50, self.height - 50 rightrect.center = self.width - 50, self.height - 50 #if (page == 1) or (page == 2) or (page == 3): self.screen.blit(left, leftrect) self.screen.blit(right, rightrect) # else: # self.screen.blit(left, leftrect) return rightrect, leftrect def drawPage1(self): self.pcontrols() height = 150 for i in xrange(8): centerx = 225 inum = i + 1 self.drawP1(inum, centerx, height) centerx = self.width/2.0 self.drawNames(inum, centerx, height) centerx = self.width - 225 self.drawP2(inum, centerx, height) height += 75 def drawP1(self, inum, centerx, height): p1keyname = "p1" + str(inum) + ".jpg" p1key = pygame.image.load(os.path.join("images", "page1", p1keyname)) p1keyrect = p1key.get_rect() p1keyrect.center = centerx, height self.screen.blit(p1key, p1keyrect) def drawNames(self, inum, centerx, height): keyname = "name" + str(inum) + ".jpg" key = pygame.image.load(os.path.join("images", "page1", keyname)) keyrect = key.get_rect() keyrect.center = centerx, height self.screen.blit(key, keyrect) def drawP2(self, inum, centerx, height): p2keyname = "p2" + str(inum) + ".jpg" p2key = pygame.image.load(os.path.join("images", "page1", p2keyname)) p2keyrect = p2key.get_rect() p2keyrect.center = centerx, height self.screen.blit(p2key, p2keyrect) def pcontrols(self): p1 = pygame.image.load(os.path.join("images", "page1", "p1controls.jpg")) p1rect = p1.get_rect() p2 = pygame.image.load(os.path.join("images", "page1", "p2controls.jpg")) p2rect = p2.get_rect() p1rect.left = 50 p1rect.top = 50 p2rect.right = self.width - 50 p2rect.top = 50 self.screen.blit(p1, p1rect) self.screen.blit(p2, p2rect) def drawPage2(self): self.drawPage2Title() self.drawDescriptions() self.drawWeaponImages() def drawPage2Title(self): title = pygame.image.load(os.path.join("images","page2","weapons.jpg")) titlerect = title.get_rect() titlerect.top = 10 titlerect.centerx = self.width/2.0 self.screen.blit(title, titlerect) def drawWeaponImages(self): height = 110 centerx = 150 for i in xrange(len(self.weaponlist1)): self.weaponlist1[i].weaponDraw(self, centerx, height) height += 100 greensphere = pygame.image.load(os.path.join("images", "green.jpg")) greenrect = greensphere.get_rect() greenrect.center = centerx, height self.screen.blit(greensphere, greenrect) def drawDescriptions(self): height = 80 left = self.width * 1.0/4 for i in xrange(6): inum = i + 1 descripname = "descrip" + str(inum) + ".jpg" descrip = pygame.image.load(os.path.join("images", "page2", descripname)) descriprect = descrip.get_rect() descriprect.top, descriprect.left = height, left self.screen.blit(descrip, descriprect) height += 100 def drawPage3(self): self.drawPage3Title() height = 150 for i in xrange(3): left = 100 inum = i + 1 self.drawGodNames(inum, left, height) left = self.width * 1.0/4 self.drawSuperDescrip(inum, left, height) height += 200 def drawGodNames(self, inum, left, height): godname = "god" + str(inum) + ".jpg" god = pygame.image.load(os.path.join("images", "page3", godname)) godrect = god.get_rect() godrect.left, godrect.top = left, height self.screen.blit(god, godrect) def drawSuperDescrip(self, inum, left, height): supername = "super" + str(inum) + ".jpg" image = pygame.image.load(os.path.join("images", "page3", supername)) superrect = image.get_rect() superrect.left, superrect.top = left, height self.screen.blit(image, superrect) def drawPage3Title(self): title = pygame.image.load(os.path.join("images","page3","superw.jpg")) titlerect = title.get_rect() titlerect.top = 10 titlerect.centerx = self.width/2.0 self.screen.blit(title, titlerect) def drawPage4(self): self.drawFirst() self.drawSecond() self.drawThird() self.drawFourth() def drawFirst(self): image = pygame.image.load(os.path.join("images", "page4", "pg41.jpg")) rect = image.get_rect() rect.left = 150 rect.top = 100 self.screen.blit(image, rect) def drawSecond(self): image = pygame.image.load(os.path.join("images", "page4", "pg42.jpg")) rect = image.get_rect() rect.left = 150 rect.top = 200 self.screen.blit(image, rect) self.drawInstructBars() def drawInstructBars(self): healthColor1 = (255, 150, 0) healthColor2 = (255,0,0) shadowGreen = (0, 75, 0) height = 15 totalWidth = 200 width1 = 60/100.0 * totalWidth width2 = 20/100.0 * totalWidth top = 300 left1 = 200 left2 = 600 #initializing shadow bars shadowbar1 = (left1, top, totalWidth, height) shadowbar2 = (left2, top, totalWidth, height) #initializing health bars healthbar1 = (left1, top, width1, height) healthbar2 = (left2, top, width2, height) #drawing shadow bars pygame.draw.rect(self.screen, shadowGreen, shadowbar1, 0) pygame.draw.rect(self.screen, shadowGreen, shadowbar2, 0) #drawing health bars pygame.draw.rect(self.screen, healthColor1, healthbar1, 0) pygame.draw.rect(self.screen, healthColor2, healthbar2, 0) def drawThird(self): image = pygame.image.load(os.path.join("images", "page4", "pg43.jpg")) rect = image.get_rect() rect.left = 150 rect.top = 400 self.screen.blit(image, rect) self.drawInstructSuper(20, 150) self.drawInstructSuper(50, 400) self.drawInstructSuper(100, 650) def drawInstructSuper(self, demo, left): superbarfull = pygame.image.load(os.path.join("images", "bars", "superbarfull.jpg")) superbarempty = pygame.image.load(os.path.join("images", "bars", "superbarempty.jpg")) rect = superbarfull.get_rect() height = rect.height width = demo/100.0 * rect.width fullrect1 = pygame.Rect(0,0,width, height) emptyrect1 = superbarempty.get_rect() super1 = superbarfull.subsurface(fullrect1) superrect = super1.get_rect() superrect.left = emptyrect1.left = left superrect.top = emptyrect1.top = 500 self.screen.blit(superbarempty, emptyrect1) self.screen.blit(super1, superrect) def drawFourth(self): image = pygame.image.load(os.path.join("images", "page4", "pg44.jpg")) rect = image.get_rect() rect.left = 150 rect.top = 600 self.screen.blit(image, rect) # This function draws the menu def menuDraw(self, inumber): self.screen.fill((0,0,0)) pygame.display.set_caption("Greek Pong") xblock = self.width/2 yblock = [2.75, 4.25, 5.75, 7.25] for i in xrange(len(yblock)): yblock[i] = yblock[i]/10 * self.height titlerect = self.drawTitle() self.drawPlay(xblock, yblock[0]) self.drawInstructions(xblock, yblock[1]) self.drawDifficulty(xblock, yblock[2]) self.drawQuit(xblock, yblock[3]) self.drawTorch(inumber) self.drawFlames(titlerect, inumber) pygame.display.update() def drawTitle(self): title = pygame.image.load(os.path.join("images", "greekpong.jpg")) titlerect = title.get_rect() titlerect.centerx = self.width/2.0 titlerect.top = 0 self.screen.blit(title, titlerect) return titlerect def drawPlay(self, x, y): play = pygame.image.load(os.path.join("images", "menu", "play.jpg")) self.playrect = play.get_rect() self.playrect.center = x, y self.screen.blit(play, self.playrect) def drawInstructions(self, x, y): instructions = pygame.image.load(os.path.join("images", "menu", "instructions.jpg")) self.instructionsrect = instructions.get_rect() self.instructionsrect.center = x, y self.screen.blit(instructions, self.instructionsrect) def drawDifficulty(self, x, y): difficulty = pygame.image.load(os.path.join("images", "menu", "difficulty.jpg")) self.difficultyrect = difficulty.get_rect() self.difficultyrect.center = x, y self.screen.blit(difficulty, self.difficultyrect) def drawQuit(self, x, y): quit = pygame.image.load(os.path.join("images", "menu", "quit.jpg")) self.quitrect = quit.get_rect() self.quitrect.center = x, y self.screen.blit(quit, self.quitrect) def drawTorch(self, inumber): torch = pygame.image.load(os.path.join("images", "torch.jpg")) torch1 = torch.get_rect() torch2 = torch.get_rect() left1 = self.width * 0.25/10 right2 = self.width * 9.75/10 top = self.height * 2.0/10 torch1.topleft = left1, top torch2.topright = right2, top self.screen.blit(torch, torch1) self.screen.blit(torch, torch2) #self.drawFlames(torch1, torch2, inumber) def drawFlames(self, titlerect, inumber): inumber = inumber % 32 imageNumber = inumber/2 y = imageNumber / 4 x = (imageNumber-(y*4))%4 x = x*128 y = y*128 imageName = "flames.jpg" image = pygame.image.load(os.path.join("images", imageName)) cropped = pygame.Rect(x,y,128,128) croppedimage = image.subsurface(cropped) imagerect1 = pygame.Rect(0,0,128,128) imagerect2 = pygame.Rect(0,0,128,128) imagerect1.right = titlerect.left - 10 imagerect2.left = titlerect.right + 10 self.screen.blit(croppedimage, imagerect1) self.screen.blit(croppedimage, imagerect2) # This function calls all required functions for the game to run. def run(self): pygame.init() pygame.display.set_caption("Greek Pong") margin = 50 self.player1.reinit(margin, self.gameHeight, self.width) self.player2.reinit(margin, self.gameHeight, self.width) player1 = self.player1 player2 = self.player2 ball = Ball(self.width, self.gameHeight, self.screen, self) black = pygame.Color(0,0,0) counter = 0 runGame = True while runGame and self.play: for event in pygame.event.get(): if (event.type == QUIT): self.play = False self.state = False runGame = False break pygame.event.pump() keys = pygame.key.get_pressed() mouse = pygame.mouse.get_pressed() ball.moveBall(self.width, self.gameHeight, player1, player2, self) player1.movePaddle(keys, self.gameHeight, self.width, ball, self) player2.movePaddle(keys, self.gameHeight, self.width, ball, self) player1.useWeaponRack(keys, ball, player2, self) player2.useWeaponRack(keys, ball, player1, self) self.checkInstruction(keys) if counter == 400: counter = 0 self.redrawAll(player1, player2, ball, counter) counter += 1 if (self.checkWin(player1, player2)): runGame = False break def checkInstruction(self, keys): if keys[pygame.K_t]: self.instruction() def weapons(self, counter, player1, player2, ball): if counter == 0: self.num1 = random.randint(0,4) self.num2 = random.randint(0,4) self.collide1 = False self.collide2 = False weapon1 = self.weaponlist1[self.num1] weapon2 = self.weaponlist2[self.num2] if counter == 0: weapon1.x = random.randint(50, self.width/2 - 50) weapon2.x = random.randint(self.width/2 + 50, self.width - 50) weapon1.y = random.randint(50, self.gameHeight-50) weapon2.y = random.randint(50, self.gameHeight-50) if self.collide1 == False: weapon1.weaponDraw(self, weapon1.x, weapon1.y) if self.collide2 == False: weapon2.weaponDraw(self, weapon2.x, weapon2.y) if self.collide1 == False: if weapon1.collide(player1): self.collide1 = True for i in xrange(3): if player1.weaponrack[i] == 0: player1.weaponrack[i] = weapon1 break if self.collide2 == False: if weapon2.collide(player2): self.collide2 = True for i in xrange(3): if player2.weaponrack[i] == 0: player2.weaponrack[i] = weapon2 break self.drawWeaponRack(player1, player2) def drawWeaponRack(self, player1, player2): outer = 40 colorouter1 = player1.checkColor() colorouter2 = player2.checkColor() colorinner = (0,0,0) inner = 38 outerrect = pygame.Rect(0,0,outer,outer) innerrect = pygame.Rect(0,0,inner,inner) outerrect.center = self.width*2.0/10, self.gameHeight + 40 innerrect.center = self.width*2.0/10, self.gameHeight + 40 distance = 670 for i in xrange(3): pygame.draw.rect(self.screen, colorouter1, outerrect, 0) pygame.draw.rect(self.screen, colorinner, innerrect, 0) if player1.weaponrack[i] != 0: x = outerrect.centerx y = outerrect.centery player1.weaponrack[i].weaponDraw(self, x, y) outerrect.centerx += distance innerrect.centerx += distance pygame.draw.rect(self.screen, colorouter2, outerrect, 0) pygame.draw.rect(self.screen, colorinner, innerrect, 0) if player2.weaponrack[i] != 0: x = outerrect.centerx y = outerrect.centery player2.weaponrack[i].weaponDraw(self, x, y) outerrect.centerx -= distance innerrect.centerx -= distance outerrect.centerx += (outer+2) innerrect.centerx += (inner+4) def superWeapons(self, counter, player1, player2): greenSphere = pygame.image.load(os.path.join("images", "green.jpg")) greenrect1 = greenSphere.get_rect() greenrect2 = greenSphere.get_rect() if counter == 0: self.superx1 = random.randint(50, self.width/2 - 50) self.superx2 = random.randint(self.width/2 + 50, self.width - 50) self.supery = random.randint(50, self.gameHeight - 50) self.collidegreen1 = False self.collidegreen2 = False greenrect1.center = self.superx1, self.supery greenrect2.center = self.superx2, self.supery if self.collidegreen1 == False: self.screen.blit(greenSphere, greenrect1) if self.collidegreen2 == False: self.screen.blit(greenSphere, greenrect2) if self.collidegreen1 == False: if greenrect1.colliderect(player1.rect): self.collidegreen1 = True if player1.superbar < 100: player1.superbar += 20 if self.collidegreen2 == False: if greenrect2.colliderect(player2.rect): self.collidegreen2 = True if player2.superbar < 100: player2.superbar += 20 self.drawSuperBar(player1, player2) # This function draws the superbars. def drawSuperBar(self, player1, player2): superbarfull = pygame.image.load(os.path.join("images", "bars", "superbarfull.jpg")) superbarempty = pygame.image.load(os.path.join("images", "bars", "superbarempty.jpg")) rect = superbarfull.get_rect() height = rect.height width1 = player1.superbar/100.0 * rect.width width2 = player2.superbar/100.0 * rect.width fullrect1 = pygame.Rect(0,0,width1, height) emptyrect1 = superbarempty.get_rect() fullrect2 = pygame.Rect(0,0,width2, height) emptyrect2 = superbarempty.get_rect() super1 = superbarfull.subsurface(fullrect1) super2 = superbarfull.subsurface(fullrect2) super1rect = super1.get_rect() super2rect = super2.get_rect() super1rect.right = emptyrect1.right = self.width/2.0 - 25 super2rect.left = emptyrect2.left = self.width/2.0 + 25 super1rect.top = emptyrect1.top = self.gameHeight+20 super2rect.top = emptyrect2.top = self.gameHeight+20 self.screen.blit(superbarempty, emptyrect1) self.screen.blit(superbarempty, emptyrect2) self.screen.blit(super1, super1rect) self.screen.blit(super2, super2rect) # This function checks whether any player has won by killing the other. def checkWin(self, player1, player2): if (player1.health <= 0): player2.score += 1 self.hades[0] = False self.zeus[0] = False self.poseidon[0] = False return True elif (player2.health <= 0): player1.score += 1 self.hades[0] = False self.zeus[0] = False self.poseidon[0] = False return True else: return False # This function calls all the draw functions to display the game. def redrawAll(self,player1,player2,ball,counter): black = (0,0,0) self.screen.fill(black) self.weapons(counter, player1, player2, ball) self.superWeapons(counter, player1, player2) self.drawBoard() self.drawBall(ball) self.drawPaddle(player1, player2) self.drawText(player1, player2) self.drawHealth(player1, player2) self.drawScore(player1, player2) if self.zeus[0] == True: self.drawLightning(player1, player2) pygame.display.update() # This function draws the board. def drawBoard(self): pygame.draw.line(self.screen, (255,255,255), (self.width/2, 0), (self.width/2, self.height)) pygame.draw.line(self.screen, (255,255,255), (0,self.gameHeight), (self.width, self.gameHeight)) # This function draws the ball. def drawBall(self, ball): if self.hades[3] == 3: self.hades[0] = False if self.hades[0] == True: if self.hades[1].player == 1: if ball.horizontalspeed < 0: self.screen.blit(ball.image, ball.rect) else: if ball.rect.right >= (self.width/10.0 * 2): pass else: self.screen.blit(ball.image, ball.rect) if self.hades[1].player == 2: if ball.horizontalspeed > 0: self.screen.blit(ball.image, ball.rect) else: if ball.rect.right <= (self.width/10.0 * 8): pass else: self.screen.blit(ball.image, ball.rect) else: self.screen.blit(ball.image, ball.rect) # This function draws both the paddles. def drawPaddle(self, player1, player2): self.screen.blit(player1.image, player1.rect) self.screen.blit(player2.image, player2.rect) # This function writes any text required to be written. def drawText(self, player1, player2): player1Color = player1.checkColor() player2Color = player2.checkColor() message1 = "Player 1" message2 = "Player 2" size = 35 font = pygame.font.Font(None, size) text1 = font.render(message1, 1, player1Color) text2 = font.render(message2, 1, player2Color) player1text = text1.get_rect() player1text.topleft = 1, (self.gameHeight+1) player2text = text2.get_rect() player2text.topright = self.width-1, (self.gameHeight+1) self.screen.blit(text1, player1text) self.screen.blit(text2, player2text) # This function draws the health bars of both the paddles. def drawHealth(self, player1, player2): healthColor1 = self.getHealthColor(player1) healthColor2 = self.getHealthColor(player2) shadowGreen = (0, 75, 0) height = 15 totalWidth = 200 width1 = player1.health/100.0 * totalWidth width2 = player2.health/100.0 * totalWidth top = self.height * 9.5/10 left1 = 1 left2 = self.width -totalWidth - 1 #initializing shadow bars shadowbar1 = (left1, top, totalWidth, height) shadowbar2 = (left2, top, totalWidth, height) #initializing health bars healthbar1 = (left1, top, width1, height) healthbar2 = (left2, top, width2, height) #drawing shadow bars pygame.draw.rect(self.screen, shadowGreen, shadowbar1, 0) pygame.draw.rect(self.screen, shadowGreen, shadowbar2, 0) #drawing health bars pygame.draw.rect(self.screen, healthColor1, healthbar1, 0) pygame.draw.rect(self.screen, healthColor2, healthbar2, 0) # This function draws the score of the player def drawScore(self, player1, player2): size = 50 font = pygame.font.Font(None, size) color1 = player1.checkColor() color2 = player2.checkColor() text1 = font.render(str(player1.score), 1, color1) text2 = font.render(str(player2.score), 1, color2) score1 = text1.get_rect() score1.topright = self.width/2 - 3, self.gameHeight + 1 score2 = text2.get_rect() score2.topleft = self.width/2 + 3, self.gameHeight + 1 self.screen.blit(text1, score1) self.screen.blit(text2, score2) def drawLightning(self, player1, player2): light = pygame.image.load(os.path.join("images", "light.jpg")) lightrect = light.get_rect() lightrect.centery = self.zeus[4] if self.zeus[1] == player1: self.zeus[3] += 6 lightrect.left = self.zeus[3] else: self.zeus[3] -= 6 lightrect.right = self.zeus[3] if self.zeus[2].rect.centery > self.zeus[4]: self.zeus[4] += 4 lightrect.centery = self.zeus[4] elif self.zeus[2].rect.centery < self.zeus[4]: self.zeus[4] -= 4 lightrect.centery = self.zeus[4] if self.zeus[2] == player1: if lightrect.colliderect(player1.rect): self.zeus[0] = False player1.health -= 30 if lightrect.left <= 0: self.zeus[0] = False if self.zeus[2] == player2: if lightrect.colliderect(player2.rect): self.zeus[0] = False player2.health -= 30 if lightrect.left >= self.width: self.zeus[0] = False self.screen.blit(light, lightrect) # This function returns the color that the health bar should be. def getHealthColor(self, player): green = (0, 200, 0) orange = (255, 150, 0) red = (255, 0, 0) if player.health >= 70: return green elif player.health >= 40: return orange else: return red
class GameSpace: def __init__(self): # initialization pygame.init() self.size = SCREEN_WIDTH, SCREEN_HEIGHT self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption("3D Pongbreaker Host") # create game objects self.background = self.create_background() self.paddle_1 = Paddle(PADDLE_BUFFER, 'host', self) self.paddle_2 = Paddle((HALLWAY_DEPTH - PADDLE_BUFFER), 'client', self) self.bc = BrickCreator(self) self.bricks = self.bc.get_bricks(BRICK_POS_FN) self.balls = set() self.balls.add(Ball(self.paddle_1.rect.center, (self.paddle_1.z_pos + 1), 1, self)) self.balls.add(Ball(self.paddle_2.rect.center, (self.paddle_2.z_pos - 1), 2, self)) self.title_font = pygame.font.Font(None, TITLE_FONT_SIZE) self.paddle_1_title_text = self.title_font.render('Player 1', False, TEXT_COLOR) self.paddle_2_title_text = self.title_font.render('Player 2', False, TEXT_COLOR) self.paddle_1_title_rect = self.paddle_1_title_text.get_rect() self.paddle_2_title_rect = self.paddle_2_title_text.get_rect() self.score_font = pygame.font.Font(None, SCORE_FONT_SIZE) def gameloop(self): # handle user inputs for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == MOUSEBUTTONDOWN and event.button == 1: self.paddle_1.launch = True elif event.type == MOUSEBUTTONUP and event.button == 1: self.paddle_1.launch = False # tick/update game objects self.paddle_1.tick() self.paddle_2.tick() for ball in set(self.balls): ball.tick() # display background self.screen.blit(self.background, (0, 0)) # display sprites sprites = [self.paddle_1, self.paddle_2] sprites.extend(self.bricks) sprites.extend(self.balls) sprites.sort(key=lambda sprite: sprite.z_pos, reverse=True) for sprite in sprites: self.blit_3D(sprite) # display ball traces for ball in self.balls: self.display_ball_trace(ball) # create score texts and rects paddle_1_score_text = self.score_font.render(str(self.paddle_1.score), False, TEXT_COLOR) paddle_2_score_text = self.score_font.render(str(self.paddle_2.score), False, TEXT_COLOR) paddle_1_score_rect = paddle_1_score_text.get_rect() paddle_2_score_rect = paddle_2_score_text.get_rect() # align title and score rects paddle_1_score_rect.bottomleft = (0, SCREEN_HEIGHT) paddle_2_score_rect.bottomright = (SCREEN_WIDTH, SCREEN_HEIGHT) self.paddle_1_title_rect.bottomleft = paddle_1_score_rect.topleft self.paddle_2_title_rect.bottomright = paddle_2_score_rect.topright # display titles and scores self.screen.blit(self.paddle_1_title_text, self.paddle_1_title_rect) self.screen.blit(self.paddle_2_title_text, self.paddle_2_title_rect) self.screen.blit(paddle_1_score_text, paddle_1_score_rect) self.screen.blit(paddle_2_score_text, paddle_2_score_rect) pygame.display.flip() def create_background(self): background = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT)) # draw wall edges pygame.draw.aaline(background, HALLWAY_EDGE_COLOR, (0, 0), WALL_TL) pygame.draw.aaline(background, HALLWAY_EDGE_COLOR, (SCREEN_WIDTH, 0), WALL_TR) pygame.draw.aaline(background, HALLWAY_EDGE_COLOR, (0, SCREEN_HEIGHT), WALL_BL) pygame.draw.aaline(background, HALLWAY_EDGE_COLOR, (SCREEN_WIDTH, SCREEN_HEIGHT), WALL_BR) # draw back wall back_wall_pl = [WALL_TL, WALL_TR, WALL_BR, WALL_BL] pygame.draw.polygon(background, HALLWAY_EDGE_COLOR, back_wall_pl, HALLWAY_EDGE_THICK) return background def blit_3D(self, sprite): scale = pow(SCALING_FACTOR, sprite.z_pos) # resize image scaled_image_width = sprite.image.get_size()[0] * scale scaled_image_height = sprite.image.get_size()[1] * scale scaled_image = pygame.transform.scale(sprite.image, (int(scaled_image_width), int(scaled_image_height))) # realign center of rectangle rect_screen_diff_x = sprite.rect.centerx - SCREEN_CENTER_X rect_screen_diff_y = sprite.rect.centery - SCREEN_CENTER_Y scaled_rect = scaled_image.get_rect() scaled_rect.centerx = SCREEN_CENTER_X + (rect_screen_diff_x * scale) scaled_rect.centery = SCREEN_CENTER_Y + (rect_screen_diff_y * scale) self.screen.blit(scaled_image, scaled_rect) def display_ball_trace(self, ball): # calculate trace dimensions trace_width = SCREEN_WIDTH * pow(SCALING_FACTOR, ball.z_pos) trace_height = SCREEN_HEIGHT * pow(SCALING_FACTOR, ball.z_pos) # calculate trace corners trace_tl = (((SCREEN_WIDTH - trace_width) / 2), ((SCREEN_HEIGHT - trace_height) / 2)) trace_tr = (((SCREEN_WIDTH - trace_width) / 2 + trace_width), ((SCREEN_HEIGHT - trace_height) / 2)) trace_bl = (((SCREEN_WIDTH - trace_width) / 2), ((SCREEN_HEIGHT - trace_height) / 2 + trace_height)) trace_br = (((SCREEN_WIDTH - trace_width) / 2 + trace_width), ((SCREEN_HEIGHT - trace_height) / 2 + trace_height)) # draw trace trace_pl = [trace_tl, trace_tr, trace_br, trace_bl] pygame.draw.polygon(self.screen, HALLWAY_EDGE_COLOR, trace_pl, HALLWAY_EDGE_THICK)
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 Pong(Engine): def __init__(self): Engine.__init__(self, 320, 240, (00, 150, 150)) self.fps_text = None self.scoreP1_text = None self.scoreP1 = 0 self.scoreP2_text = None self.scoreP2 = 0 self.ball = None self.playerOne = None self.playerTwo = None self.fps_update = 0 self.fps_count = 0 self.sfx_beep = None self.sfx_padOne = None self.sfx_padTwo = None self.music_bg = None self.winner_text = None self.start_game_text = None self.max_score = 7 def on_init(self): Engine.on_init(self) self.winner_text = Text(self.width/4, 80, str(""), 30) self.add(self.winner_text) self.start_game_text = Text(self.width/3, 120, str("Press START"), 30) self.add(self.start_game_text) self.scoreP1_text = Text(self.width/4, 30, str(self.scoreP1), 50) self.scoreP2_text = Text(self.width - self.width/4, 30, str(self.scoreP2), 50) self.add(self.scoreP1_text) self.add(self.scoreP2_text) self.fps_text = Text(280, 220, "30") self.add(self.fps_text) self.ball = Ball(self.width/2, self.height/2, "ball.png") self.add(self.ball) self.playerOne = Paddle(20, self.height/2, "paddle.png") self.add(self.playerOne) self.playerTwo = Paddle(320 - 20, self.height/2, "paddle.png") self.add(self.playerTwo) self.sfx_padOne = soundEffect("blip1.wav") self.sfx_padTwo = soundEffect("blip2.wav") self.music_bg = musicPlayer("UGH1.wav", -1) self.music_bg.play() self.start_game(False) def start_game(self, active): self.fps_text.set_active(active) self.scoreP1_text.set_active(active) self.scoreP1 = 0 self.scoreP2_text.set_active(active) self.scoreP2 = 0 self.ball.set_active(active) self.playerOne.set_active(active) self.playerTwo.set_active(active) self.fps_update = 0 self.fps_count = 0 self.start_game_text.set_active(not active) self.winner_text.set_active(not active) def show_end_game(self): self.ball.set_active(False) self.playerOne.set_active(True) self.playerTwo.set_active(True) self.fps_update = 0 self.fps_count = 0 self.winner_text.set_active(True) self.start_game_text.set_active(True) if self.scoreP1 > self.scoreP2: self.winner_text.set_text("Player 1 Wins") else: self.winner_text.set_text("Player 2 Wins") def update(self, delta_time): self.fps_update += 1 self.fps_count += self.delta_time if self.fps_update >= 20: self.fps_count /= 20 self.fps_text.set_text(str(int(1.0/(float(self.fps_count)/1000)))) self.fps_count = 0 self.fps_update = 0 self.handleInput() if self.scoreP1 == self.max_score or self.scoreP2 == self.max_score: self.show_end_game() else: self.checkCollision() def checkCollision(self): if self.ball.checkCollision(self.playerOne.getRect()): self.sfx_padOne.play_sound() self.ball.negateXVel() if self.ball.checkCollision(self.playerTwo.getRect()): self.sfx_padTwo.play_sound() self.ball.negateXVel() # p2 scores if self.ball.getX() < 0: self.ball.setPosition([self.width/2, self.height/2]) self.ball.negateXVel() self.scoreP2 += 1 self.scoreP2_text.set_text(str(self.scoreP2)) # p1 scores if self.ball.getX() > self.width: self.ball.setPosition([self.width/2, self.height/2]) self.ball.negateXVel() self.scoreP1 += 1 self.scoreP1_text.set_text(str(self.scoreP1)) def handleInput(self): # quitting if pygame.key.get_pressed()[pygame.K_ESCAPE] != 0: sys.exit() if pygame.key.get_pressed()[pygame.K_RETURN] != 0: self.start_game(True) # playerone if pygame.key.get_pressed()[pygame.K_UP] != 0: self.playerOne.setVelocity([0, -.2]) elif pygame.key.get_pressed()[pygame.K_DOWN] != 0: self.playerOne.setVelocity([0, .2]) else: self.playerOne.setVelocity([0, 0]) # playertwo if pygame.key.get_pressed()[pygame.K_SPACE] != 0: self.playerTwo.setVelocity([0, -.2]) elif pygame.key.get_pressed()[pygame.K_LALT] != 0: self.playerTwo.setVelocity([0, .2]) else: self.playerTwo.setVelocity([0, 0])
class Pong: 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 checkContact(self): xMiddle = self.p.getMiddle().getX() xPadLeft = xMiddle - 5 xPadRight = xMiddle + 5 xCenter = self.b.getCenter().getX() xBallRight = xCenter + self.b.getRadius() xBallLeft = xCenter - self.b.getRadius() yMiddle = self.p.getMiddle().getY() yPadTop = yMiddle - 50 yPadBottom = yMiddle + 50 yCenter = self.b.getCenter().getY() yBallTop = yCenter - self.b.getRadius() yBallBottom = yCenter + self.b.getRadius() # If the x value of right side of the ball is = to the x value of the left side of the paddle, # and the y value of the top/bottom of the ball is not outside the y value of the top/bottom of the paddle, # then the ball has made contact if (xBallRight >= xPadLeft and yBallBottom >= yPadTop) and (xBallRight >= xPadLeft and yBallTop <= yPadBottom): self.hits += 1 self.score += 1 self.userScore.setText(self.score) if self.hits % 2 == 0: self.level += 1 self.userLevel.setText(self.level) self.b.goFaster() if self.level % 4 == 0: self.tier = Text(Point(250, 250), "You have reached a new tier") self.tier.setTextColor("red") self.tier.setSize(20) self.tier.draw(self.pWin) self.wow = Text(Point(250, 81), "WOW!") self.wow.setSize(30) self.wow.setTextColor("red") self.wow.draw(self.pWin) sleep(3) self.tier.undraw() self.wow.undraw() return True else: return False def checkContactShrink(self): xMiddle = self.p.getMiddle().getX() xPadLeft = xMiddle - 5 xPadRight = xMiddle + 5 xCenter = self.b.getCenter().getX() xBallRight = xCenter + self.b.getRadius() xBallLeft = xCenter - self.b.getRadius() yMiddle = self.p.getMiddle().getY() yPadTop = yMiddle - 50 yPadBottom = yMiddle + 50 yCenter = self.b.getCenter().getY() yBallTop = yCenter - self.b.getRadius() yBallBottom = yCenter + self.b.getRadius() # If the x value of right side of the ball is = to the x value of the left side of the paddle, # and the y value of the top/bottom of the ball is not outside the y value of the top/bottom of the paddle, # then the ball has made contact if (xBallRight >= xPadLeft and yBallBottom >= yPadTop) and (xBallRight >= xPadLeft and yBallTop <= yPadBottom): self.hits += 1 self.score += 1 self.userScore.setText(self.score) if self.hits % 2 == 0: self.level += 1 self.userLevel.setText(self.level) self.b.goFaster() # Undraw the original Paddle, and Replace with new, smaller Paddle self.p.pad.undraw() self.p.newRectangle(self.hits*4) self.p.pad.draw(self.pWin) if self.level % 4 == 0: self.tier = Text(Point(250, 250), "You have reached a new tier") self.tier.setTextColor("red") self.tier.setSize(20) self.tier.draw(self.pWin) self.wow = Text(Point(250, 81), "WOW!") self.wow.setSize(30) self.wow.setTextColor("red") self.wow.draw(self.pWin) sleep(3) self.tier.undraw() self.wow.undraw() return True else: return False # First Ball Used for Multiple-Ball Pong def checkContactBallA(self): xMiddle = self.p.getMiddle().getX() xPadLeft = xMiddle - 5 xPadRight = xMiddle + 5 xCenter = self.b.getCenter().getX() xBallRight = xCenter + self.b.getRadius() xBallLeft = xCenter - self.b.getRadius() yMiddle = self.p.getMiddle().getY() yPadTop = yMiddle - 50 yPadBottom = yMiddle + 50 yCenter = self.b.getCenter().getY() yBallTop = yCenter - self.b.getRadius() yBallBottom = yCenter + self.b.getRadius() # If the x value of right side of the ball is = to the x value of the left side of the paddle, # and the y value of the top/bottom of the ball is not outside the y value of the top/bottom of the paddle, # then the ball has made contact if (xBallRight >= xPadLeft and yBallBottom >= yPadTop) and (xBallRight >= xPadLeft and yBallTop <= yPadBottom): self.hits += 1 self.score += 1 self.userScore.setText(self.score) if self.hits % 4 == 0: self.level += 1 self.userLevel.setText(self.level) self.b.goFaster() if self.level % 10 == 0: self.tier = Text(Point(250, 250), "You have reached a new tier") self.tier.setTextColor("red") self.tier.setSize(20) self.tier.draw(self.pWin) self.wow = Text(Point(250, 81), "WOW!") self.wow.setSize(30) self.wow.setTextColor("red") self.wow.draw(self.pWin) sleep(3) self.tier.undraw() self.wow.undraw() return True else: return False # Second Ball Used for Multiple-Ball Pong def checkContactBallB(self): xMiddle = self.p.getMiddle().getX() xPadLeft = xMiddle - 5 xPadRight = xMiddle + 5 xCenter2 = self.b.getCenter2().getX() xBallRight2 = xCenter2 + self.b.getRadius2() xBallLeft2 = xCenter2 - self.b.getRadius2() yMiddle = self.p.getMiddle().getY() yPadTop = yMiddle - 50 yPadBottom = yMiddle + 50 yCenter2 = self.b.getCenter2().getY() yBallTop2 = yCenter2 - self.b.getRadius2() yBallBottom2 = yCenter2 + self.b.getRadius2() # If the x value of right side of the ball is = to the x value of the left side of the paddle, # and the y value of the top/bottom of the ball is not outside the y value of the top/bottom of the paddle, # then the ball has made contact if (xBallRight2 >= xPadLeft and yBallBottom2 >= yPadTop) and (xBallRight2 >= xPadLeft and yBallTop2 <= yPadBottom): self.hits += 1 self.score += 1 self.userScore.setText(self.score) if self.hits % 4 == 0: self.level += 1 self.userLevel.setText(self.level) self.b.goFaster() if self.level % 3 == 0: self.tier = Text(Point(250, 250), "You have reached a new tier") self.tier.setTextColor("red") self.tier.setSize(20) self.tier.draw(self.pWin) self.wow = Text(Point(250, 81), "WOW!") self.wow.setSize(30) self.wow.setTextColor("red") self.wow.draw(self.pWin) sleep(3) self.tier.undraw() self.wow.undraw() return True else: return False def gameOver(self): # If the ball goes past the paddle, the game is over and the user is asked to play again xCenter = self.b.getCenter().getX() xBallLeft = xCenter - self.b.getRadius() xCenter2 = self.b.getCenter2().getX() xBallLeft2 = xCenter2 - self.b.getRadius2() xMiddle = self.p.getMiddle().getX() xPadRight = xMiddle + 5 if (xBallLeft > xPadRight) or (xBallLeft2 > xPadRight): loser = Text(Point(250, 150), "GAME OVER!") loser.setSize(25) loser.setTextColor("red") again = Text(Point(250, 200), "PLAY AGAIN?") again.setSize(25) again.setTextColor("red") loser.draw(self.pWin) again.draw(self.pWin) return True def restart(self): # If the player types 'yes', the game will restart completely restart = input("\nWould You Like To Restart (yes/no)? ") if restart.lower() == "yes": self.pWin.close() newGame = Pong() print("WARNING!! IN SHRINKING MODE, PADDLE RESETS TO MIDDLE AFTER EACH LEVEL") game = input("Which version would you like to play: 'shrinking mode' (s), 'multiple mode' (m), or 'normal mode' (n)? ") newGame.play(game) else: self.pWin.close() def play(self, ans): # The user will be given 3 seconds after asked to play until the game begins sleep(1) self.ready = Text(Point(250, 81), "Are You Ready?") self.ready.setSize(30) self.ready.setTextColor("red") self.ready.draw(self.pWin) self.three = Text(Point(250, 200), "THREE") self.three.setSize(35) self.three.setTextColor("white") self.three.draw(self.pWin) sleep(1) self.three.undraw() self.two = Text(Point(250, 200), "TWO") self.two.setSize(35) self.two.setTextColor("white") self.two.draw(self.pWin) sleep(1) self.two.undraw() self.one = Text(Point(250, 200), "ONE") self.one.setSize(35) self.one.setTextColor("white") self.one.draw(self.pWin) sleep(1) self.one.undraw() self.ready.undraw() while True: click = self.pWin.checkMouse() if click != None: self.p.movePad(click) if ans.lower() == 's': if self.checkContactShrink(): self.b.reverseX() elif ans.lower() == 'm': if self.checkContactBallA(): self.b.reverseX() if self.checkContactBallB(): self.b.reverse2X() self.b.moveBall2(self.pWin) elif ans.lower() == 'n': if self.checkContact(): self.b.reverseX() else: print("\nOh Well, I Didn't Want To Play With You Anyway!") self.b.moveBall(self.pWin) if self.gameOver(): self.restart()