コード例 #1
0
ファイル: main.py プロジェクト: bmwalters/terminal-pong
class Game():
	def __init__(self):
		self.window = curses.initscr()
		self.window.nodelay(True)
		self.window.keypad(True)
		curses.cbreak()

		SCRH, SCRW = self.window.getmaxyx()

		self.ball = Ball(2, 2)
		self.paddle1 = Paddle(0, 0, 5, [curses.KEY_LEFT, curses.KEY_RIGHT])
		self.paddle2 = Paddle(0, SCRH - 1, 5, [97, 100])

		self.scorex = 0
		self.scorey = 0
		self.score = Label(1, 1, "Score: 0:0")

	def loop(self):
		while True:
			key = self.window.getch()

			self.ball.update(self.window, [self.paddle1, self.paddle2])
			self.paddle1.update(self.window, key)
			self.paddle2.update(self.window, key)

			self.window.clear()
			draworder = sorted([self.ball, self.paddle1, self.paddle2, self.score], key=lambda o: o.x)
			for o in draworder:
				o.draw(self.window)
			self.window.refresh()

			curses.flushinp()

			curses.napms(1000 / TICKRATE)
コード例 #2
0
ファイル: pong.py プロジェクト: piotut/Pong
    def __init__(self, file1=None, file2=None):
        pygame.mixer.pre_init(44100, -16, 2, 2048)
        pygame.init()
        self.fps = pygame.time.Clock()
        flag = DOUBLEBUF

        self.board = pygame.display.set_mode(screenRect, flag)
        pygame.display.set_caption('[ --- Pong --- ]')

        self.state = 1  # 1 - run, 0 - exit

        self.track = Tracking(file1, file2)

        self.sound = Sound()
        self.p1 = Paddle(self.board, (200,100,100),screenRect)
        self.p1.setInitialPostition(0,screenHeight/2)
        self.p2 = Paddle(self.board, (100,200,100),screenRect)
        self.p2.setInitialPostition(screenWidth-self.p2.get()['width'],screenHeight/2)
        self.ball = Ball(self.board, (50,50,250), screenRect, self.sound)
        self.ball.setInitialPostition(screenWidth/2,screenHeight/2)
        self.arena = Arena(self.board, screenRect)
        self.referee = Referee(self.ball, self.p1, self.p2, screenRect, self.sound)

        

        self.t = Thread(target=self.track.run)
        #self.track.run()
        self.t.start()

        self.p1_pos = 0
        self.p2_pos = 0

        self.loop()
コード例 #3
0
ファイル: main.py プロジェクト: bmwalters/terminal-pong
	def __init__(self):
		self.window = curses.initscr()
		self.window.nodelay(True)
		self.window.keypad(True)
		curses.cbreak()

		SCRH, SCRW = self.window.getmaxyx()

		self.ball = Ball(2, 2)
		self.paddle1 = Paddle(0, 0, 5, [curses.KEY_LEFT, curses.KEY_RIGHT])
		self.paddle2 = Paddle(0, SCRH - 1, 5, [97, 100])

		self.scorex = 0
		self.scorey = 0
		self.score = Label(1, 1, "Score: 0:0")
コード例 #4
0
ファイル: game.py プロジェクト: RecklessYan/Breakout-Clone
	def __init__(self):
		super(GameLayer, self).__init__(randint(0, 255), randint(0, 255), randint(0, 255), 255)
		# 添加一个 板子
		self.paddle = Paddle('images/ban.png')
		self.add(self.paddle.sprite)
		self.ball = Ball('images/qiu.png')
		self.add(self.ball.sprite)
		self.level = 0
		# 添加一个 label 显示当前的游戏状态
		self.hud = Label('Score: 0',
						 color=(randint(0, 255), randint(0, 255), randint(0, 255), 255))
		self.hud.position = (0, 450)
		self.add(self.hud)
		self.hud2 = Label('Level: 1',
						  color=(randint(0, 255), randint(0, 255), randint(0, 255), 255))
		self.hud2.position = (100, 450)
		self.add(self.hud2)
		# 添加一个变量来记录金币
		self.score = 0
		# 设置 4 个按键状态
		self.key_pressed_left = False
		self.key_pressed_right = False
		self.key_pressed_up = False
		self.key_pressed_down = False

		self.blocks = []
		# 调用 reset 函数初始化状态
		self.gamestart()
		# 定期调用 self.update 函数
		# FPS frame per second 每秒帧数
		self.schedule(self.update)
コード例 #5
0
ファイル: levels.py プロジェクト: Kranek/BlockBuster
 def __init__(self, screen, draw_offset, control_set, player_color, finish_game):
     """
     Init with... way too many parameters
     :param screen: Main PyGame surface to draw the objects/UI on
     :param draw_offset: Drawing offset used in multiplayer
     :param control_set: Key-set used to control the Paddle
     :param player_color: Color of the player's Paddle
     :param finish_game: Function passed to the constructor, triggered on
     the game end
     :return:
     """
     self.screen = screen
     self.draw_offset = draw_offset
     self.control_set = control_set
     self.prev_input_x = 0
     self.level_number = 1
     self.block_count = 0
     self.player = Player("Derp")
     self.paddle = Paddle(LEVEL_WIDTH/2 - Paddle.WIDTH/2, LEVEL_HEIGHT - 40,
                          player_color, parent=self, owner=self.player)
     self.ball = Ball(self.paddle.rect.x + Paddle.WIDTH/2 - Ball.RADIUS,
                      self.paddle.rect.y - Ball.RADIUS * 2)
     self.items = None
     self.blocks = []
     self.blocks_surface = None
     self.blocks_surface_dirty = True
     self.entities = []
     self.font = Assets.font
     self.score_label = None
     self.lives_label = None
     self.level_label = None
     self.load_level(self.level_number)
     self.finish_game = finish_game
    def __init__(self):
        super(GameLayer, self).__init__(246, 226, 76, 255)
        # 添加一个 板子
        self.paddle = Paddle('images/ban.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/qiu.png')
        self.add(self.ball.sprite)

        # 添加一个 label 显示当前的游戏状态
        self.hud = Label('金币: 0',
                         color=(0, 0, 0, 255))
        self.hud.position = (0, 450)
        self.add(self.hud)
        # 添加一个变量来记录金币
        self.gold = 0
        # 设置 4 个按键状态
        self.key_pressed_left   = False
        self.key_pressed_right  = False
        self.key_pressed_up     = False
        self.key_pressed_down   = False

        self.blocks = []
        # 调用 reset 函数初始化状态
        self.reset()
        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)
	def __init__(self):
		super(GameLayer, self).__init__()
		# 添加一个 板子
		self.paddle = Paddle('images/ash.png')
		self.add(self.paddle.sprite)
		self.ball = Ball('images/pokem.png')
		self.add(self.ball.sprite)

		# 添加一个 label 显示当前的游戏状态
		self.hud = Label('皮卡丘: 0')
		self.hud.position = (0, 450)
		self.add(self.hud)
		# 添加一个 label 显示当前游戏关卡
		self.level = Label('Level 1')
		self.level.position = (100, 450)
		self.add(self.level)
		# 添加一个变量来记录金币
		self.gold = 0
		# 设置 4 个按键状态
		self.key_pressed_left = False
		self.key_pressed_right = False
		self.key_pressed_up = False
		self.key_pressed_down = False

		self.blocks = []
		# 调用 reset 函数初始化状态
		self.reset()
		# 定期调用 self.update 函数
		# FPS frame per second 每秒帧数
		self.schedule(self.update)
コード例 #8
0
ファイル: gui-network.py プロジェクト: jrcapriles/Pong
 def initUI(self):
   
     self.parent.title("Pong")        
     self.pack(fill=BOTH, expand=1)
     
     self.canvas = Canvas(self, bg="#"+str(self.bg_status)+str(self.bg_status)+str(self.bg_status))
     
     self.left = Paddle(self.canvas, 1, [30, 10], 10, 100,"#fb0")
     self.right = Paddle(self.canvas, 1, [570, 40], 10, 100,"#05f")        
     
     self.balls.append(Ball(self.canvas,1,[70,70],10,[-2,-2]))
     #self.balls.append(Ball(self.canvas,1,[100,100],10,[2,2]))
     #self.balls.append(Ball(self.canvas,1,[200,100],10,[2,-2]))
     #self.balls.append(Ball(self.canvas,1,[100,200],10,[-2,2]))
     
     self.obs.append(Obstacle(self.canvas,[200,200],"Pin",6))
     self.obs.append(Obstacle(self.canvas,[400,300],"Paddle",7))
     self.obs.append(Obstacle(self.canvas,[350,350],"Pin",4))
     self.obs.append(Obstacle(self.canvas,[210,250],"Paddle",8))
     self.obs.append(Obstacle(self.canvas,[250,250],"Size",8))
     self.obs.append(Obstacle(self.canvas,[300,350],"Switch",8))
     self.obs.append(Obstacle(self.canvas,[400,350],"Switch",8))
     self.obs.append(Obstacle(self.canvas,[420,320],"Teleport",6))
     self.obs.append(Obstacle(self.canvas,[250,200],"Gravity",8))
     self.obs.append(Obstacle(self.canvas,[300,50],"Reset",4,[0,1]))
     
     self.canvas.pack(fill=BOTH, expand=1)
     
     self.score_msg = '  Home  0 - 0  Visitor  '
     self.label_score = Label(self, text=self.score_msg, width=len(self.score_msg), bg='yellow')
     
     self.choices = ['Easy', 'Medium', 'Hard']
     self.dificulty = StringVar()
     self.dificulty.set('Medium')
     self.option = OptionMenu(self, self.dificulty, *self.choices)
     self.option.pack(side=LEFT, fill=BOTH)
     self.label_score.pack(side= LEFT, fill=BOTH)
     
     self.text = ""
     self.text_canvas = self.canvas.create_text(300,10, text=self.text, fill="white")
     
     self.after(200, self.update)
コード例 #9
0
ファイル: pong.py プロジェクト: progworkshop/pong
    def __init__(self, width=640, height=480, title="Prog Workshop - Pong!"):
        pygame.init()

        # Sets key repeat to a max of once every 5 ms
        #pygame.key.set_repeat(5, 5)
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption(title)
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        self._running = True
        
        self.player1 = Paddle(0,0,20,100,self)
        self.player2 = Paddle(width-20,0,20,100,self)
        
        self.ball = Ball(width/2,height/2,20,20,self)
        self.ball.setSpeed(random.random()*14-7, random.random()*14-7)

        self.balls = []

        self.score = Scoreboard(self, 36)
コード例 #10
0
ファイル: player.py プロジェクト: jrcapriles/Pong
class Player(object):
 
    difficulty = {"Easy": 7.5,
                  "Medium": 15,
                  "Hard": 20}   
    
    def __init__(self, canvas, name="CPU", difficulty="Medium", pos=[70,70], width = 10, height=100, color="#fb0"):
        
        self.canvas = canvas        
        self.name = name
        self.pos = pos
        self.width = width
        self.height = height
        self.turn = True
        self.color =color
        
        self.player_steps={"Up": self.difficulty[difficulty],
                           "Down": -self.difficulty[difficulty]}
        
        self.paddle = Paddle(self.canvas, 1, self.pos, self.width, self.height, self.color)
       

    def check_collision(self, ball_xy):
        return self.paddle.check_collision(ball_xy)


    def update(self, ball):
        pos = self.paddle.get_position()
        if (pos[1]>ball.get_center()[1]):
            self.paddle.update_position(self.player_steps["Up"])
        else:
            self.paddle.update_position(self.player_steps["Down"])
コード例 #11
0
ファイル: board.py プロジェクト: Nolski/rm-out
    def __init__(self, window, path="."):

        self.window = window
        self.h, self.w = window.getmaxyx()

        self.cells_x = self.w // Block.WIDTH
        self.cells_y = self.h // Block.HEIGHT
        self.field = [[None] * self.cells_x  for i in range(self.cells_y)]

        self._gen_blocks(path)
        self.ball = Ball(self.h-2, self.w//2)

        self.paddle = Paddle(self.h-1, self.w//2)
コード例 #12
0
ファイル: player.py プロジェクト: jrcapriles/Pong
 def __init__(self, canvas, name="CPU", difficulty="Medium", pos=[70,70], width = 10, height=100, color="#fb0"):
     
     self.canvas = canvas        
     self.name = name
     self.pos = pos
     self.width = width
     self.height = height
     self.turn = True
     self.color =color
     
     self.player_steps={"Up": self.difficulty[difficulty],
                        "Down": -self.difficulty[difficulty]}
     
     self.paddle = Paddle(self.canvas, 1, self.pos, self.width, self.height, self.color)
コード例 #13
0
ファイル: core.py プロジェクト: ovoNiku/blockhittter
    def __init__(self, game, level=0):
        super().__init__(game)
        self.level = level

        ball = Ball()
        paddle = Paddle()
        blocks = []
        for i in game.config.get('level')[self.level]:
            blocks.append(Block(i))

        self.register_action(pygame.K_LEFT, paddle.move_left)
        self.register_action(pygame.K_RIGHT, paddle.move_right)
        self.register_action(pygame.K_SPACE, ball.fire)
        self.register_action(pygame.K_ESCAPE, sys.exit)
        self.draw(ball=ball, paddle=paddle, blocks=blocks)
コード例 #14
0
ファイル: main.py プロジェクト: vjspranav/BrickBreaker
def activate_power_up(power_up):
    global curNumPaddles
    timer = 0
    # Expand
    if power_up.number == 0:
        if len(paddle) <= 3:
            p4 = Paddle(4, 14, len(paddle))
            p5 = Paddle(5, 14, len(paddle) + 1)
            paddle.append(p4)
            paddle.append(p5)
            grid[14][p4.y].add_paddle(p4)
            grid[14][p5.y].add_paddle(p5)
            while timer < 15:
                time.sleep(1)
                timer += 1
            grid[14][p4.y].remove_paddle()
            grid[14][p5.y].remove_paddle()
            paddle.remove(p4)
            paddle.remove(p5)
            power_ups.remove(power_up)
            return 1
    if power_up.number == 1:
        ball.decrease_life()
        power_ups.remove(power_up)
コード例 #15
0
ファイル: game.py プロジェクト: pavani-17/Brick-Breaker
    def nextLevel(self):
        self._level += 1
        self._screen.flash()
        if (self._level == 2):
            self.bricks_pos = self.bricks_pos_l2
        elif (self._level == 3):
            threading.Thread(target=playsound,
                             args=('boss.wav', ),
                             daemon=True).start()
            self.bricks_pos = self.bricks_pos_l3
            pos = self._paddle.getPosition()
            size = self._paddle.getSize()
            self._isUfo = True
            self._ufo = Ufo(np.array([2, pos[1] + size[1] / 2]))
        else:
            time_temp = int(time.time() - self._start_time)
            self._screen.gameOver(win=True,
                                  score=(self._score +
                                         max(0, (1000 - time_temp) / 100)))
            quit()

        self._move = False
        self._len = self.bricks_pos.shape[0]
        self.powerup = []
        self._laser = False
        self.laserbeams = []
        self.createBricks()
        self._paddle = Paddle(
            np.array([config.HEIGHT - 3, config.WIDTH / 2 - 7]),
            np.array([1, 16]))
        self._ball = []
        self._ball.append(
            Ball(np.array([config.HEIGHT - 4, config.WIDTH / 2]),
                 np.array([-1, 0]), True))
        self._balls = 1
        self.lastMove = time.time()
コード例 #16
0
ファイル: main.py プロジェクト: crkubiak/terminal-pong
class Game():
    def __init__(self):
        self.window = curses.initscr()
        self.window.nodelay(True)
        self.window.keypad(True)
        curses.cbreak()

        SCRH, SCRW = self.window.getmaxyx()

        self.ball = Ball(2, 2)
        self.paddle1 = Paddle(0, 0, 5, [curses.KEY_LEFT, curses.KEY_RIGHT])
        self.paddle2 = Paddle(0, SCRH - 1, 5, [97, 100])

        self.scorex = 0
        self.scorey = 0
        self.score = Label(1, 1, "Score: 0:0")

    def loop(self):
        while True:
            key = self.window.getch()

            self.ball.update(self.window, [self.paddle1, self.paddle2])
            self.paddle1.update(self.window, key)
            self.paddle2.update(self.window, key)

            self.window.clear()
            draworder = sorted(
                [self.ball, self.paddle1, self.paddle2, self.score],
                key=lambda o: o.x)
            for o in draworder:
                o.draw(self.window)
            self.window.refresh()

            curses.flushinp()

            curses.napms(1000 / TICKRATE)
コード例 #17
0
    def __init__(self):
        '''
            Explanation: The initialisation function (constructor). It is called when object of the class is created. Clears the screen and initialises the class variables and creates required objects of other classes

            Class Variables:
                H, W: Height and Width of the terminal
                T: Stores the size of the upper wall
                P_T: Stores the thickness of the paddle
                pattern: Stores the terminal as 2D array, storing each pixel as a character
                tiles: Stores the required relation between HP of bricks and character associated
                release: Stores information regarding whether ball has been released or not from the paddle
                time: Stores the time passed since the game began
                score: Stores the score since the game began
                life: Stores the number of life a player has
        '''
        os.system('clear')
        self.H, self.W = os.popen('stty size', 'r').read().split()
        self.H = int(self.H)
        self.W = int(self.W)
        self.T = Y_WALL
        self.P_T = PADDLE_THICKNESS
        self._layout = Layout(self.H, self.W)
        self.pattern = self._layout.layout()
        self.tiles = self._layout.getTiles()
        self.brick = Brick(self.tiles)
        self.paddle = Paddle(self.H, self.W, self.pattern)
        self.ball = Ball(self.H, self.W, self.pattern)
        self.release = False
        self.one = One(self.tiles)
        self.two = Two(self.tiles)
        self.three = Three(self.tiles)
        self.four = Four(self.tiles)
        self.five = Five(self.tiles)
        self.time = 0
        self.score = 0
        self.life = 1
コード例 #18
0
    def __init__(self, four_player=False):
        self.ball = Ball(PongGame.window_width / 2, PongGame.window_height / 2)
        self.paddle1 = NNPaddle(PongGame.window_width - 50,
                                PongGame.window_height / 2, self.ball, self)
        self.paddle2 = AIPaddle(50, PongGame.window_height / 2, self.ball,
                                self)
        self.paddle3 = None
        self.paddle4 = None

        self.temp_paddle = None
        self.four_player = four_player

        self.winner = None
        self.game_over = False
        self.speed = 1000
        self.scores = [0, 0]
        self.timeout = 0
        self.pause = False

        if self.four_player:
            PongGame.window_width = 650
            PongGame.window_height = 650

            self.ball = Ball(PongGame.window_width / 2,
                             PongGame.window_height / 2)
            self.scores = [0, 0, 0, 0]
            self.paddle1 = NNPaddle(PongGame.window_width - 50,
                                    PongGame.window_height / 2, self.ball,
                                    self, True)
            self.paddle2 = NNPaddle(50, PongGame.window_height / 2, self.ball,
                                    self, True)
            self.paddle3 = SidewaysNNPaddle(PongGame.window_width / 2,
                                            PongGame.window_height - 50,
                                            self.ball, self)
            self.paddle4 = SidewaysNNPaddle(PongGame.window_width / 2, 50,
                                            self.ball, self)
コード例 #19
0
    def __init__(self):
        #game window
        pygame.init()
        self.size = self.width, self.height = (640, 480)
        self.screen = pygame.display.set_mode(self.size)
        self.black = (0, 0, 0)

        #game scores
        self.score_p1 = 0
        self.score_p2 = 0

        #paddle
        self.paddle = Paddle()
        #player2 paddle
        self.opponent = Opponent()
        #ball
        self.ball = Ball()

        pygame.key.set_repeat(10, 5)

        #opponent presses space
        self.space_host = False
        self.space_client = False
        self.direction = None
コード例 #20
0
ファイル: ball.py プロジェクト: arsaizdihar/breakout-game
 def player_collision(self, player: Paddle):
     if self.circle:
         rect = player.get_rect()
         player_left = rect.left
         if rect.colliderect(
                 self.circle) and self.circle.top - self.vel_y <= rect.top:
             self.y = rect.top - SIZE
             self.angle = 30 + (
                 1 -
                 (self.circle.centerx - player_left) / player.width) * 120
             if self.angle < 30:
                 self.angle = 30
             elif self.angle > 150:
                 self.angle = 150
             return True
コード例 #21
0
ファイル: my_agents.py プロジェクト: sujaygarlanka/pong-ai
    def train(self):
        lr = 0.2
        num_episodes = 1000
        max_steps_per_episode = 5000
        gamma = 0.99

        env = Paddle()
        for episode in range(num_episodes):
            state = env.reset()
            score = 0
            for step in range(max_steps_per_episode):
                action = self.select_action(state)
                reward, next_state, done = env.step(action)
                new_q_value = lr * (
                    (self.get_q_value(next_state) * gamma) +
                    reward) + (1 - lr) * agent.get_q_value(state, action)
                self.set_q_value(state, action, new_q_value)

                score += reward
                state = next_state
                if done:
                    break
            print("episode: {}/{}, score: {}".format(episode + 1, num_episodes,
                                                     score))
コード例 #22
0
class pongGame():
    def __init__(self):
        super().__init__()
        self.hits =0
        self.miss =0
        self.screensize = (640,480)
        self.screen = pygame.display.set_mode(self.screensize)
        self.pong = Pong(self.screensize)
        self.paddle = Paddle(self.screensize)
        self.done = False
        self.reward=0
    
    def reset(self):
        self.pong=Pong(self.screensize)
        self.paddle=Paddle(self.screensize)
        return [self.paddle.centerx*0.01, self.pong.centerx*0.01, self.pong.centery*0.01, self.pong.speedx, self.pong.speedy]
    
    def step(self,action):
        self.reward = 0
        self.done = 0
        
        if action == 0:
            self.paddle.direction=-1
            self.paddle.update()
            self.reward -= .1

        if action == 2:
            self.paddle.direction=1
            self.reward -= .1

        self.update()

        state = [self.paddle.centerx*0.01, self.pong.centerx*0.01, self.pong.centery*0.01, self.pong.speedx, self.pong.speedy]
        return self.reward, state, self.done

    def update(self):
        self.paddle.update()
        newhits=self.pong.update(self.paddle,self.hits)
        if self.hits < newhits:
            self.reward +=3
            self.hits=newhits
        if self.pong.hit_edge_bottom:
            self.miss +=1
            self.reward -= 3
            self.done=True
        self.screen.fill((0,0,0))
        self.paddle.render(self.screen)
        self.pong.render(self.screen)
        #Display scores:
        font = pygame.font.Font(None, 30)
        text = font.render("Hit: "+str(self.hits), 1, white)
        self.screen.blit(text, (250,10))
        text = font.render("Miss: "+str(self.miss), 1, white)
        self.screen.blit(text, (350,10))
        pygame.display.flip()        
コード例 #23
0
    def testBallHitPlayer(self):
        print('Describe: test Ball Collision with player Paddle')
        tests = [
            {'x': 37, 'y': 160, 'speed':[-3,3], 'expcX': 37, 'expcY': 160, 'expcVel': [3,3]},
            {'x': 30, 'y': 160, 'speed':[-3,3], 'expcX': 37, 'expcY': 160, 'expcVel': [3,3]},
            {'x': 65, 'y': 160, 'speed':[-3,3], 'expcX': 65, 'expcY': 160, 'expcVel': [-3,3]},
            {'x': 45, 'y': 100, 'speed':[-3,3], 'expcX': 45, 'expcY': 100, 'expcVel': [-3,3]}
        ]
        for t in tests:
            b = Ball(t['x'], t['y'], t['speed'])
            p = Paddle(27)
            b.hitPlayer(p)

            self.assertEqual(b.rect.x, t['expcX'], 'x should be ' + str(t['expcX']))
            self.assertEqual(b.rect.y, t['expcY'], 'y should be ' + str(t['expcY']))
            self.assertListEqual(b.vel, t['expcVel'], 'Vel should be ' + str(t['expcVel']))
コード例 #24
0
ファイル: game.py プロジェクト: LBPeraza/Juicy-Breakout
 def init(self):
     self.camera = Camera(self.width, self.height,
                          Vector2(self.width // 2, self.height // 2))
     self.blocks = self.structured_blocks(5, 5)
     self.dead_blocks = pygame.sprite.Group()
     self.bg_color = (0, 0, 0)
     self.paddle = pygame.sprite.GroupSingle(
         Paddle(self.camera, Vector2(self.width / 2,
                                     self.height - Paddle.height)))
     self.ball = pygame.sprite.GroupSingle(
         Ball(self.camera, Vector2(self.width / 2, self.height / 2)))
     self.mouse_pos = None
     self.track_paddle = self.paddle.sprite
     self.ball.sprite.track_to_paddle(self.track_paddle)
     self.camera_v = Vector2(0, 0)
     self.inverted = False
コード例 #25
0
    def update(self, entities, paddles, coins):
        for row in self.level:  # вся строка
            for col in row:  # каждый символ
                if col == "-":
                    # создаем блок, заливаем его цветом и рисеум его
                    pf = Paddle(self.x, self.y)
                    entities.add(pf)
                    paddles.append(pf)
                if col == "#":
                    coin = Coin(self.x, self.y)
                    entities.add(coin)
                    coins.append(coin)

                self.x += conf.BLOCK_WIDTH  # блоки платформы ставятся на ширине блоков
            self.y += conf.BLOCK_HEIGHT  # то же самое и с высотой
            self.x = 0
コード例 #26
0
ファイル: breakout.py プロジェクト: oc-cs170/breakout
	def __init__(self):
		# Initilaize pygame and the display/window
		pygame.init()
		self.screen_width, self.screen_height = 600, 800
		self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))  # , pygame.FULLSCREEN)
		pygame.display.set_caption('Breakout')
		
		# Create the game objects
		self.paddle = Paddle(self.screen_width, self.screen_height)
		self.ball = Ball(self.screen_width, self.screen_height)
		self.bricks = list()
		for i in range(0,600,60):
			for j in range(42, 211, 42):
				self.bricks.append(Brick(self.screen_width, self.screen_height, i, j))

		# Let's control the frame rate
		self.clock = pygame.time.Clock()
コード例 #27
0
    def run(self):
        scoreboard = Scoreboard()

        pad_l = Paddle(POS_LEFT)
        pad_l.register_listener(self.screen)
        pad_r = Paddle(POS_RIGHT)
        pad_r.register_listener(self.screen)

        ball = Ball()

        while self.running:
            start = time.time()

            ball.move()
            ball.collision(pad_l, pad_r, scoreboard)
            scoreboard.update_score()

            self.screen.update()
            time.sleep(max(1.0 / 10 - (time.time() - start), 0))
コード例 #28
0
ファイル: game.py プロジェクト: rvk7895/BrickBreaker
def reset():
    global lives
    global pd
    global ball
    global attached
    global ACTIVE_POWERUPS

    lives -= 1

    for i in range(pd.length):
        CANVAS[pd.y][pd.x + i] = " "

    pd = Paddle()
    ball = Ball()
    ACTIVE_POWERUPS = []
    for powerup in POWERUPS:
        powerup.ball = ball

    attached = True
コード例 #29
0
def main():
    # Setup board and its components
    game_board = Screen()
    game_board.setup(width=800, height=600)
    game_board.bgcolor("black")
    game_board.tracer(0)
    game_board.listen()
    scoreboard = Scoreboard((0, game_board.window_height()/2-40))
    paddle_one = Paddle(((game_board.window_width()/2)-40, 25))
    paddle_two = Paddle((-(game_board.window_width()/2)+40, 25))
    ball = Ball()

    # Setup generic keys
    game_board.onkey(game_board.bye, "Escape")
    game_board.onkey(ball.increase_speed, "KP_Add")
    game_board.onkey(ball.decrease_speed, "KP_Subtract")
    # Setup player keys
    game_board.onkey(paddle_one.up, "Up")
    game_board.onkey(paddle_one.down, "Down")
    game_board.onkey(paddle_two.up, "q")
    game_board.onkey(paddle_two.down, "a")

    # Run the game
    game_is_on = True
    while game_is_on:
        game_board.update()
        time.sleep(ball.game_speed)
        ball.move()

        # bounce off top/bottom wall
        if ball.ycor() > (game_board.window_height()/2-20) or ball.ycor() < -game_board.window_height()/2+20:
            ball.change_direction()

        # hit paddle
        if (ball.xcor() > game_board.window_width()/2 - 70 and paddle_one.distance(ball) < 50) or \
                (ball.xcor() < -game_board.window_width()/2 + 70 and paddle_two.distance(ball) < 50):
            ball.change_direction(True)
            # Randomly increase the game speed a little
            if randint(0, 3) == 2:
                ball.game_speed *= 0.9

        # hit back wall and score point
        if ball.xcor() > game_board.window_width()/2 - 20:
            scoreboard.update_score(1)
            ball.reset_game()
        if ball.xcor() < -game_board.window_width()/2 + 20:
            scoreboard.update_score(0)
            ball.reset_game()

    game_board.exitonclick()
コード例 #30
0
 def fillthescreen(self, paddleobj, ballobj, brickobj, powerupobj,
                   cannonobj, bulletobj, num):
     ballobj = []
     brickobj = []
     powerupobj = []
     cannonobj = []
     bulletobj = []
     sco = 0
     if len(paddleobj) != 0:
         sco = paddleobj[0].get_score()
     paddleobj = []
     paddleobj.append(
         Paddle(FRAMEHEIGHT - 2, int(FRAMEWIDTH / 2), 1, 7, 0, 0))
     paddleobj[0]._score = sco
     ballobj.append(
         Ball(FRAMEHEIGHT - 3,
              paddleobj[0]._y + int(paddleobj[0]._ylength / 2), 1, 1, -2,
              2))
     brickobj, powerupobj = self.fillBricks(num)
     return paddleobj, ballobj, brickobj, powerupobj, cannonobj, bulletobj
コード例 #31
0
def init_game():
    global screen, score, ball, wall, paddle
    
    screen = Screen()
    screen.bgcolor("black")
    screen.setup(width=800, height=600)
    screen.title("Breakout")
    screen.tracer(0)

    wall = BlockBuilder()
    wall.create_wall(SCREEN_SIZE)
    paddle = Paddle(STARTING_POSITION,SCREEN_SIZE)
    ball = Ball(SCREEN_SIZE)

    score = Scoreboard()

    screen.listen()
    screen.update()
    screen.onkeypress(paddle.go_left, "Left")
    screen.onkeypress(paddle.go_right, "Right")
コード例 #32
0
def create_paddles(p_settings, screen, paddles):
    """Create all the paddles in their original positions."""
    paddle_right = Paddle(p_settings, screen, 'right', 'vert')
    paddle_left = Paddle(p_settings, screen, 'left', 'vert')
    paddle_tr = Paddle(p_settings, screen, 'tr', 'hor')
    paddle_tl = Paddle(p_settings, screen, 'tl', 'hor')
    paddle_br = Paddle(p_settings, screen, 'br', 'hor')
    paddle_bl = Paddle(p_settings, screen, 'bl', 'hor')

    paddles.add(paddle_right)
    paddles.add(paddle_left)
    paddles.add(paddle_tr)
    paddles.add(paddle_tl)
    paddles.add(paddle_br)
    paddles.add(paddle_bl)
コード例 #33
0
 def __init__(self):
     self.action_publisher = rospy.Publisher('move_player_paddle',
                                             MovePlayerPaddle,
                                             queue_size=10)
     #Wait until the game node starts running
     print 'Waiting to get game information'
     rospy.wait_for_service('game_info')
     try:
         get_game_info = rospy.ServiceProxy('game_info', GameInfo)
         game_info = get_game_info()
         self.board_length = game_info.board_length
         self.board_width = game_info.board_width
         self.ball_speed = game_info.ball_speed
         self.scale = game_info.scale
         self.player = Paddle(self.board_width / 2, self.board_length)
         print 'Ready to win!'
         #For listening ball movements
         rospy.Subscriber("ball_info", BallInfo, self.move_player_paddle)
         self.move_msg = MovePlayerPaddle()
     except rospy.ServiceException, e:
         print 'Service call failed: %s' % e
コード例 #34
0
ファイル: game.py プロジェクト: SkylerKidd/CodeZ
    def __init__(self):
        #Initialize pygame and window
        pygame.init()
        self.screen_width, self.screen_height = 400, 600
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height), 0, 32)
        self.screen.fill(blue)
        pygame.display.update()

        #Clock
        self.clock = pygame.time.Clock()

        #Bricks
        self.blocks = list()
        for w in range(1,self.screen_width,50):
			for h in range(23, 198, 22):
				self.blocks.append(Block(self.screen_width, self.screen_height, w, h, orange, blue_shadow))

        #Paddle
        self.paddle = Paddle(self.screen_width, self.screen_height, purple, blue_shadow)

        #Ball
        self.ball = Ball(self.screen_width, self.screen_height, green, blue_shadow)
コード例 #35
0
ファイル: main.py プロジェクト: sruptash/Python-Breakout
    def loadSprites(self):
        """
        From here we can load all sprites needed, whether they
        are the paddle, balls, bricks, backgrounds, etc.
        """
        # level
        # Background and bricks defined in here
        self.level = Level(BreakoutMain.levels[self.currentLevel])

        # paddle
        self.paddle = Paddle(self.width, self.height)
        self.paddleSprite = pygame.sprite.GroupSingle(self.paddle)

        # ball
        self.mainBall = Ball((self.paddle.x, self.paddle.y),
                             self.paddle.height)
        self.ballSprites = pygame.sprite.RenderPlain(self.mainBall)

        for i in range(self.numBalls):
            ball = Ball((self.paddle.x, self.paddle.y),
                        self.paddle.height)
            self.ballSprites.add(ball)
コード例 #36
0
ファイル: game.py プロジェクト: rvk7895/BrickBreaker
def level_inc():
    global level
    global level_string
    global pd
    global ball
    global attached
    global ACTIVE_POWERUPS
    global game_won
    global level_start_time

    level_start_time = time()

    level += 1
    game_won = False

    file = None

    if level == 2:
        file = open(r"./Levels/Level_2.txt", "r")
    if level == 3:
        file = open(r"./Levels/Level_3.txt", "r")

    if not (file is None):
        level_string = file.read()

    set_bricks()

    for i in range(pd.length):
        CANVAS[pd.y][pd.x + i] = " "

    pd = Paddle()
    ball = Ball()
    ACTIVE_POWERUPS = []
    for powerup in POWERUPS:
        powerup.ball = ball

    attached = True
コード例 #37
0
    def set_up_level(self, level) -> None:
        if level == 0:
            return

        current_level = AVAILABLE_LEVELS[level - 1]

        # entities
        self.entities = [*current_level.entities]

        # bricks
        for i in range(BRICK_LINE_COUNT):
            for j in range(BRICK_LINE_COUNT):
                if current_level.layout[j][i]:
                    brick = Brick(
                        id=f"brick{i}{j}",
                        dimens=(BRICK_WIDTH, 1),
                        position=(BRICK_PADDING + (i * BRICK_WIDTH), 6 + j),
                        health=current_level.layout[j][i][0],
                        powerup=current_level.layout[j][i][1],
                        rainbow=(current_level.layout[j][i][0] > 0)
                        and (random.randint(0, 9) < BRICK_RAINBOW_CHANCE),
                    )
                    self.register(brick)

        # paddle
        paddle = Paddle(
            dimens=(PADDLE_WIDTH, 1),
            position=((self.width // 2) - (PADDLE_WIDTH // 2), self.height - 2),
        )
        self.register(paddle)

        # ball
        ball = Ball(
            start_position=((self.width // 2), self.height - 3),
        )
        self.register(ball)
コード例 #38
0
ファイル: arkanoid.py プロジェクト: DuhPhd/Arkanoid
    def __init__(self):
    
        from utilities import pygame, load_stages
        from text import Score, Timer, Name, Text
        from paddle import Paddle
        from ball import Ball
        from brick import Brick
        from stage import Stage
        
        C = Constants()
        self.C = C
        self.pygame = pygame

        # setup FPS governor
        self.clock = pygame.time.Clock()

        # set the window size
        divTop = int(C.DIV_POS*C.SIZE[1]) # top of divider. Affects bounds for ball
        divBot = divTop + C.DIV_WIDTH
        self.screen = pygame.display.set_mode(C.SIZE)
        area = pygame.Rect(0, divBot, C.SIZE[0], C.SIZE[1]-divBot)

        # create game screen objects/sprites
        self.score = Score(C.SCORE_POS, self.screen, C.SCORE_START, C.SCORE_COLOR, C.SCORE_SIZE)
        self.scoreText = Text(C.S_LABEL_POS, self.screen, C.S_LABEL_TEXT, C.S_LABEL_COLOR, C.S_LABEL_SIZE)
        self.timer = Timer(C.TIMER_POS, self.screen, C.TIMER_START, C.TIMER_COLOR, C.TIMER_SIZE)
        self.timerText = Text(C.T_LABEL_POS, self.screen, C.T_LABEL_TEXT, C.T_LABEL_COLOR, C.T_LABEL_SIZE)
        self.name = Name(C.NAME_POS, self.screen, '', C.NAME_COLOR)
        self.paddle = Paddle(area)
        self.ball = Ball(area)
        self.stages = load_stages(self.screen)
        self.divider = (self.screen, C.DIV_COLOR, [0, divTop], [C.SIZE[0], divTop], C.DIV_WIDTH)
        self.sprites = pygame.sprite.RenderPlain((self.paddle, self.ball))

        self.paused = True # flag to indicate if the stage is paused or moving 
        self.pausedReset = False # flag to indicate pause was due to reset, in which case dont pause timer
コード例 #39
0
ファイル: game.py プロジェクト: sreeharsha2002/Ball-Brick
 def _loopGame(self):
     paddleobj= []
     paddleobj.append(Paddle(FRAMEHEIGHT-2,int(FRAMEWIDTH/2),1,7,0,0))
     ballobj=[]
     ballobj.append(Ball(FRAMEHEIGHT-3,paddleobj[0]._y+int(paddleobj[0]._ylength/2),1,1,-2,2))
     brickobj=[]
     powerupobj=[]
     brickobj,powerupobj=self.fillBricks()
     flag=0
     while (self.status(brickobj,paddleobj)):
         getch=Get()
         ch=input_to(getch,0.1)
         if ch=='e':
             flag=1
             break
         if(ch=='f'):
             for i in ballobj:
                 i.isCollidedWithPaddle=False
         print("\033[0;0H")
         
         self._update(ballobj,paddleobj,ch,brickobj,powerupobj)
         self.checkBricks(brickobj,powerupobj)
         self.checkBall(ballobj,paddleobj)
         self.checkPowerupIsCollided(powerupobj)
         self.scores(paddleobj)
         self._printGame()
     if flag:
         print("You Exited")
         print(f"With Score {paddleobj[0].score}")
     else:
         if(self.lives==0):
             print("You Lost")
             print(f"With Score {paddleobj[0].score}")
         else:
             print("You Won")
             print(f"With Score {paddleobj[0].score}")
コード例 #40
0
def run_game():
    # Initialize pygame, settings and screen object
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("BREAKOUT clone by Cameron Tee")

    #Instantiate GameStats, Scoreboard and Messages
    stats = GameStats(settings)
    sb = Scoreboard(settings, screen, stats)
    msg = Messages(settings, screen)

    #Make the paddle, ball and group of bricks
    paddle = Paddle(settings, screen)
    ball = Ball(settings, screen, paddle)
    bricks = Group()

    #Creates a 'wall' (rows and columns) of bricks
    gf.build_wall(settings, screen, bricks)

    #Clock controlling the frequency of the screen updates
    clock = pygame.time.Clock()

    #Begin the main loop for the game
    while True:
        gf.check_events(paddle, ball, bricks, screen, settings, sb, stats, msg)
        #Player should be able to move around the paddle before releasing the ball
        if not stats.game_active:
            paddle.update()
            ball.center_ball(paddle)

        if stats.game_active:
            paddle.update()
            ball.update(paddle)
            gf.update_lives(paddle, ball, bricks, settings, screen, sb, stats)
            gf.update_bricks(bricks, ball, screen, settings, sb, stats)

        gf.update_screen(settings, screen, paddle, ball, bricks, sb, stats,
                         msg)

        #At most 120 frames will pass per second
        clock.tick(120)
コード例 #41
0
def start_new_life():
    global balls
    global powerups
    global to_activate_powerups
    global active_powerups
    global paddle
    global boss_bricks
    clear_screen()

    balls.remove_all()

    paddle = Paddle(8, width=5)
    balls.add_ball(paddle.get_x() + random.randint(0, paddle.get_width() - 1), paddle.get_y() - 1, 0, 0, speed=0.2,
                   free=True)
    paddle.hold_ball(balls.get_balls()[0])

    powerups = []
    to_activate_powerups = []
    active_powerups = []

    for b in boss_bricks:
        b.clear(board.matrix)
    boss_bricks = []
コード例 #42
0
def create_paddles(settings, screen, paddles, ai_paddles):
    # Create the player paddles
    playerLeftPaddle = Paddle(settings, screen, "left", "player")
    playerTopPaddle = Paddle(settings, screen, "top", "player")
    playerBottomPaddle = Paddle(settings, screen, "bottom", "player")

    # Create the three ai paddles
    aiRightPaddle = Paddle(settings, screen, "right", "ai")
    aiTopPaddle = Paddle(settings, screen, "top", "ai")
    aiBottomPaddle = Paddle(settings, screen, "bottom", "ai")

    # Add all the paddles to the sprite Group
    paddles.add(playerLeftPaddle)
    paddles.add(playerTopPaddle)
    paddles.add(playerBottomPaddle)
    paddles.add(aiRightPaddle)
    paddles.add(aiTopPaddle)
    paddles.add(aiBottomPaddle)

    # Add the ai paddles to their own sprite Group
    ai_paddles.add(aiRightPaddle)
    ai_paddles.add(aiTopPaddle)
    ai_paddles.add(aiBottomPaddle)
コード例 #43
0
class Game:
    def __init__(self):
        pygame.init()
        self._window = pygame.display.set_mode((800, 600))
        pygame.display.set_caption("Pong")
        self.deltaTime = 0.0
        self.player = Paddle()
        self.ball = Ball()

    def run(self):
        while True:
            start = time.time()
            self.handle_events()
            self.update()
            self.render()
            end = time.time()
            self.deltaTime = end - start

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.player.move(-self.deltaTime * 250.0, 0.0)
        elif keys[pygame.K_RIGHT]:
            self.player.move(self.deltaTime * 250.0, 0.0)
        self.ball.update(self.deltaTime, self.player)

    def render(self):
        self._window.fill((0, 0, 0))
        self.player.draw(self._window)
        self.ball.draw(self._window)
        pygame.display.update()

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
コード例 #44
0
ファイル: pong.py プロジェクト: LeonardoChirivi/pygames
os.environ['SDL_VIDEO_CENTERED'] = "1"

pygame.init()

#screen set up
WIDTH = 1300
HEIGHT = 600
SURFACE = pygame.display.set_mode([WIDTH, HEIGHT])
pygame.display.set_caption('PONG')

#colours set up
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# Paddle objects and ball object
leftPaddle = Paddle( 13, HEIGHT/5, 15, (2*HEIGHT)/5.0 )
rightPaddle = Paddle( 13, HEIGHT/5, WIDTH-15-13, (2*HEIGHT)/5.0 )
ball = Ball( WIDTH/2, HEIGHT/2, 13 )

#players score
rightScore = leftScore = 0
scored = False

#score font
font = pygame.font.Font( None, 150 )

FPS = 60
clock = pygame.time.Clock()
run = True

pygame.mouse.set_visible(False)
class GameLayer(Layer):
	is_event_handler = True

	def __init__(self):
		super(GameLayer, self).__init__()
		# 添加一个 板子
		self.paddle = Paddle('images/ash.png')
		self.add(self.paddle.sprite)
		self.ball = Ball('images/pokem.png')
		self.add(self.ball.sprite)

		# 添加一个 label 显示当前的游戏状态
		self.hud = Label('皮卡丘: 0')
		self.hud.position = (0, 450)
		self.add(self.hud)
		# 添加一个 label 显示当前游戏关卡
		self.level = Label('Level 1')
		self.level.position = (100, 450)
		self.add(self.level)
		# 添加一个变量来记录金币
		self.gold = 0
		# 设置 4 个按键状态
		self.key_pressed_left = False
		self.key_pressed_right = False
		self.key_pressed_up = False
		self.key_pressed_down = False

		self.blocks = []
		# 调用 reset 函数初始化状态
		self.reset()
		# 定期调用 self.update 函数
		# FPS frame per second 每秒帧数
		self.schedule(self.update)

	def reset(self):
		self.gold = 0
		self.update_hud()
		self.paddle.reset()
		self.ball.reset()

		# 添加砖块并且显示出来
		# 先删除残存的砖块
		for b in self.blocks:
			self.remove(b)
		# 再初始化新的砖块
		self.blocks = []
		levelfile = 'level.txt'
		positions = level_from_file(levelfile)
		number_of_blocks = len(positions)
		for i in range(number_of_blocks):
			b = Sprite('images/pikachu.png', anchor=(0, 0))
			b.position = positions[i]
			# b.position = (randint(0, 500), 400)
			self.add(b)
			self.blocks.append(b)

	def game_over(self):
		print('游戏结束,跪了。捉到了', self.gold, '只皮卡丘')
		# 没接到球,跳转到结束画面(失败)
		scene = Scene(GameOver())
		director.replace(SplitColsTransition(scene))

	def game_win(self):
		# 打完所有皮卡丘,跳转到下一关或(成功)
		scene = Scene(GameWin())
		director.replace(SplitColsTransition(scene))

	def update_hud(self):
		self.hud.element.text = '皮卡丘:' + str(self.gold)

	def update_blocks(self):
		# 判断是否撞到了砖块
		for b in self.blocks:
			if collides(self.ball.sprite, b):
				# self.ball_speedy = -self.ball_speedy
				self.ball.hit()
				self.remove(b)
				self.blocks.remove(b)
				self.gold += 1
				# self.speed += 1
				self.update_hud()
				print('捉到', self.gold, '只皮卡丘')
				break
		if len(self.blocks) == 0:
			self.game_win()

	def update_ball(self):
		if self.ball.fired:
			self.ball.update()
		else:
			bx, by = self.ball.sprite.position
			px, py = self.paddle.sprite.position
			self.ball.sprite.position = (px, by)

		collide = collides(self.ball.sprite, self.paddle.sprite)
		if collide:
			self.ball.hit()
		if self.ball.dead():
			self.game_over()

	def update_paddle(self):
		self.paddle.update()

	def update_input(self):
		self.paddle.move_left = self.key_pressed_left
		self.paddle.move_right = self.key_pressed_right
		if self.key_pressed_up:
			self.ball.fire()

	# 这个函数每帧都会被调用
	def update(self, dt):
		self.update_input()
		# 更新挡板
		self.update_paddle()
		# 更新球的位置
		self.update_ball()
		# 更新砖块
		self.update_blocks()

	def on_key_press(self, key, modifiers):
		k = symbol_string(key)
		status = True
		if k == "LEFT":
			self.key_pressed_left = status
		elif k == "RIGHT":
			self.key_pressed_right = status
		elif k == "UP":
			self.key_pressed_up = status

	def on_key_release(self, key, modifiers):
		k = symbol_string(key)
		print('release', k)
		if k == "LEFT":
			self.key_pressed_left = False
		if k == "RIGHT":
			self.key_pressed_right = False
		if k == "UP":
			self.key_pressed_up = False
コード例 #46
0
ファイル: gui-network.py プロジェクト: jrcapriles/Pong
class PongGUI(Frame):
  
    player_1 = {'Up'  :-5, 
                'Down': 5}  
    player_2 = {'w':-5, 
                's': 5}  
                 
    cpu_level = {'Easy'  : {'Up'  :  -3,
                            'Down':   3},
                 'Medium': {'Up'  :  -9,
                            'Down':   9},
                 'Hard'  : {'Up'  : -15,
                            'Down':  15} }
    score = [0,0]
    plays =1

    cpu_enable = False
    cpu_turn = True
    buffsize = 1024

    
    #List to check all balls
    balls = []
    obs = []
 
    def __init__(self, parent,screen=[600,400]):
        Frame.__init__(self, parent)   
        self.parent = parent     
        self.bg_status = 0
        self.initUI()
        self.key_pressed = set()
        self.obstacles = set()
        
        self.bind_all('<KeyPress>', lambda event: self.key_pressed.add(event.keysym)) 
        self.bind_all('<KeyRelease>', lambda event: self.key_pressed.discard(event.keysym)) 
        
        self.bind_all('<Escape>',self.end)
        self.connect_server() 
        
    def end(self, event):
        self.master.destroy()
        
        
    def connect_server(self):
        self.setup = True
        host = 'localhost'
        port = 9000
        addr = (host, port)
        try: 
            self.tcpclisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.tcpclisock.connect(addr)
            print 'Connected to: ', addr
            self.tcpclisock.setblocking(0)
            self.parent.title("Pong Client "+'Connected to: '+ str(addr))
        except:
            print 'not able to connect to server.'
            self.create_server()

    def create_server(self):
        
        host = ''
        port = 9000
        addr = (host, port)
        self.setup = True
        
        print "makeServer():"
        
        self.tcpsersock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcpsersock.bind(addr)
        self.tcpsersock.listen(5)
        self.tcpclisock, addr = self.tcpsersock.accept()
        self.tcpclisock.setblocking(0)
        print 'Connected from: ', addr
        self.parent.title("Pong Server: " + 'Connected from: ' + str(addr))        


    def initUI(self):
      
        self.parent.title("Pong")        
        self.pack(fill=BOTH, expand=1)
        
        self.canvas = Canvas(self, bg="#"+str(self.bg_status)+str(self.bg_status)+str(self.bg_status))
        
        self.left = Paddle(self.canvas, 1, [30, 10], 10, 100,"#fb0")
        self.right = Paddle(self.canvas, 1, [570, 40], 10, 100,"#05f")        
        
        self.balls.append(Ball(self.canvas,1,[70,70],10,[-2,-2]))
        #self.balls.append(Ball(self.canvas,1,[100,100],10,[2,2]))
        #self.balls.append(Ball(self.canvas,1,[200,100],10,[2,-2]))
        #self.balls.append(Ball(self.canvas,1,[100,200],10,[-2,2]))
        
        self.obs.append(Obstacle(self.canvas,[200,200],"Pin",6))
        self.obs.append(Obstacle(self.canvas,[400,300],"Paddle",7))
        self.obs.append(Obstacle(self.canvas,[350,350],"Pin",4))
        self.obs.append(Obstacle(self.canvas,[210,250],"Paddle",8))
        self.obs.append(Obstacle(self.canvas,[250,250],"Size",8))
        self.obs.append(Obstacle(self.canvas,[300,350],"Switch",8))
        self.obs.append(Obstacle(self.canvas,[400,350],"Switch",8))
        self.obs.append(Obstacle(self.canvas,[420,320],"Teleport",6))
        self.obs.append(Obstacle(self.canvas,[250,200],"Gravity",8))
        self.obs.append(Obstacle(self.canvas,[300,50],"Reset",4,[0,1]))
        
        self.canvas.pack(fill=BOTH, expand=1)
        
        self.score_msg = '  Home  0 - 0  Visitor  '
        self.label_score = Label(self, text=self.score_msg, width=len(self.score_msg), bg='yellow')
        
        self.choices = ['Easy', 'Medium', 'Hard']
        self.dificulty = StringVar()
        self.dificulty.set('Medium')
        self.option = OptionMenu(self, self.dificulty, *self.choices)
        self.option.pack(side=LEFT, fill=BOTH)
        self.label_score.pack(side= LEFT, fill=BOTH)
        
        self.text = ""
        self.text_canvas = self.canvas.create_text(300,10, text=self.text, fill="white")
        
        self.after(200, self.update)
    

    def check_keys(self):
        for i in self.key_pressed:
            if i == 'w' or i == 's':
                border = self.left.get_border()
                if 270 >= (self.player_2[i] + border[1]) >=0:
                    self.left.update_position(self.player_2[i])
                
            if i == 'Up' or i == 'Down':
                border = self.right.get_border()
                if 270 >= (self.player_1[i] + border[1]) >=0:
                    self.right.update_position(self.player_1[i])            
    

    def reset(self):
        self.bg_status = 0
        self.plays = 1
        self.__dx = 2
        self.__dy = -2
        self.canvas.configure(bg="#"+str(self.bg_status)+str(self.bg_status)+str(self.bg_status))
        
        
    def check_collision(self):        
       
        #Check obstacle contacts
        for i in self.obs :
            for j in self.balls:
                
                if i.alive and i.vel is not None:
                    i.move()
                
                if i.update(j.get_position()) and j.get_inside():
                    #We have a collision!
                    
                    ball_pos = j.get_center()
                    obs_pos = i.get_position()
                    
                    if i.get_type() == 'Pin':
                        #If pin just ounce back
                        if abs(ball_pos[0] - obs_pos[0]) < abs(ball_pos[1] - obs_pos[1]):
                            j.set_velocity([ j.vel[0], -j.vel[1] ])
                        else:
                            j.set_velocity([ -j.vel[0], j.vel[1] ])
                    
                        j.set_inside(False)
                    
                        if j.get_velocity()[0]<0:
                            self.cpu_turn = True
                        else:
                            self.cpu_turn = False
                    
                    if i.get_type() == 'Size' and 'Size' not in self.obstacles:
                            self.obstacles.add('Size')
                            #Increase size of ball                        
                            self.text += "Size "
                            self.update_text()
                            i.affected = True
                            j.set_radious(20)
                            j.re_draw()
                        
                    if i.get_type() == 'Paddle':
                        #Increase size paddle
                        i.affected = True
                        if j.get_velocity()[0] < 0 and 'Paddle2' not in self.obstacles:
                            self.obstacles.add('Paddle2')
                            self.text += "Paddle2 "                            
                            self.update_text()
                            self.right.length = 150
                            self.right.re_draw()
                        elif j.get_velocity()[0] > 0 and 'Paddle1' not in self.obstacles:
                            self.obstacles.add('Paddle1')
                            self.text += "Paddle1 "                            
                            self.update_text()
                            self.left.length = 150
                            self.left.re_draw()
                    
                    if i.get_type() == 'Switch':
                        #Change controller configuration
                        i.affected = True
                        if j.get_velocity()[0] < 0 and 'Switch2' not in self.obstacles:
                            self.obstacles.add('Switch2')
                            self.text += "Switch2 "                            
                            self.update_text()
                            self.player_2['w'] = -1*self.player_2['w']
                            self.player_2['s'] = -1*self.player_2['s']
                        elif j.get_velocity()[0] > 0 and 'Switch1' not in self.obstacles:
                            self.obstacles.add('Switch1')
                            self.text += "Switch1 "                            
                            self.update_text()
                            self.player_1['Up'] = -1*self.player_1['Up']
                            self.player_1['Down'] = -1*self.player_1['Down']
                    
                    if i.get_type() == 'Teleport':
                        i.affected = True
                        j.set_position([200+int(200*random.random()), 100+int(100*random.random())])
                        j.set_velocity([j.vel[0],j.vel[1]*2*random.random()])
                        j.re_draw()
                        
                    if i.get_type() == "Reset":
                        i.affected = "True"
                        self.obstacle_reset(j)
                    
                elif not i.update(j.get_position()):
                    j.set_inside(True)
                    
                #TODO CHANGE DIRECTION OF GRAVITY RANDOMLY
                if i.get_type() == "Gravity":
                    if i.alive and 'Gravity' not in self.obstacles:
                        self.obstacles.add('Gravity')
                        self.text += "Gravity "
                        self.update_text()
                        j.set_gravity(j.pos[1])
                    elif not i.alive:
                        self.obstacles.discard('Gravity')
                        self.text = self.text.replace('Gravity ',"")
                        self.update_text()
                        if j.gravity:                        
                            j.set_gravity()
                    
    def update_text(self):
        self.canvas.delete(self.text_canvas)
        self.text_canvas = self.canvas.create_text(300,10, text=self.text, fill="white")

    def obstacle_reset(self, ball):
        self.text = ""
        self.update_text()
        
        ball.set_radious(10)
        ball.re_draw()
        self.right.length = 100
        self.right.re_draw()
        self.left.length = 100
        self.left.re_draw()
        self.player_2['w'] = -5
        self.player_2['s'] = 5
        self.player_1['Up'] = -5
        self.player_1['Down'] = 5
        
        if ball.gravity:
            ball.set_gravity()
            #ball.vel[1] = ball.vel[1]+0.1
            
        self.obstacles.clear()
                    

    def check_disable(self):
        for i in self.obs :
            for j in self.balls:
                if not i.affected:
                    if i.type_obstacle == 'Size':
                        j.set_radious(10)
                        j.re_draw()
                    if i.type_obstacle == 'Switch':
                        self.player_2['w'] = -5
                        self.player_2['s'] = 5
                        self.player_1['Up'] = -5
                        self.player_1['Down'] = 5
                    if i.type_obstacle == 'Paddle':
                        self.right.length = 100
                        self.left.length = 100
                        self.right.re_draw()
                        self.left.re_draw()
    


    def restart(self, ball, player):
        ball.set_position([300,250])
        ball.set_velocity([(-4*player)+2,(-4*player)+2])

        ball.set_radious(10)
        self.left.length = 100
        self.right.length = 100
                
        self.left.set_position(self.left.pos)
        self.right.set_position(self.right.pos)

        self.player_2['w'] = -5
        self.player_2['s'] = 5
        self.player_1['Up'] = -5
        self.player_1['Down'] = 5
                        
        if player == 1: 
            self.cpu_turn = True
        
        self.score[player] += 1
        self.update_score()
        self.reset()    

    def check_paddle_collision(self, paddle, ball):
        if paddle.check_collision(ball.get_position()):
            delta_y = ball.get_center()[1] - paddle.get_center()[1]
            ball.set_velocity([-ball.vel[0],ball.vel[1]+0.05*delta_y])
            self.plays +=1
            self.cpu_turn = not self.cpu_turn

            

    def update(self):
     
        self.check_keys()     

        self.check_collision()
        
        #self.check_disable()
        #Update new value fo the ball
        for i in self.balls:
            i.update()
            
            if not (self.plays % 5):
                print "Increasing speed"
                i.set_velocity([1.1*i.vel[0],1.1*i.vel[1]])
                self.plays = 1
                self.bg_status += 1
 
                if self.bg_status ==9:
                    self.bg_status = 0

                self.canvas.configure(bg="#"+str(self.bg_status)+str(self.bg_status)+str(self.bg_status))
                
            if i.get_position()[1] <= 0 or i.get_position()[1] >= 350:
                i.set_velocity([i.vel[0],-i.vel[1]])
       
       
            if i.get_position()[2] >= 580:
                self.obstacle_reset(i)                
                self.restart(i,0)
            elif i.get_position()[0] <= 0:
                self.obstacle_reset(i)                
                self.restart(i,1)                
                
             
            self.check_paddle_collision(self.left,i)
            
            self.check_paddle_collision(self.right,i)
 
            
        if self.cpu_turn and self.cpu_enable:
            for i in self.balls:
                pos = self.left.get_center()
                if (pos[1]>i.get_center()[1]):
                    border = self.left.get_border()
                    if border[1]>0:
                        self.left.update_position(self.cpu_level[self.dificulty.get()]['Up'])#   self.player_1["Up"])
                else:
                    border = self.left.get_border()
                    if border[3]<365:
                        self.left.update_position(self.cpu_level[self.dificulty.get()]['Down'])#self.player_1["Down"])
            
        self.after(10, self.update)
 
    def update_score(self):
        self.label_score['text']=self.score_msg[:8]+str(self.score[0])+self.score_msg[9:12]+str(self.score[1])+self.score_msg[13:]
        self.label_score.update()
class GameLayer(cocos.layer.ColorLayer):
    is_event_handler = True

    def __init__(self):
        super(GameLayer, self).__init__(246, 226, 76, 255)
        # 添加一个 板子
        self.paddle = Paddle('images/ban.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/qiu.png')
        self.add(self.ball.sprite)

        # 添加一个 label 显示当前的游戏状态
        self.hud = Label('金币: 0',
                         color=(0, 0, 0, 255))
        self.hud.position = (0, 450)
        self.add(self.hud)
        # 添加一个变量来记录金币
        self.gold = 0
        # 设置 4 个按键状态
        self.key_pressed_left   = False
        self.key_pressed_right  = False
        self.key_pressed_up     = False
        self.key_pressed_down   = False

        self.blocks = []
        # 调用 reset 函数初始化状态
        self.reset()
        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)

    def reset(self):
        self.gold = 0
        self.update_hud()
        self.paddle.reset()
        self.ball.reset()

        # 添加砖块并且显示出来
        # 先删除残存的砖块
        for b in self.blocks:
            self.remove(b)
        # 再初始化新的砖块
        self.blocks = []
        levelfile = 'level1.txt'
        positions = level_from_file(levelfile)
        number_of_blocks = len(positions)
        for i in range(number_of_blocks):
            b = Sprite('images/zhuan.png', anchor=(0, 0))
            b.position = positions[i]
            b.color = (randint(0, 255), randint(0, 255), randint(0, 255))
            # b.position = (randint(0, 500), 400)
            self.add(b)
            self.blocks.append(b)

    def game_over(self):
        print('游戏结束,跪了。金币是', self.gold)
        self.reset()

    def update_hud(self):
        self.hud.element.text = '金币:' + str(self.gold)

    def update_blocks(self):
        # 判断是否撞到了砖块
        for b in self.blocks:
            if collides(self.ball.sprite, b):
                # self.ball_speedy = -self.ball_speedy
                self.ball.hit()
                self.remove(b)
                self.blocks.remove(b)
                self.gold += 1
                # self.speed += 1
                self.update_hud()
                print('金币', self.gold)
                break

    def update_ball(self):
        if self.ball.fired:
            self.ball.update()
        else:
            bx, by = self.ball.sprite.position
            px, py = self.paddle.sprite.position
            self.ball.sprite.position = (px, by)

        collide = collides(self.ball.sprite, self.paddle.sprite)
        if collide:
            self.ball.hit()
        if self.ball.dead():
            self.game_over()

    def update_paddle(self):
        self.paddle.update()

    def update_input(self):
        self.paddle.move_left = self.key_pressed_left
        self.paddle.move_right = self.key_pressed_right
        if self.key_pressed_up:
            self.ball.fire()

    # 这个函数每帧都会被调用
    def update(self, dt):
        self.update_input()
        # 更新挡板
        self.update_paddle()
        # 更新球的位置
        self.update_ball()
        # 更新砖块
        self.update_blocks()

    def on_key_press(self, key, modifiers):
        k = symbol_string(key)
        status = True
        if k == "LEFT":
            self.key_pressed_left = status
        elif k == "RIGHT":
            self.key_pressed_right = status
        elif k == "UP":
            self.key_pressed_up = status

    def on_key_release(self, key, modifiers):
        k = symbol_string(key)
        print('release', k)
        if k == "LEFT":
            self.key_pressed_left = False
        if k == "RIGHT":
            self.key_pressed_right = False
        if k == "UP":
            self.key_pressed_up = False
コード例 #48
0
ファイル: script.py プロジェクト: borntofrappe/python-scripts
height = 500
padding = 20
bgcolor = "#FEFEFE"
color = "#333333"

# setup
window = turtle.Screen()
window.title(title)
window.setup(width=width, height=height)
window.bgcolor(bgcolor)

# stops the window from updating
window.tracer(0)

# initialize turtles
paddle_a = Paddle(-width / 2 + padding, 0, 5, 1)
paddle_b = Paddle(width / 2 - padding, 0, 5, 1)
ball = Ball(0, 0)

# score
score_a = 0
score_b = 0

pen = turtle.Turtle()
pen.penup()
pen.hideturtle()
pen.goto(0, height / 2 - 30)
pen.write(f"Player A: {score_a} Player B: {score_b}",
          align="center",
          font=("Fira Code", 12, "normal"))
コード例 #49
0
ファイル: pong.py プロジェクト: progworkshop/pong
class Pong:
    def __init__(self, width=640, height=480, title="Prog Workshop - Pong!"):
        pygame.init()

        # Sets key repeat to a max of once every 5 ms
        #pygame.key.set_repeat(5, 5)
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption(title)
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        self._running = True
        
        self.player1 = Paddle(0,0,20,100,self)
        self.player2 = Paddle(width-20,0,20,100,self)
        
        self.ball = Ball(width/2,height/2,20,20,self)
        self.ball.setSpeed(random.random()*14-7, random.random()*14-7)

        self.balls = []

        self.score = Scoreboard(self, 36)

    def handle_event(self, event):
        if event.type == pygame.QUIT:
            self._running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            ball = Ball(self.screen.get_width()/2,self.screen.get_height()/2,20,20,self)
            ball.setSpeed(random.random()*14-7, random.random()*14-7)
            self.balls.append(ball)
            
    def update_game(self):
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_UP]:
            self.player2.moveUp()
        if keys_pressed[pygame.K_DOWN]:
            self.player2.moveDown()
        if keys_pressed[pygame.K_w]:
            self.player1.moveUp()
        if keys_pressed[pygame.K_s]:
            self.player1.moveDown()
        self.ball.update()
        for ball in self.balls:
            ball.update()
    
    def render(self):
        background = pygame.Surface(self.screen.get_size()).convert()
        background.fill((250, 250, 250))
        self.screen.blit(background, (0,0))

        self.player1.render()
        self.player2.render()
        
        self.ball.render()

        for ball in self.balls:
            ball.render()

        self.score.renderScore()
        
        pygame.display.flip()
    
    def start(self):
        while self._running:
            self.clock.tick(60) # Limit to 60 fps
            
            # Handle events
            for event in pygame.event.get():
                self.handle_event(event)

            # Handle game logic
            self.update_game()

            # Handle rendering
            self.render()
            
        pygame.quit()
コード例 #50
0
ファイル: main.py プロジェクト: LeonardoChirivi/pygames
pygame.init()

#color setup
BLACK = ( 0, 0, 0 )
WHITE = ( 255, 255, 255 )

#surface setup
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 650
SURFACE = pygame.display.set_mode([ SCREEN_WIDTH, SCREEN_HEIGHT ])
pygame.display.set_caption('Breakout')

#initialize players
#paddle:
#                   width        height                  xpos                            ypos
paddle = Paddle( SCREEN_WIDTH/8,   10,     (SCREEN_WIDTH/2)-(SCREEN_WIDTH/8)/2,    SCREEN_HEIGHT - 12 )

#ball
#                  ballx                                bally                    radius
ball = Ball( paddle.left()+paddle.width/2,    SCREEN_HEIGHT-paddle.height-20,      7   )

#bicks array:
bricks = []
x = y = 50
for i in range( 12 ):
    for j in range( 20 ):
        bricks.append( Brick( 25, 10, x, y ) )
        x += 30

    y += 12
    x = 50
コード例 #51
0
ファイル: player.py プロジェクト: prgreen/grym
	def initPaddle(self, padWidth, padHeight, padColor, padPosX0, padPosY0):
		self.paddleX0 = padPosX0
		self.paddleY0 = padPosY0
		self.paddle = Paddle(width=padWidth, height=padHeight, posX=self.paddleX0, posY=self.paddleY0, color=padColor)
コード例 #52
0
ファイル: pong.py プロジェクト: piotut/Pong
class Pong(object):
    def __init__(self, file1=None, file2=None):
        pygame.mixer.pre_init(44100, -16, 2, 2048)
        pygame.init()
        self.fps = pygame.time.Clock()
        flag = DOUBLEBUF

        self.board = pygame.display.set_mode(screenRect, flag)
        pygame.display.set_caption('[ --- Pong --- ]')

        self.state = 1  # 1 - run, 0 - exit

        self.track = Tracking(file1, file2)

        self.sound = Sound()
        self.p1 = Paddle(self.board, (200,100,100),screenRect)
        self.p1.setInitialPostition(0,screenHeight/2)
        self.p2 = Paddle(self.board, (100,200,100),screenRect)
        self.p2.setInitialPostition(screenWidth-self.p2.get()['width'],screenHeight/2)
        self.ball = Ball(self.board, (50,50,250), screenRect, self.sound)
        self.ball.setInitialPostition(screenWidth/2,screenHeight/2)
        self.arena = Arena(self.board, screenRect)
        self.referee = Referee(self.ball, self.p1, self.p2, screenRect, self.sound)

        

        self.t = Thread(target=self.track.run)
        #self.track.run()
        self.t.start()

        self.p1_pos = 0
        self.p2_pos = 0

        self.loop()

    def movep1(self, diry):
       '''Player1 moves support'''
       self.p1.move(diry)

    def movep2(self, diry):
       '''Player2 moves support'''
       self.p2.move(diry)

    def game_exit(self):
        exit()

    def loop(self):
        flaga = 1
        while self.state==1:
            for event in pygame.event.get():
                if event.type==QUIT or (event.type==KEYDOWN and event.key==K_ESCAPE):
                   self.state=0

            keys = pygame.key.get_pressed()


            dirp1 = copysign(1, self.track.p1_position - self.p1_pos)
            dirp2 = copysign(1, self.track.p2_position - self.p2_pos)

            self.p1_pos += dirp1
            self.p2_pos += dirp2

            self.p1.set(self.track.p1_position+45)
            self.p2.set(self.track.p2_position+45)
            
            if keys[K_f]:
                pygame.display.toggle_fullscreen()

            self.arena.render(self.track.frame)

            font = pygame.font.Font("gfx/ATARCC__.TTF",40)
            text1 = font.render('P1={}'.format(self.p1.getScore()), True,(200,200,200))
            text2 = font.render('P2={}'.format(self.p2.getScore()), True,(200,200,200))
                   
            quartWidth = screenWidth/4
            self.board.blit(text1,(quartWidth * 1 - quartWidth/2,10))
            self.board.blit(text2,(quartWidth * 3 - quartWidth/2,10))

            self.p1.render()
            self.p2.render()
            self.ball.render()
            self.referee.judge()

            pygame.display.flip()   # wyswietlamy obrazki
            self.fps.tick(80)

        self.track.running = False 
        self.game_exit()
コード例 #53
0
ファイル: levels.py プロジェクト: Kranek/BlockBuster
class Level(object):
    """
    Main Level class, handles most of the gameplay
    """
    def __init__(self, screen, draw_offset, control_set, player_color, finish_game):
        """
        Init with... way too many parameters
        :param screen: Main PyGame surface to draw the objects/UI on
        :param draw_offset: Drawing offset used in multiplayer
        :param control_set: Key-set used to control the Paddle
        :param player_color: Color of the player's Paddle
        :param finish_game: Function passed to the constructor, triggered on
        the game end
        :return:
        """
        self.screen = screen
        self.draw_offset = draw_offset
        self.control_set = control_set
        self.prev_input_x = 0
        self.level_number = 1
        self.block_count = 0
        self.player = Player("Derp")
        self.paddle = Paddle(LEVEL_WIDTH/2 - Paddle.WIDTH/2, LEVEL_HEIGHT - 40,
                             player_color, parent=self, owner=self.player)
        self.ball = Ball(self.paddle.rect.x + Paddle.WIDTH/2 - Ball.RADIUS,
                         self.paddle.rect.y - Ball.RADIUS * 2)
        self.items = None
        self.blocks = []
        self.blocks_surface = None
        self.blocks_surface_dirty = True
        self.entities = []
        self.font = Assets.font
        self.score_label = None
        self.lives_label = None
        self.level_label = None
        self.load_level(self.level_number)
        self.finish_game = finish_game

    def handle_input(self, events):
        """
        Handles incoming input events
        :param events: input events from the main app
        :return:
        """
        BONUS_SPAWN_X = 305
        BONUS_SPAWN_Y = 200
        for event in events:
            if event.type == KEYDOWN:
                if event.key == self.control_set[0]:
                    if self.paddle.vx != 0:
                        self.prev_input_x = 1
                    self.paddle.vx = -1

                elif event.key == self.control_set[2]:
                    if self.paddle.vx != 0:
                        self.prev_input_x = -1
                    self.paddle.vx = 1

                # elif event.key == K_SPACE:
                #     self.paddle.change_size(self.paddle.rect.width+10)

                elif event.key == K_1:
                    # self.add_entity(ItemExpand(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 1)

                elif event.key == K_2:
                    # self.add_entity(ItemLaserGun(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 2)

                elif event.key == K_3:
                    # self.add_entity(ItemShrink(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 3)

                elif event.key == K_4:
                    # self.add_entity(ItemPaddleNano(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 4)

                elif event.key == K_5:
                    # self.add_entity(ItemLife(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 5)

                elif event.key == K_6:
                    # self.add_entity(ItemLife(BONUS_SPAWN_X, BONUS_SPAWN_Y))
                    self.spawn_item(BONUS_SPAWN_X, BONUS_SPAWN_Y, 6)

            elif event.type == KEYUP:
                if event.key == self.control_set[0]:
                    if self.prev_input_x < 0:
                        self.prev_input_x = 0
                    elif self.prev_input_x > 0:
                        self.paddle.vx = 1
                        self.prev_input_x = 0
                    else:
                        self.paddle.vx = 0

                elif event.key == self.control_set[2]:
                    if self.prev_input_x > 0:
                        self.prev_input_x = 0
                    elif self.prev_input_x < 0:
                        self.paddle.vx = -1
                        self.prev_input_x = 0
                    else:
                        self.paddle.vx = 0

                elif event.key == self.control_set[1]:
                    if self.ball.docked:
                        self.ball.docked = False
                        self.ball.vx = 1
                        self.ball.vy = -1
                    else:
                        self.paddle.use_attachment()

                elif event.key == K_EQUALS:
                    self.start_level(self.level_number + 1)

    def start_level(self, new_level_num):
        """
        Used to start level, checks the level bounds
        :param new_level_num:
        :return:
        """
        self.ball.docked = True
        self.ball.dead = False

        if new_level_num > get_level_count():
            self.finish_game()
        else:
            if self.level_number < new_level_num:
                self.player.score += self.player.lives * 500
            else:
                self.player.score = 0

            self.load_level(new_level_num)
            self.paddle.change_size(PADDLE_WIDTHS[PADDLE_DEFAULT_WIDTH_INDEX])
            self.paddle.attachments = []
            self.paddle.rect.x = LEVEL_WIDTH/2 - self.paddle.rect.width/2
            self.paddle.rect.y = LEVEL_HEIGHT - 40
            self.player.lives = 3
            self.blocks_surface = Surface((LEVEL_WIDTH, LEVEL_HEIGHT))
            self.blocks_surface_dirty = True

    def load_level(self, new_level_num):
        """
        Parses level from the Character array that is provided by the LevelLoader class
        :param new_level_num: Number of the level, used to construct the filename,
        compute the next level number, and viewed on the UI
        :return:
        """
        loaded_level = LevelLoader.load(LEVELDIR + str(new_level_num).zfill(2) + ".lvl")
        level = loaded_level[0]
        self.items = loaded_level[1]
        self.level_number = new_level_num
        self.blocks = []
        self.entities = []
        self.block_count = 0
        for y in xrange(0, BLOCK_NUM_HEIGHT):
            self.blocks.append([None, ] * BLOCK_NUM_WIDTH)
            for x in xrange(0, BLOCK_NUM_WIDTH):
                if level[y][x] == 'i':
                    self.blocks[y][x] = BlockIndestructible(PLAYFIELD_PADDING[0] + x * Block.WIDTH,
                                                            PLAYFIELD_PADDING[1] + y * Block.HEIGHT)
                elif level[y][x] == 'm':
                    self.blocks[y][x] = BlockMultiHit(PLAYFIELD_PADDING[0] + x * Block.WIDTH,
                                                      PLAYFIELD_PADDING[1] + y * Block.HEIGHT)
                    self.block_count += 1
                elif level[y][x] == 'e':
                    self.blocks[y][x] = BlockExplosive(PLAYFIELD_PADDING[0] + x * Block.WIDTH,
                                                       PLAYFIELD_PADDING[1] + y * Block.HEIGHT)
                    self.block_count += 1
                elif level[y][x] != '0':
                    self.blocks[y][x] = Block(PLAYFIELD_PADDING[0] + x * Block.WIDTH,
                                              PLAYFIELD_PADDING[1] + y * Block.HEIGHT,
                                              int(level[y][x]) - 1)
                    self.block_count += 1

    def add_entity(self, entity):
        """
        Utility function to add new entities to the level. Later, might search for dead entities
        to replace them instead of expanding the list indefinitely
        :param entity:
        :return:
        """
        self.entities.append(entity)

    def spawn_item(self, x, y, item):
        """
        Function used to spawn items from blocks
        :param x: x coordinate of the play-field
        :param y: y coordinate of the play-field
        :param item: item to spawn, leave empty to make it randomly selected
        :return:
        """
        if item == 1:
            self.add_entity(ItemLife(x, y))
        elif item == 2:
            self.add_entity(ItemExpand(x, y))
        elif item == 3:
            self.add_entity(ItemShrink(x, y))
        elif item == 4:
            self.add_entity(ItemLaserGun(x, y))
        elif item == 5:
            self.add_entity(ItemPaddleNano(x, y))
        elif item == 6:
            pass
        elif randint(0, 35) == 0:
            item_type = randint(0, 4)
            if item_type == 0:
                dropped_item = ItemLife(x, y)
            elif item_type == 1:
                dropped_item = ItemExpand(x, y)
            elif item_type == 2:
                dropped_item = ItemShrink(x, y)
            elif item_type == 3:
                dropped_item = ItemLaserGun(x, y)
            else:
                dropped_item = ItemPaddleNano(x, y)
            self.add_entity(dropped_item)

    def block_destruction(self, block, item, func):
        """
        Decides what to do with the block, based on the block type (sigh), and performs
        appropriate action
        :param block: Block to operate on
        :param item: If the block has a hard-assigned item in level, it will be spawned
        :param func: Function of the block that returns its points-value
        :return:
        """
        return_v = func()
        if isinstance(block, BlockExplosive):
            rect = block.rect
            self.entities.append(Explosion(rect.x + rect.width/2 - Explosion.WIDTH/2,
                                           rect.y + rect.height/2 - Explosion.HEIGHT/2))

        if block.dead:
            self.player.add_points(return_v)
            self.block_count -= 1
            if not isinstance(block, BlockExplosive):
                self.spawn_item(block.rect.x, block.rect.y, item)
        self.blocks_surface_dirty = True

    def draw(self):
        """
        Method called each frame to (re)draw the objects and UI
        :return:
        """
        self.screen.blit(Assets.background, (self.draw_offset[0], self.draw_offset[1]))

        self.screen.blit(Assets.border, (self.draw_offset[0], self.draw_offset[1]))
        self.screen.blit(Assets.border, (self.draw_offset[0] + LEVEL_WIDTH - PLAYFIELD_PADDING[0],
                                         self.draw_offset[1]))
        if self.blocks_surface_dirty:
            self.blocks_surface = Surface((LEVEL_WIDTH, LEVEL_HEIGHT), SRCALPHA, 32)
            self.blocks_surface = self.blocks_surface.convert_alpha()
            self.blocks_surface_dirty = False
            for row in self.blocks:
                for block in row:
                    if block is not None and not block.dead:
                        block.draw(self.blocks_surface)
        self.screen.blit(self.blocks_surface, self.draw_offset)
        self.paddle.draw(self.screen, self.draw_offset)

        if not self.ball.dead:
            self.ball.draw(self.screen, self.draw_offset)

        # draw entities
        for entity in self.entities:
            if not entity.dead:
                entity.draw(self.screen, self.draw_offset)

        # draw upper bar
        draw.rect(self.screen, (0, 0, 0), (self.draw_offset[0] + PLAYFIELD_PADDING[0], self.draw_offset[1],
                                           LEVEL_WIDTH - PLAYFIELD_PADDING[0] * 2, PLAYFIELD_PADDING[1]))

        self.screen.blit(self.score_label,
                         (self.draw_offset[0] + PLAYFIELD_PADDING[0] + 10, self.draw_offset[1]))
        self.screen.blit(self.lives_label,
                         (self.draw_offset[0] + PLAYFIELD_PADDING[0] + 150, self.draw_offset[1]))
        self.screen.blit(self.level_label,
                         (self.draw_offset[0] + LEVEL_WIDTH - 100, self.draw_offset[1]))

    def update(self):
        """
        Method called each frame, to update the state of entities based on input events and
        previous state of the game
        :return:
        """
        if self.block_count <= 0:
            self.start_level(self.level_number + 1)
        elif self.player.lives <= 0:
            self.start_level(self.level_number)

        self.paddle.update()
        if self.ball.docked and not self.ball.dead:
            self.ball.rect.x = self.paddle.rect.x + self.paddle.rect.width/2 - self.ball.radius
            self.ball.rect.y = self.paddle.rect.y - self.ball.radius * 2
        elif self.player.lives > 0:
            self.ball.update()
        for entity in self.entities:
            if not entity.dead:
                entity.update()

        self.check_collision()
        self.score_label = self.font.render("SCORE: " + str(self.player.score), 1, (255, 255, 255))
        self.lives_label = self.font.render("LIVES: " + str(self.player.lives), 1, (255, 255, 255))
        self.level_label = self.font.render("LEVEL " + str(self.level_number), 1, (255, 255, 255))

    def check_collision(self):
        """
        Called after input handling and movement of the object, to check and solve collisions
        :return:
        """
        # ball vs paddle
        if self.ball.rect.y < self.paddle.rect.y and \
                sprite.collide_rect(self.paddle, self.ball):
            self.ball.vy = -1  # ball.vy

        # ball vs bottom
        if not self.ball.dead and self.ball.rect.y + self.ball.radius * 2 > LEVEL_HEIGHT:
            self.player.lives -= 1
            if self.player.lives < 1:
                self.ball.dead = True
            else:
                self.ball.rect.x = self.paddle.rect.x + self.paddle.rect.width/2 - self.ball.radius
                self.ball.rect.y = self.paddle.rect.y - self.ball.radius * 2
            self.ball.docked = True
            self.paddle.change_size(PADDLE_WIDTHS[PADDLE_DEFAULT_WIDTH_INDEX])
            self.paddle.attachments = []

        # ball vs blocks
        coll_num = [0, 0, 0]
        coll_num_val = (4, 2, 1)
        ball_grid_x = (self.ball.rect.x - PLAYFIELD_PADDING[0] + self.ball.radius) / Block.WIDTH
        ball_grid_y = (self.ball.rect.y - PLAYFIELD_PADDING[1] + self.ball.radius) / Block.HEIGHT
        for y in range(ball_grid_y - 1, ball_grid_y + 2):
            for x in range(ball_grid_x - 1, ball_grid_x + 2):
                if 0 <= x < BLOCK_NUM_WIDTH and 0 <= y < BLOCK_NUM_HEIGHT:
                    if self.blocks[y][x] is not None and not self.blocks[y][x].dead and \
                            sprite.collide_rect(self.blocks[y][x], self.ball):
                        self.block_destruction(self.blocks[y][x],
                                               self.items[y][x], self.blocks[y][x].on_collide)

                        coll_num[y - ball_grid_y + 1] += coll_num_val[x - ball_grid_x + 1]

        self.ball.on_collide(coll_num)

        # entities
        for entity in self.entities:
            if not entity.dead:
                # paddle vs items
                if isinstance(entity, Item) and sprite.collide_rect(self.paddle, entity):
                    entity.on_collect(self.paddle)
                    entity.dead = True
                    # self.player.lives += 1
                # explosion vs blocks
                elif isinstance(entity, Explosion) and entity.state > 0:
                    entity_block_x = (entity.rect.x - PLAYFIELD_PADDING[0] +
                                      Explosion.WIDTH/2) / Block.WIDTH
                    entity_block_y = (entity.rect.y - PLAYFIELD_PADDING[1] +
                                      Explosion.HEIGHT/2) / Block.HEIGHT
                    for y in xrange(entity_block_y - 1, entity_block_y + 2):
                        for x in xrange(entity_block_x - 1, entity_block_x + 2):
                            if 0 <= x < BLOCK_NUM_WIDTH and 0 <= y < BLOCK_NUM_HEIGHT:
                                if self.blocks[y][x] is not None and not self.blocks[y][x].dead:
                                    self.block_destruction(self.blocks[y][x], self.items[y][x],
                                                           self.blocks[y][x].kill)
                elif isinstance(entity, Projectile):
                    entity_block_x = (entity.rect.x - PLAYFIELD_PADDING[0] +
                                      entity.rect.width/2) / Block.WIDTH
                    entity_block_y = (entity.rect.y - PLAYFIELD_PADDING[1] +
                                      entity.rect.height/2) / Block.HEIGHT
                    for y in xrange(entity_block_y - 1, entity_block_y + 2):
                        for x in xrange(entity_block_x - 1, entity_block_x + 2):
                            if 0 <= x < BLOCK_NUM_WIDTH and 0 <= y < BLOCK_NUM_HEIGHT:
                                if self.blocks[y][x] is not None and not self.blocks[y][x].dead \
                                        and sprite.collide_rect(self.blocks[y][x], entity):
                                    self.block_destruction(self.blocks[y][x], self.items[y][x],
                                                           self.blocks[y][x].kill)
                                    entity.on_collide()
コード例 #54
0
ファイル: arkanoid.py プロジェクト: DuhPhd/Arkanoid
class Arkanoid:

    def __init__(self):
    
        from utilities import pygame, load_stages
        from text import Score, Timer, Name, Text
        from paddle import Paddle
        from ball import Ball
        from brick import Brick
        from stage import Stage
        
        C = Constants()
        self.C = C
        self.pygame = pygame

        # setup FPS governor
        self.clock = pygame.time.Clock()

        # set the window size
        divTop = int(C.DIV_POS*C.SIZE[1]) # top of divider. Affects bounds for ball
        divBot = divTop + C.DIV_WIDTH
        self.screen = pygame.display.set_mode(C.SIZE)
        area = pygame.Rect(0, divBot, C.SIZE[0], C.SIZE[1]-divBot)

        # create game screen objects/sprites
        self.score = Score(C.SCORE_POS, self.screen, C.SCORE_START, C.SCORE_COLOR, C.SCORE_SIZE)
        self.scoreText = Text(C.S_LABEL_POS, self.screen, C.S_LABEL_TEXT, C.S_LABEL_COLOR, C.S_LABEL_SIZE)
        self.timer = Timer(C.TIMER_POS, self.screen, C.TIMER_START, C.TIMER_COLOR, C.TIMER_SIZE)
        self.timerText = Text(C.T_LABEL_POS, self.screen, C.T_LABEL_TEXT, C.T_LABEL_COLOR, C.T_LABEL_SIZE)
        self.name = Name(C.NAME_POS, self.screen, '', C.NAME_COLOR)
        self.paddle = Paddle(area)
        self.ball = Ball(area)
        self.stages = load_stages(self.screen)
        self.divider = (self.screen, C.DIV_COLOR, [0, divTop], [C.SIZE[0], divTop], C.DIV_WIDTH)
        self.sprites = pygame.sprite.RenderPlain((self.paddle, self.ball))

        self.paused = True # flag to indicate if the stage is paused or moving 
        self.pausedReset = False # flag to indicate pause was due to reset, in which case dont pause timer


    # stage_event() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
    def stage_event(self, event):
        """Handles stage events"""
        
        C = self.C
        
        # quit the game
        if event.type == C.QUIT: return 2
        elif event.type == C.KEYDOWN:
        
            # quit the game
            if event.key == C.K_ESCAPE: return 2
            
            # move the paddle
            else: self.paddle.move(event.key)
            
        # key has been un-pressed
        elif event.type == C.KEYUP:
            
            # stop moving the paddle
            self.paddle.move(None)
        
            # reset the ball and paddle (dont reset stage)
            if event.key == C.K_r:
                self.ball.reset()
                self.paddle.reset()
                self.paused = True
                self.pausedReset = True
                
            # pause the game
            elif event.key == C.K_p:
                self.ball.pause()
                self.paddle.pause()
                if self.paused: self.paused = False
                else: self.paused = True
                
            elif event.key == C.K_SPACE:
            
                # start the stage
                if self.paused:
                    self.ball.pause()
                    if self.paddle.paused: self.paddle.pause()
                    self.paused = False
                    self.pausedReset = False
                    
        return 0
        

    # update_ball() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
    def update_ball(self):
        """Updates the ball and does ball related actions"""

        from brick import Brick
        
        if self.ball.inbounds:
            if (
                isinstance(self.ball.bouncedOff, Brick) and
                self.ball.bouncedOff.destroyed
            ): 
                self.score.change_by(self.ball.bouncedOff.points * self.timer.value)
                
        else: # ball went out of bounds
            self.ball.reset()
            self.paused = True
            self.pausedReset = True
        
        
    # PLAY_STAGE() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
    def play_stage(self, stage):
        """Plays a single stage"""
        
        C = self.C
        
        # update the ball's check surfaces
        self.ball.surfaces = set()
        self.ball.surfaces.add(self.paddle)
        self.ball.surfaces.update(stage.bricks)
        self.ball.surfaces.update(stage.powerups)
        
        # update the stage name
        self.name.value = '%i: %s' % (stage.number, stage.name)
        
        # draw the stage to prepare the round
        self.timer.change_by(stage.time)
        stage.draw()
        self.pygame.draw.line(*self.divider)
        self.ball.reset()
        self.paddle.reset()
        self.sprites.draw(self.screen)
        self.pygame.display.flip()
        
        self.paused = True
        self.pausedReset = False
        
        # play the round
        while True:
        
            # Handle Input Events
            for event in self.pygame.event.get():
                returnCode = self.stage_event(event)
                if returnCode == 2: return 2
                
            # update ball
            self.update_ball()
                
            # check if the stage is complete and go to the next stage if so
            if stage.completed:
                self.ball.bouncedOff = None
                stage.paused = False
                stage.pausedReset = False
                return 0
            
            # update timer. If time has run out, you lose
            if not self.paused or self.pausedReset:
                self.timer.change_by(C.TIMER_FRAME_SPEED)
            if self.timer.exact <= 0: return 1
            
            # Draw Everything
            self.sprites.update()
            stage.update()
            stage.draw()
            self.pygame.draw.line(*self.divider)
            self.name.render()
            self.timer.render()
            self.score.render()
            self.scoreText.render()
            self.timerText.render()
            self.sprites.draw(self.screen)
            self.pygame.display.flip()
            self.clock.tick(C.FRAMES_PER_SECOND)
コード例 #55
0
ファイル: board.py プロジェクト: Nolski/rm-out
class Board:

    def __init__(self, window, path="."):

        self.window = window
        self.h, self.w = window.getmaxyx()

        self.cells_x = self.w // Block.WIDTH
        self.cells_y = self.h // Block.HEIGHT
        self.field = [[None] * self.cells_x  for i in range(self.cells_y)]

        self._gen_blocks(path)
        self.ball = Ball(self.h-2, self.w//2)

        self.paddle = Paddle(self.h-1, self.w//2)

    def draw(self):
        for row in self.field:
            for cell in row:
                if cell is not None:
                    cell.draw(self.window)

        self.window.attron(curses.color_pair(1))

        self.ball.draw(self.window)
        self.paddle.draw(self.window)

    def move(self, offset):
        self.paddle.move(offset, self.w)

    def animate(self):
        self.ball.animate(self.h, self.w)
        self._collide_endzone()
        self._collide_blocks()
        self._collide_paddle()

    def _collide_blocks(self):
        cell_x = self.ball.x // Block.WIDTH
        cell_y = self.ball.y // Block.HEIGHT

        if (cell_y >= self.cells_y) or (cell_x >= self.cells_x):
            return

        block = self.field[cell_y][cell_x]
        if block is not None:

            self.field[cell_y][cell_x] = None # destroy the block

            # deflect the ball
            if (self.ball.y == block.top()) or \
               (self.ball.y == block.bottom()):
                self.ball.bounce_y()

            if (self.ball.x == block.left()) or \
               (self.ball.x == block.right()):
                self.ball.bounce_x()

            if block.isdir:
                self._gen_blocks(block.f)
            else:
                pass
                #block.destroy()

    def _collide_endzone(self):
        if self.ball.y == self.h - 1:
            exit()

    def _collide_paddle(self):
        if self.paddle.contacts(self.ball):
            self.ball.bounce_y()

    def _add_block(self, f):
        for y, row in enumerate(self.field):
            for x, cell in enumerate(row):
                if cell is None:
                    b = Block(f, y, x)
                    self.field[y][x] = b
                    return

    def _gen_blocks(self, path):
        for f in os.listdir(path):
            self._add_block(os.path.join(path, f))
コード例 #56
0
ファイル: main.py プロジェクト: sruptash/Python-Breakout
class BreakoutMain:
    """
    This class is instantiated upon the game being launched.
    This houses information on width, height, and tick rate.

    Note that all loops essential to game function are located
    near the bottom of this file.
    """

    # Keep a list of all levels used. More levels can be added
    # by updating this list.
    # NOTE: "level0" is the menu.
    levels = ["level0",
              "level1",
              "level2",
              "level3",
              "level4",
              "level5"]

    # Here is a tuple with the standard width and height.
    # Change these to change dimensions of screen.
    # NOTE: Window is non-resizeable.
    dimensions = (600, 600)

    # Initialization function
    def __init__(self):
        """
        Initialize a new window using pygame, with a specified w and h.
        Set the caption as well.
        """
        pygame.init()

        # Screen and window settings
        self.width = BreakoutMain.dimensions[0]
        self.height = BreakoutMain.dimensions[1]
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption('Breakout!')

        # Timer settings
        self.clock = pygame.time.Clock()
        self.elapsed = 0.0

        # Game vars
        self.numBalls = 10
        self.ballLaunched = False
        self.paused = False
        self.pauseText = load_text("Paused", 48)
        self.pauseTextPos = self.pauseText.get_rect(center=
                                                    (self.width/2,
                                                     self.height/2))

        self.currentLevel = 2
        self.score = 0
        self.difficulty = "normal"

        # Life vars
        self.lives = 3
        self.lifeRadius = 5
        self.lifeX = 0 + 5
        self.lifeY = self.height - 5

    # Used to load sprites to the screen
    def loadSprites(self):
        """
        From here we can load all sprites needed, whether they
        are the paddle, balls, bricks, backgrounds, etc.
        """
        # level
        # Background and bricks defined in here
        self.level = Level(BreakoutMain.levels[self.currentLevel])

        # paddle
        self.paddle = Paddle(self.width, self.height)
        self.paddleSprite = pygame.sprite.GroupSingle(self.paddle)

        # ball
        self.mainBall = Ball((self.paddle.x, self.paddle.y),
                             self.paddle.height)
        self.ballSprites = pygame.sprite.RenderPlain(self.mainBall)

        for i in range(self.numBalls):
            ball = Ball((self.paddle.x, self.paddle.y),
                        self.paddle.height)
            self.ballSprites.add(ball)

    # Draw score
    def drawScore(self):
        """
        Draws the score to the bottom right of the screen.
        """
        text = load_text("Score: %s" % self.score, 18)
        textpos = text.get_rect(bottomright=(self.width,
                                             self.height))
        pygame.draw.rect(self.screen,
                         (0, 0, 0),
                         textpos)
        self.screen.blit(text, textpos)

    # Draw level name to screen
    def drawName(self):
        """
        Draws the current level name to the bottom middle
        of the screen.
        """
        text = load_text("%s" % self.level.name, 18)
        textpos = text.get_rect(midbottom=(self.width/2, self.height))

        self.screen.blit(text, textpos)

    # Draw lives
    def drawLives(self):
        """
        Draws the number of lives remaining to the bottom left
        of the screen.
        """
        if self.lives > 0:
                for i in range(self.lives - 1):
                    pygame.draw.circle(self.screen,
                                       (255, 255, 255),
                                       (self.lifeX + (i*10), self.lifeY),
                                       self.lifeRadius)

    # MENU LOOP FUNCTION
    def menuLoop(self, skipMenu):
        """
        Function used to give the user a navigatable menu.
        Once this loop returns, the game begins.
        """
        # Skipping menu means user has progressed to next level
        if skipMenu:
            return False

        else:
            background = pygame.Surface(self.screen.get_size()).convert()
            background.fill((0, 0, 0))
            self.screen.blit(background, (0, 0))
            
            mainText = load_text("Breakout!", 48, (255, 255, 255))

            # Message
            mainTextPos = mainText.get_rect(midtop=(self.width/2,
                                            0))
            self.screen.blit(mainText, mainTextPos)
            
            mainText = load_text("Type from 1-5 to select level.", 36, (255, 255, 255))

            # Message
            mainTextPos = mainText.get_rect(midtop=(self.width/2,
                                            self.height/2))
            self.screen.blit(mainText, mainTextPos)
            
            # Loop
            while 1:
                # EVENT CHECKER
                for event in pygame.event.get():
                    # Window 'X' clicked
                    if event.type == pygame.QUIT:
                        pygame.quit()
                        sys.exit()

                    # Keys pressed
                    if event.type == KEYDOWN:
                        # Quit game
                        if event.key == K_ESCAPE or event.key == K_q:
                            pygame.event.post(pygame.event.Event(QUIT))
                        # Levels
                        if event.key == K_1:
                            self.currentLevel = 1
                            return True

                        if event.key == K_2:
                            self.currentLevel = 2
                            return True

                        if event.key == K_3:
                            self.currentLevel = 3
                            return True
                            
                        if event.key == K_4:
                            self.currentLevel = 4
                            return True
                            
                        if event.key == K_5:
                            self.currentLevel = 5
                            return True

                pygame.display.flip()

                # Keep track of time elapsed
                self.elapsed = self.clock.tick(60)
            

    # GAME LOOP FUNCTION
    def gameLoop(self, newGame):
        """
        Function houses a loop that isrepeated over and over to check
        for new events, such as key presses or events in game.
        """
        # Reset score and lives if user starting new game
        if newGame:
            self.lives = 3
            self.score = 0
            self.ballLaunched = False

        # Load our sprites
        self.loadSprites()

        # Set key repeat on
        pygame.key.set_repeat(5, 10)

        # Draw background to screen initially
        self.screen.blit(self.level.background, (0, 0))
        self.level.brickSprites.draw(self.screen)
        self.drawLives()
        self.drawScore()
        self.drawName()

        while 1:
            seconds = self.elapsed / 1000.0
            
            # First rotation hasn't occurred yet
            if self.level.rotated:
                rotatedScreen = pygame.transform.rotate(self.screen, -self.level.rotation)
                self.screen.blit(rotatedScreen, (0, 0))


            # Redraw where paddle and balls used to be
            self.screen.blit(self.level.background,
                             (self.paddle.rect.x, self.paddle.rect.y),
                             self.paddle.rect)
            for ball in self.ballSprites:
                self.screen.blit(self.level.background,
                                 (ball.rect.x, ball.rect.y),
                                 ball.rect)

############# EVENT CHECKER ###################################
            for event in pygame.event.get():
                # Window 'X' clicked
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                # Keys pressed
                if event.type == KEYDOWN:
                    # Quit game
                    if event.key == K_ESCAPE or event.key == K_q:
                        pygame.event.post(pygame.event.Event(QUIT))

                    # Pause game
                    if event.key == K_p:
                        pygame.key.set_repeat()
                        self.paused = True

                        self.screen.blit(self.pauseText, self.pauseTextPos)
                        self.paddleSprite.draw(self.screen)
                        self.ballSprites.draw(self.screen)
                        pygame.display.flip()

                        pygame.event.clear()

                        # If paused, flow control does not leave this
                        # loop until unpaused.
                        while self.paused:
                            for event in pygame.event.get():
                                if event.type == KEYDOWN:
                                    # Unpause game
                                    if event.key == K_p:
                                        pygame.key.set_repeat(5, 10)
                                        self.paused = False

                                        # Blit out text and old ball location
                                        self.screen.blit(self.level.background,
                                                         (self.pauseTextPos.x,
                                                          self.pauseTextPos.y),
                                                         self.pauseTextPos)
                                        for ball in self.ballSprites:
                                            self.screen.blit(self.level.background,
                                                             (ball.rect.x,
                                                              ball.rect.y),
                                                             ball.rect)
                                        pygame.display.flip()
                                    # Need to update elapsed time, or
                                    # else balls will end up somewhere
                                    # wacky.
                                    self.elapsed = self.clock.tick(60)

                    # Move paddle
                    if (event.key == K_LEFT or
                            event.key == K_RIGHT):
                        for ball in self.ballSprites:
                            self.paddle.move(event.key,
                                             self.width,
                                             self.height,
                                             ball,
                                             seconds)

                    # Start game by launching the ball
                    if event.key == K_SPACE:
                        if not self.ballLaunched:
                            for ball in self.ballSprites:
                                ball.launch()
                            self.ballLaunched = True

                    # Go back to menu
                    if event.key == K_m:
                        self.ballSprites.empty()
                        self.paddleSprite.empty()
                        self.level.brickSprites.empty()
                        return "menu"

############# BALL MOVER ###############################
            if self.ballLaunched:
                for ball in self.ballSprites:
                    ballLost = ball.move(self.width,
                                         self.height,
                                         seconds,
                                         self.paddle)

                    # Check if ball went past paddle
                    if ballLost:
                        ball.kill()
                        if not self.ballSprites:
                            self.mainBall = Ball((self.paddle.x, self.paddle.y),
                                                 self.paddle.height)
                            self.ballSprites.add(self.mainBall)
                            for i in range(self.numBalls):
                                ball = Ball((self.paddle.x, self.paddle.y),
                                                     self.paddle.height)
                                self.ballSprites.add(ball)
                            self.ballLaunched = False

                            # Lose a life, fill in circle where one used to be
                            self.lives -= 1
                            self.drawScore()
                            self.drawName()
                            pygame.draw.circle(self.screen,
                                       (0, 0, 0),
                                       (self.lifeX + ((self.lives - 1)*10), self.lifeY),
                                       self.lifeRadius)

                            # End game if lives are gone
                            if self.lives == 0:
                                return "lost"

############# COLLISION DETECTION ###########################
            # Collision detection between ball and paddle
            hitPaddle = pygame.sprite.spritecollide(self.paddle,
                                                    self.ballSprites,
                                                    False)
            if hitPaddle:
                # For levels that have constant rotation
                if self.level.alwaysRotating:
                    if self.level.rotation == 360:
                        self.level.rotation = 90
                    else:
                        self.level.rotation += 90
                    
                for ball in hitPaddle:
                    ball.paddleCollide(self.paddle)

            # Collision detection between ball and brick
            if not self.level.brickSprites:
                try:
                    BreakoutMain.levels[self.currentLevel + 1]
                    self.currentLevel += 1
                    self.ballSprites.empty()
                    self.paddleSprite.empty()
                    self.level.brickSprites.empty()
                    self.ballLaunched = False
                    return "next"
                except IndexError:
                    return "won"
            else:
                for ball in self.ballSprites:
                    hitBricks = pygame.sprite.spritecollide(ball,
                                                            self.level.brickSprites,
                                                            True)
                    ball.brickCollide(hitBricks)
                    for brick in hitBricks:
                        self.screen.blit(self.level.background,
                                         (brick.rect.x, brick.rect.y),
                                         brick.rect)
                        self.score += 1
                        # Redraw score
                        self.drawScore()

############# SPRITE REFRESH #################################
            # Redraw lives left
            self.drawLives()

            # Redraw sprites
            self.paddleSprite.draw(self.screen)
            self.ballSprites.draw(self.screen)
            if self.level.rotation != 0:
                rotatedScreen = pygame.transform.rotate(self.screen, self.level.rotation)
                self.screen.blit(rotatedScreen, (0, 0))
                self.level.rotated = True
            pygame.display.flip()

            # Keep track of time elapsed
            self.elapsed = self.clock.tick(60)
############################################################

    # END LOOP FUNCTION
    def endLoop(self, state):
        """
        Called when the game reaches an end state.
        There are 3 possible states:
            -Game Win
            -Game Lose
            -Next Level
        This loop will handle them all accordingly.
        """
        if state == "menu":
            return False
        
        else:
            background = pygame.Surface(self.screen.get_size()).convert()
            background.fill((0, 0, 0))
            self.screen.blit(background, (0, 0))

            pygame.time.delay(500)

            # Check state, and change screen accordingly
            if state == "lost":
                mainText = load_text("You Lose.", 48, (255, 0, 0))
            elif state == "won":
                mainText = load_text("You Won!", 48, (0, 255, 0))
            elif state == "next":
                mainText = load_text("Level Completed.", 36, (0, 255, 255))

            # Message
            mainTextPos = mainText.get_rect(center=(self.width/2,
                                            self.height/3))
            self.screen.blit(mainText, mainTextPos)

            if state == "next":
                scoreText = load_text("Score so far: %s" % self.score,
                                      36,
                                      (255, 255, 0))
            else:
                scoreText = load_text("Final Score: %s" % self.score,
                                      36,
                                      (255, 255, 0))
            # Score
            scoreTextPos = scoreText.get_rect(center=(self.width/2,
                                              (self.height/2) - 30))
            self.screen.blit(scoreText, scoreTextPos)

            # Controls
            if state == "next":
                sText = load_text("Tap 'space' for next level", 24)
                sTextPos = sText.get_rect(center=(self.width/2,
                                                  (self.height/1.5) - 30))
                self.screen.blit(sText, sTextPos)

            qText = load_text("Tap 'q' to quit", 24)
            qTextPos = qText.get_rect(center=(self.width/2,
                                              self.height/1.5))
            self.screen.blit(qText, qTextPos)

            mText = load_text("Tap 'm' for main menu", 24)
            mTextPos = mText.get_rect(center=(self.width/2,
                                              (self.height/1.5) + 30))
            self.screen.blit(mText, mTextPos)

            # Loop
            while 1:
                # EVENT CHECKER
                for event in pygame.event.get():
                    # Window 'X' clicked
                    if event.type == pygame.QUIT:
                        pygame.quit()
                        sys.exit()

                    # Keys pressed
                    if event.type == KEYDOWN:
                        # Quit game
                        if event.key == K_ESCAPE or event.key == K_q:
                            pygame.event.post(pygame.event.Event(QUIT))

                        if event.key == K_SPACE:
                            if state == "next":
                                return True

                        if event.key == K_m:
                            return False

                pygame.display.flip()

                # Keep track of time elapsed
                self.elapsed = self.clock.tick(60)
コード例 #57
0
ファイル: main.py プロジェクト: JoseMMA88/PongGame
from turtle import Screen
from paddle import Paddle
from ball import Ball
from score import Score
import time

# Screen Setup
screen = Screen()
screen.setup(width=800, height=600)
screen.title("PONG GAME")
screen.bgcolor("black")
screen.tracer(0)

# Paddle Setup
paddle_1 = Paddle((350, 0))
paddle_2 = Paddle((-350, 0))

# Score Setup
score_1 = Score((40, 260))
score_2 = Score((-40, 260))

# Ball Setup
ball = Ball()

# Controls listeners
screen.listen()
screen.onkeypress(fun=paddle_1.move_up, key="Up")
screen.onkeypress(fun=paddle_1.move_down, key="Down")
screen.onkeypress(fun=paddle_2.move_up, key="w")
screen.onkeypress(fun=paddle_2.move_down, key="s")
コード例 #58
0
ファイル: game.py プロジェクト: SkylerKidd/CodeZ
class Game(object):
    """Main program"""

    def __init__(self):
        #Initialize pygame and window
        pygame.init()
        self.screen_width, self.screen_height = 400, 600
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height), 0, 32)
        self.screen.fill(blue)
        pygame.display.update()

        #Clock
        self.clock = pygame.time.Clock()

        #Bricks
        self.blocks = list()
        for w in range(1,self.screen_width,50):
			for h in range(23, 198, 22):
				self.blocks.append(Block(self.screen_width, self.screen_height, w, h, orange, blue_shadow))

        #Paddle
        self.paddle = Paddle(self.screen_width, self.screen_height, purple, blue_shadow)

        #Ball
        self.ball = Ball(self.screen_width, self.screen_height, green, blue_shadow)

    def update(self):
        self.clock.tick(game_speed)

        self.paddle.update()
        self.ball.update(self.paddle)

    def draw(self):
        #Redraw Background
        self.screen.fill(blue)

        for block in self.blocks:
            block.draw_shadow(self.screen)

        self.ball.draw_shadow(self.screen)
        self.paddle.draw_shadow(self.screen)

        for block in self.blocks:
            block.draw(self.screen)

        self.ball.draw(self.screen)
        self.paddle.draw(self.screen)


    def new_game(self):
        self.game_over = False
        self.round = 0

        self.play()

    def new_round(self):
        pass

    def play(self):
        while not self.game_over:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
						self.ball.serve()
                    if event.key == pygame.K_LEFT:
                        self.paddle.x_vel = -4
                    elif event.key == pygame.K_RIGHT:
                        self.paddle.x_vel = 4
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT and self.paddle.x_vel < 0:
                        self.paddle.x_vel = 0
                    if event.key == pygame.K_RIGHT and self.paddle.x_vel > 0:
                        self.paddle.x_vel = 0
            self.update()
            self.draw()
            pygame.display.update()
コード例 #59
0
from turtle import Screen
from scoreboard import Scoreboard
import time
from paddle import Paddle
from ball import Ball

screen = Screen()

screen.listen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(0)

r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))

ball = Ball()
scoreboard = Scoreboard()

screen.onkey(r_paddle.move_up, "Up")
screen.onkey(r_paddle.move_down, "Down")
screen.onkey(l_paddle.move_up, "w")
screen.onkey(l_paddle.move_down, "s")
game_is_on = True

while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()
コード例 #60
0
ファイル: player.py プロジェクト: prgreen/grym
class Player:

	OBJECT_INDEX = 0

	def __init__(self, playerName):

		self.id = Player.OBJECT_INDEX
		self.color = PLAYER_COLOR[self.id]
		self.totalScore = 0
		self.scores = []
		self.name = playerName
		self.lives = NB_LIVES['INIT']

		self.timesFrm = {}
		self.loadTimes()
		
		Player.OBJECT_INDEX += 1

	def initPaddle(self, padWidth, padHeight, padColor, padPosX0, padPosY0):
		self.paddleX0 = padPosX0
		self.paddleY0 = padPosY0
		self.paddle = Paddle(width=padWidth, height=padHeight, posX=self.paddleX0, posY=self.paddleY0, color=padColor)


	def initScore(self):
		""" Empties list of scores and init level score """
		del self.scores[:]
		self.scores.append(Score(label=SCORE_LVL_LBL, factor=1, value=0))

	def addBonus(self, bonusType, factor=1, value=0):
		""" Adds bonus to the list of scores """
		lbl = BONUS[bonusType][BONUS_INDEX['LBL']]
		val = value if BONUS[bonusType][BONUS_INDEX['VALUE']] == 'value' else BONUS[bonusType][BONUS_INDEX['VALUE']]
		self.scores.append(Score(label=lbl, factor=factor, value=val))

	def addBonusToTotalScore(self):
		""" Adds values of the list of bonus to total score """
		for s in self.scores[1:]:
			self.totalScore += (s.value*s.factor)

	def applyEffect(self, effectType):
		""" Applies effect to player """
		# PLA_LIFEUP: Add 1 life
		if effectType == USABLE_TYPE['PLA_LIFEUP']:
			self.addLife()
			self.paddle.applyEffect(effectType)


	def addLife(self):
		self.lives = self.lives+1 if self.lives < NB_LIVES['MAX'] else NB_LIVES['MAX']


	@staticmethod
	def initId():
		Player.OBJECT_INDEX = 0


	def addTime(self, timeFrm, lvlId):
		""" Adds time (frame number) for a level to the list of player's times """
		self.timesFrm[lvlId] = timeFrm
		

	def getTime(self, lvlId):
		""" Returns existing time (frame number) for a level, None else """
		if lvlId in self.timesFrm:
			return self.timesFrm[lvlId]

		return None
		
	def ensureDir(self, f):
		d = os.path.dirname(f)
		if not os.path.exists(d):
			os.makedirs(d)
			
	def loadTimes(self):
		self.ensureDir(PLAYERS_DIR)
		try:
			with open(PLAYERS_DIR+self.name) as f:
				lines = f.read()
				for line in lines.split('\n'):
					if line != '':
						l = line.split('|')
						self.timesFrm[l[0]] = int(l[1])
				f.close()
		except IOError:
			pass

	def saveTimes(self):
		f = open(PLAYERS_DIR+self.name, 'w')
		for k,v in self.timesFrm.iteritems():
			f.write(str(k)+'|'+str(v)+'\n')
		f.close()


# TODO
# Store / load player's trophy history