Exemplo n.º 1
0
def main():
    for i in range(10):
        balls.append(Ball((width / 2, height / 2)))
    while True:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()

    # NEW FOLLOWS ***************************************************
            if event.type == MOUSEBUTTONDOWN:
                balls.append(Ball(event.pos))
            if event.type == KEYDOWN:
                if event.key == K_d:
                    for i in range(len(balls) // 2):
                        balls.pop(0)
                if event.key == K_f:
                    pygame.display.set_mode(screen_size, FULLSCREEN)
                if event.key == K_ESCAPE:
                    pygame.display.set_mode(size)
    # NEW ABOVE *****************************************************

        screen.fill(color)
        for ball in balls:
            ball.update()
        for ball in balls:
            ball.draw(screen)

        pygame.display.flip()
Exemplo n.º 2
0
    def update(self):
        self.delta_time = self.clock.tick() / 1000.0
        self.paddle.move_paddle()
        self.ball.update(self.delta_time)

        if self.ball.position.y < 100:
            self.ball.check_collision(self.paddle, self.delta_time)
            if (self.ball.check_loss()):
                self.hearts.remove_life()
                if self.hearts.lives == 0:
                    self.game_lost = True
                    self.game_on = False
                self.ball = Ball(
                    Point(-200, -200),
                    Vector(120 + (self.level * 60), 360 + (self.level * 60)))

        for tile in self.tiles:
            if (self.ball.check_collision(tile, self.delta_time)):
                self.tile_sound.play()
                self.tiles.remove(tile)

        if self.tiles == []:
            if self.level == self.max_level:
                self.game_won = True
                self.game_on = False
            else:
                self.restart()
Exemplo n.º 3
0
    def splitBall(self, size, x, y):
        if int(size / 2) <= MINBALLSIZE:
            if len(balls) == 0:
                print('prije next leve')
                self.loadNextLevel()
                #self.timer.stop()
                #time.sleep(3)
                #self.loadNextLevel()
        else:
            ball1 = Ball(int(size / 2))
            ball2 = Ball(int(size / 2))

            self.setBallProperties(ball1, x, y, True)
            self.setBallProperties(ball2, x, y, False)

            balls.append(ball1)
            balls.append(ball2)

            if random.randrange(BONUS_RANGE) == 0:
                bonus_type = random.choice(bonus_types)
                bonus = Bonus(x, y, bonus_type)
                bonus.isActive = True
                bonuses.append(bonus)

            ball1.splitedLeft = True
            ball2.splitedRight = True
            ball1.splitedCounter = 42
            ball2.splitedCounter = 42
            ball1.y = ball1.dy
            ball2.y = ball2.dy
Exemplo n.º 4
0
    def __init__ (self, parent):
        self.ball = Ball(80, 200, 6, -3, 10., 'red')

        self.wait_time = 100 

        self.isstopped = False 

        self.maxx = 400 # canvas width, in pixels
        self.maxy = 400 # canvas height, in pixels

        self.parent = parent
        self.frame = Frame(parent)
        self.frame.pack()
        self.top_frame = Frame(self.frame)
        self.top_frame.pack(side=TOP)
        self.canvas = Canvas(self.top_frame, background="white", \
                             width=self.maxx, height=self.maxy )
        self.canvas.pack()
        self.bottom_frame = Frame(self.frame)
        self.bottom_frame.pack(side=BOTTOM)
        self.restart = Button(self.bottom_frame, text="Restart", command=self.restart)
        self.restart.pack(side=LEFT)
        self.slow = Button(self.bottom_frame, text="Slower", command=self.slower)
        self.slow.pack(side=LEFT)
        self.fast = Button(self.bottom_frame, text="Faster", command=self.faster)
        self.fast.pack(side=LEFT)
        self.quit = Button(self.bottom_frame, text="Quit", command=self.quit)
        self.quit.pack(side=RIGHT)
Exemplo n.º 5
0
    def loadNextLevel(self):
        self.level += 1

        nextLevelType = random.choice([0, 1])

        bonuses.clear()
        balls.clear()

        if nextLevelType == 0:
            if self.startingBallSize * 2 <= MAXBALLSIZE:
                self.startingBallSize = self.startingBallSize * 2
                balls.append(Ball(self.startingBallSize))
            else:
                nextLevelType = 1
        if nextLevelType == 1:
            self.previousBalls = self.previousBalls + 1
            temp = self.previousBalls
            for x in range(self.previousBalls):
                balls.append(Ball(self.startingBallSize))
            for b in balls:
                if self.currentBall % 2 == 0:
                    b.x = b.x - 35 * (temp)
                    temp += 1
                    b.counter = math.floor(b.x)
                    b.forward = False
                elif self.currentBall % 2 == 1:
                    b.x = b.x + 35 * (temp)
                    temp += 1
                    b.counter = math.floor(b.x)
                self.currentBall += 1

        #self.stopOnStart = True

        queue.put(Qt.Key_Minus)
Exemplo n.º 6
0
    def __init__(self, parent):
        ##=====DATA RELEVANT TO BALL===============
        ##  We are going to repeatedly draw a ball object on the canvas,
        ##  "moving" it across the canvas.  The ball object is specified
        ## by (a) its x and y center coordinates (a tuple), (b) its radius,
        ##  (c) the delta x and delta y to move the ball in each time
        ## increment, and (d)  its color.
        self.ball_x, self.ball_y = 100, 200  # initial location
        self.ball_radius = 10
        self.ball_dx, self.ball_dy = 6, -3  # the movement of the ball object
        self.ball_color = "slateblue"

        self.b = Ball(self.ball_x, self.ball_y, self.ball_dx, self.ball_dy,
                      self.ball_radius, self.ball_color)
        #========DATA NEEDED FOR ANIMATION=========
        #  Here is the time in milliseconds between consecutive instances
        #  of drawing the ball.  If this time is too small the ball will
        #  zip across the canvas in a blur.
        self.wait_time = 100

        #this will allow us to stop moving the ball when the program quits
        self.isstopped = False

        self.maxx = 400  # canvas width, in pixels
        self.maxy = 400  # canvas height, in pixels

        #=============CREATE THE NEEDED GUI ELEMENTS===========
        ##  Create a frame, attach a canvas and 4 buttons to this frame
        ##  Buttons are used to cleanly exit the program;
        ##  to speed up or slow down the animation, and to restart
        ##  the animation.
        ##  Canvas, like an image, is an object that we can draw objects on.
        ##  This canvas is called chart_1.
        ##  Parent = root window, contains a frame
        ##  The frame contains the canvas and the 4 buttons.
        ##  We only care about the canvas in our animation
        self.parent = parent
        self.frame = Frame(parent)
        self.frame.pack()
        self.top_frame = Frame(self.frame)
        self.top_frame.pack(side=TOP)
        self.canvas = Canvas(self.top_frame, background="white", \
                             width=self.maxx, height=self.maxy )
        self.canvas.pack()
        self.bottom_frame = Frame(self.frame)
        self.bottom_frame.pack(side=BOTTOM)
        self.restart = Button(self.bottom_frame,
                              text="Restart",
                              command=self.restart)
        self.restart.pack(side=LEFT)
        self.slow = Button(self.bottom_frame,
                           text="Slower",
                           command=self.slower)
        self.slow.pack(side=LEFT)
        self.fast = Button(self.bottom_frame,
                           text="Faster",
                           command=self.faster)
        self.fast.pack(side=LEFT)
        self.quit = Button(self.bottom_frame, text="Quit", command=self.quit)
        self.quit.pack(side=RIGHT)
Exemplo n.º 7
0
def checkColide():
    global ball, background, ennemy
    y = (Ball.getY(ball)) - 1  #-1 les deux y,x
    x = ball['x'] - 1
    if Background.getI(background, int(x), int(y), Ball.getS(ball)) == '-':
        sys.stdout.write("crashed on the borders" + "\n")
        quitGame()
Exemplo n.º 8
0
 def hit(self):
     game = self.get_game()
     super(BallBrick, self).hit()
     ball = Ball((GameConstants.SCREEN_SIZE[0] / 2,
                  GameConstants.SCREEN_SIZE[1] * 2 / 3),
                 pygame.image.load(GameConstants.SPRITE_BALL), game)
     game.add_a_ball(ball)
     ball.set_motion(True)
Exemplo n.º 9
0
 def __init__(self):
     pygame.init()
     (WIDTH, HEIGHT) = (640, 480)
     self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
     pygame.display.set_caption("Pong Game")
     self.ball = Ball(5, 5, 35, 35, 5, 5, Pong.CLR["RED"])
     self.paddle = Paddle(WIDTH / 2, HEIGHT - 50, 100, 10, 3,
                          Pong.CLR["RED"])
Exemplo n.º 10
0
def event_handler():
    for event in pygame.event.get():
        if event.type == QUIT:
            Tools.OnExit()
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                Tools.OnExit()
            if event.key == K_r:
                # RàZ du jeu
                Tools.GameInit()
            if event.key == K_SPACE:
                Config.Sounds['intro'].stop()
                Config.Sounds['intro-2'].play()
                # on lance les balles
                Ball.Ballsmoving()
                if Config.player.laserMode:
                    Config.player.laserFire()
            if event.key == K_LEFT:
                Config.player.moveLeft()
            if event.key == K_RIGHT:
                Config.player.moveRight()
            if (event.key == K_PLUS
                    or event.key == K_KP_PLUS) and Config.godMode:
                # cheat code, on change de niveau
                Tools.NextLevel()
            if (event.key == K_MINUS
                    or event.key == K_KP_MINUS) and Config.godMode:
                # cheat code, on change de niveau
                if Config.level > 1:
                    Config.level -= 1
                else:
                    # on boucle
                    Config.level = Config.maxlevel
                Level.LoadLevel(Config.level)
                if Config.bossLevel:
                    # niveau d'un boss
                    Boss.doBossLevel()
                else:
                    Tools.InitBG()
                Bonus.initBonus()
                Config.player.reset()
                Ball.Ballsreset()
        elif event.type == KEYUP:
            if event.key == K_LEFT or event.key == K_RIGHT:
                Config.player.state = "still"
        elif event.type == USEREVENT:
            # MàJ des fps toutes les secondes
            pygame.display.set_caption(
                Config.titre +
                ' (fps: {0:.0f})'.format(Config.clock.get_fps()))
        elif event.type == (USEREVENT + 1):
            # génération d'ennemis (toutes les 10s)
            if not Config.Perdu and not Level.FinishedLevel():
                Enemys.randomGen()
        elif event.type == (USEREVENT + 2):
            # génération des bombes et missiles du boss (déclenché toutes les 5s)
            if Config.bossLevel:
                Config.boss.attack()
Exemplo n.º 11
0
def interact():
    global ball, background, timeStep
    if isData():
        c = sys.stdin.read(1)
        if c == '\x1b':  # x1b is ESC
            quitGame()
        elif c == 'a':
            Ball.moveUp(ball)
        elif c == 'x':
            Ball.moveDown(ball)
Exemplo n.º 12
0
def MULTIBALL(ball_group):

    for ball in ball_group:
        temp_ball = Ball(ball.rect.centerx, ball.rect.centery)
        temp_ball.dx, temp_ball.dy = ball.dx, ball.dy
        temp_ball.dx *= -1
        temp_ball.SPAWNSTATE = False
        ball_group.add(temp_ball)

    return ball_group
Exemplo n.º 13
0
class Pong(object):
    CLR = {"WHITE": (255, 255, 255), "RED": (255, 0, 0)}

    def __init__(self):
        pygame.init()
        (WIDTH, HEIGHT) = (640, 480)
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("Pong Game")
        self.ball = Ball(5, 5, 35, 35, 5, 5, Pong.CLR["RED"])
        self.paddle = Paddle(WIDTH / 2, HEIGHT - 50, 100, 10, 3,
                             Pong.CLR["RED"])

    def play(self):
        clock = pygame.time.Clock()
        while True:
            clock.tick(50)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type in (pygame.KEYDOWN, pygame.KEYUP):
                    self.paddle.key_handler(event)

            self.collision_handler()
            self.draw()

    def collision_handler(self):
        if self.ball.rect.colliderect(self.paddle.rect):
            self.ball.vy *= -1

        if self.ball.x + self.ball.width >= self.screen.get_width():
            self.ball.vx = -(math.fabs(self.ball.vx))
        elif self.ball.x <= 0:
            self.ball.vx = math.fabs(self.ball.vx)

        if self.ball.y + self.ball.height >= self.screen.get_height():
            pygame.quit()
            sys.exit()
        elif self.ball.y <= 0:
            self.ball.vy = math.fabs(self.ball.vy)

        if self.paddle.x + self.paddle.width >= self.screen.get_width():
            self.paddle.x = self.screen.get_width() - self.paddle.width
        elif self.paddle.x <= 0:
            self.paddle.x = 0

    def draw(self):
        self.screen.fill(Pong.CLR["WHITE"])
        self.ball.update()
        self.ball.render(self.screen)
        self.paddle.update()
        self.paddle.render(self.screen)

        pygame.display.update()
Exemplo n.º 14
0
 def __call__(self, dt):
     self.createBallTimer += dt
     if (self.createBallTimer > self.createBallInterval):
         self.createBallTimer = 0.0
         ball = Ball(random.choice(self.ballTypes))
         ball.moveStrategy = SinusMoveStrategy(self.angularSpeed, random.choice([-1, 1])*self.ballSpeed, ball);
         self.gameLayer.addBall(ball)
         self.ballsLeft -= 1
         if self.ballsLeft == 0:
             self.expired = True
             return
Exemplo n.º 15
0
 def __init__(self, game):
     super(HighScoreScene, self).__init__(game)
     self.__level = Level(game)
     self.__level.load_highscores()
     self.__balls = [
         Ball((GameConstants.SCREEN_SIZE[0] * random.random(),
               GameConstants.SCREEN_SIZE[1] * random.random()),
              pygame.image.load(GameConstants.SPRITE_BALL), game),
         Ball((GameConstants.SCREEN_SIZE[0] * random.random(),
               GameConstants.SCREEN_SIZE[1] * random.random()),
              pygame.image.load(GameConstants.SPRITE_BALL), game)
     ]
Exemplo n.º 16
0
    def __init__(self):
        self.screen_size = (800, 800)
        self.ballObject = Ball(400, 400, 0, 200)  # x, y, z, r
        self.ballObject.setMaterialToMetal()
        self.LightObject = Light(400, 400, 400, 83)  # x, y, z, power
        self.Ia = 87
        self.Ka = 0.39
        self.fatt = 0.63

        super().__init__()

        if (len(sys.argv) > 1 and sys.argv[1] == "--debug"):
            nSlider = QSlider(Qt.Horizontal, self)
            nSlider.setGeometry(10, 10, 100, 10)
            nSlider.valueChanged[int].connect(self.changeN)
            self.labelN = QLabel("N=" + str(self.ballObject.n), self)
            self.labelN.setGeometry(110, 10, 50, 10)

            ksSlider = QSlider(Qt.Horizontal, self)
            ksSlider.setGeometry(10, 20, 100, 10)
            ksSlider.valueChanged[int].connect(self.changeKs)
            self.labelKs = QLabel("Ks=" + str(self.ballObject.Ks), self)
            self.labelKs.setGeometry(110, 20, 50, 10)

            kdSlider = QSlider(Qt.Horizontal, self)
            kdSlider.setGeometry(10, 30, 100, 10)
            kdSlider.valueChanged[int].connect(self.changeKd)
            self.labelKd = QLabel("Kd=" + str(self.ballObject.Kd), self)
            self.labelKd.setGeometry(110, 30, 50, 10)

            iaSlider = QSlider(Qt.Horizontal, self)
            iaSlider.setGeometry(10, 160, 100, 10)
            iaSlider.valueChanged[int].connect(self.changeIa)
            self.labelIa = QLabel("Ia=" + str(self.Ia), self)
            self.labelIa.setGeometry(110, 160, 50, 10)

            kaSlider = QSlider(Qt.Horizontal, self)
            kaSlider.setGeometry(10, 170, 100, 10)
            kaSlider.valueChanged[int].connect(self.changeKa)
            self.labelKa = QLabel("Ka=" + str(self.Ka), self)
            self.labelKa.setGeometry(110, 170, 50, 10)

            ipSlider = QSlider(Qt.Horizontal, self)
            ipSlider.setGeometry(10, 180, 100, 10)
            ipSlider.valueChanged[int].connect(self.changeIp)
            self.labelIp = QLabel("Ip=" + str(self.LightObject.power), self)
            self.labelIp.setGeometry(110, 180, 50, 10)

            fattSlider = QSlider(Qt.Horizontal, self)
            fattSlider.setGeometry(10, 190, 100, 10)
            fattSlider.valueChanged[int].connect(self.changeFatt)
            self.labelFatt = QLabel("fatt=" + str(self.fatt), self)
            self.labelFatt.setGeometry(110, 190, 50, 10)
Exemplo n.º 17
0
 def __call__(self, dt):
     self.createBallTimer += dt
     if (self.createBallTimer > self.createBallInterval):
         self.createBallTimer = 0.0
         ball = Ball(random.choice(self.ballTypes))
         angle = 2*math.pi*random.random()
         ball.moveStrategy = LineerMoveStrategy(angle, self.ballSpeed, ball);
         self.gameLayer.addBall(ball)
         self.ballsLeft -= 1
         if self.ballsLeft == 0:
             self.expired = True
             return
Exemplo n.º 18
0
    def __init__(self):
        self.ball = Ball()

        #  tracker variables for keyboard keys (keyboard key ???)
        self.W_PRESSED = 0
        self.S_PRESSED = 0
        self.UP_PRESSED = 0
        self.DOWN_PRESSED = 0

        #  which AIs computer player are going to use
        self.COMPUTER_1_AI = INPUT_TYPE_COMPUTER_KURALBAZ
        self.COMPUTER_2_AI = INPUT_TYPE_COMPUTER_KURALBAZ
Exemplo n.º 19
0
 def update(self, timeDelta):
     self.clock += timeDelta/1000.
     if self.clock>=5:
         self.clock = 0.
         for iter in range(0,3):
             # бөмбөг нэмэх
             bullet = Ball(self.game,self.game.world, self.nextBallpos, self.nextBallType)
             bullet.firstThump = False
             self.game.objects.append(bullet)
             self.nextBallpos = (randint(tile_size/2, (tile_dim[0]-1)*tile_size),(tile_dim[1]-2)*tile_size-0.8)
             self.nextBallType = randint(0,5)            
     pass
Exemplo n.º 20
0
 def __call__(self, dt):
     self.createBallTimer += dt
     if (self.createBallTimer > self.createBallInterval):
         self.createBallTimer = 0.0
         angle = 2*math.pi*random.random()
         for type in random.sample(self.ballTypes, self.simul):
             ball = Ball(type)
             ball.moveStrategy = LineerMoveStrategy(angle, self.ballSpeed, ball)
             self.gameLayer.addBall(ball)
             angle += self.angleStep
         self.ballsLeft -= 1
         if self.ballsLeft == 0:
             self.expired = True
             return
Exemplo n.º 21
0
    def checkCollision2Balls(self, b1, b2):
        distance = np.sqrt((b1.x - b2.x)**2 + (b1.y - b2.y)**2)
        if b1.x == -10 or b2.x == -10 or b1.y == -10 or b2.y == -10 or (
                b1.speed == 0 and b2.speed == 0):
            pass
        elif distance <= 2 * BALL_RADIUS and (
                b1.speed > 0.08 or b2.speed > 0.08
        ):  # Checks if collided and whether the balls are going at a huge speed that would make them overlap
            collisionAngle = math.atan2(b2.y - b1.y, b2.x - b1.x)
            vx1 = math.cos(collisionAngle) * (b2.speed * math.cos(
                b2.angle - collisionAngle)) - math.sin(collisionAngle) * (
                    b1.speed * math.sin(b1.angle - collisionAngle))
            vy1 = math.sin(collisionAngle) * (b2.speed * math.cos(
                b2.angle - collisionAngle)) + math.cos(collisionAngle) * (
                    b1.speed * math.sin(b1.angle - collisionAngle))
            vx2 = math.cos(collisionAngle) * (b1.speed * math.cos(
                b1.angle - collisionAngle)) - math.sin(collisionAngle) * (
                    b2.speed * math.sin(b2.angle - collisionAngle))
            vy2 = math.sin(collisionAngle) * (b1.speed * math.cos(
                b1.angle - collisionAngle)) + math.cos(collisionAngle) * (
                    b2.speed * math.sin(b2.angle - collisionAngle))
            # print("Collision Angle: " + str(collisionAngle * 180 / pi))
            # print(vx1, vy1, vx2, vy2)
            b1.speed = math.sqrt(vx1**2 + vy1**2)
            b1.angle = Ball.principleRadianAngle(math.atan2(vy1, vx1))
            b2.speed = math.sqrt(vx2**2 + vy2**2)
            b2.angle = Ball.principleRadianAngle(math.atan2(vy2, vx2))
            # print(b1.speed, b1.angle * 180 / pi, b2.speed, b2.angle * 180 / pi)

            if self.firstCollide is None and (type(b1) is Ball.WhiteBall
                                              or type(b2) is Ball.WhiteBall):
                if type(b1) is Ball.WhiteBall:
                    self.firstCollide = type(b2)
                else:
                    self.firstCollide = type(b1)

            while (distance <= 2 * BALL_RADIUS):  # To split up the two balls
                x1 = b1.x
                y1 = b1.y
                x2 = b2.x
                y2 = b2.y
                b1.updatePosition()
                b2.updatePosition()
                distance = np.sqrt((b1.x - b2.x)**2 + (b1.y - b2.y)**2)
                # print(b1.id, b1.x, b1.y, b2.id, b2.x, b2.y)
                if b1.distance(Ball.Ball(
                        x1, y1, -5)) / b1.timeDelta < 0.1 and b2.distance(
                            Ball.Ball(x2, y2, -5)) / b2.timeDelta < 0.1:
                    break
Exemplo n.º 22
0
    def __init__(self):
        self.width = 900
        self.height = 600

        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption("This is f*****g dumb")
        self.clock = pygame.time.Clock()
        self.icon = pygame.image.load("start.png")
        pygame.display.set_icon(self.icon)

        self.font = pygame.font.Font("bit5x3.ttf", 30)


        self.ball1 = Ball(int(self.width/2), int(self.height/2), 10, (255, 0, 0), 2, 45, self.screen)
        self.player = Paddle((255, 255,255), 25, 0, 15, self.height * 0.25, 0, self.screen)
        self.enemy = Paddle((255, 255,255), self.width - 30, int(self.height/2), 15, self.height * 0.25, 0, self.screen)
Exemplo n.º 23
0
def show():
    global ball, background, ennemy, ennemy2, ennemy3

    sys.stdout.write("\033[1;1H")
    sys.stdout.write("\033[2J")
    #affichage des different element
    Background.show(background, Ball.getS(ball))
    Ball.show(ball)
    Ennemy.show(ennemy)
    Ennemy.show(ennemy2)
    Ennemy.show(ennemy3)
    #restoration couleur
    sys.stdout.write("\033[26m")
    sys.stdout.write("\033[22m")
    #deplacement curseur
    sys.stdout.write("\033[0;0H\n")
Exemplo n.º 24
0
def spawn_ball(mouse_x, mouse_y, x, y):
    global click, clicked, init_ball, balls,screen
    def speed(mouse_x, mouse_y, x, y):
        s = np.array([x, y]) - np.array([mouse_x, mouse_y]) #разница координат
        norm = np.linalg.norm(s) #вычислим норму разниц координат
        angle = math.atan2(-s[1], s[0]) #угол между разницей
        vx = norm * math.cos(angle) * 3
        vy = -norm * math.sin(angle) * 3
        return vx, vy
    if click and not clicked:
        #хотим создать шарик
        clicked = True
        x, y = mouse_x, mouse_y
        init_ball = Ball.ball(mouse_x, mouse_y, 0, 0, time.time(), screen)
        screen = init_ball.draw()
    elif click and clicked:
        #держим мышь и регулируется шарик (его параметры относительно нажатия)
        init_ball.radius = int(20 * math.sin(time.time()*2.05) + 20)
        init_ball.m = (4/3)*math.pi*math.pow(init_ball.radius,3)*init_ball.p
        init_ball.vx, init_ball.vy = speed(mouse_x, mouse_y, x, y)
        pygame.draw.aaline(screen, (255,255, 255), (x, y), (mouse_x, mouse_y))
        screen = init_ball.draw()
    elif not click and clicked:
        #отпустили мышь, шарик начинает движение
        clicked = False
        init_ball.t0 = time.time()
        balls.append(init_ball)
    return x, y
Exemplo n.º 25
0
    def loadLevel(self, lev):
        file = open(lev, 'r')
        lines = file.readlines()
        file.close()

        ballOdds = 3
        ballMax = 10
        ballCount = 0

        newlines = []
        for line in lines:
            newline = ""
            for c in line:
                if c != '\n':
                    newline += c
            newlines += [newline]
        lines = newlines

        for line in lines:
            print line

        for y, line in enumerate(lines):
            for x, c in enumerate(line):
                if c == '#':
                    Wall("wall.png", [25 * x + 12, 25 * y + 12])
                if c == 'o':
                    if ballCount < ballMax:
                        if random.randint(1, ballOdds) == 1:
                            Ball(["ball.png"], [3, 3],
                                 [25 * x + 12, 25 * y + 12])

                if c == '@':
                    self.player = PlayerBall("pBall.png", [6, 6],
                                             [25 * x + 12, 25 * y + 12])
Exemplo n.º 26
0
def init(data):
    # load data.xyz as appropriate
    data.testMode = True

    data.table = Table(data, data.width, data.height)
    data.cue = Cue(0, 0, 0, 0, 0)
    data.pockets = []
    data.balls = []
    data.pocketInit = pocket(0, 0)
    data.pocketInit.addPockets(data)
    data.table.addBalls(data, data.testMode)
    data.cueBall = Ball(data.width // 2 + 100, data.height // 2, "white")
    data.balls.append(data.cueBall)

    # used to keep record of the times space is pressed
    data.spaceTime = 0
    data.forceCounter = 0
    data.placeCueStick = False

    data.score = 0

    # game state control
    data.gameOver = False
    data.scratched = None
    data.hitted = False
    data.scratchReplace = False

    data.time = 0
Exemplo n.º 27
0
class Model:
    def __init__(self):
        self.ball = Ball(500, 100, 10)

    def setup(self, window: tk.Canvas):
        self.ball.setup(window)

    def draw(self, window: tk.Canvas):
        gravity = Vector2(0, 0.5)
        self.ball.applyForce(gravity)
        # wind = Vector2(0.1, 0)
        # ball.apply_force(wind)
        self.ball.update()
        self.ball.edges(window)

        self.ball.display(window)
Exemplo n.º 28
0
 def __init__(self):
     """Constructor of the Game"""
     self._running = True
     self.size = self.width, self.height = 450, 600
     # create main display - 640x400 window
     # try to use hardware acceleration
     self.screen = pygame.display.set_mode((400,200))#, pygame.HWSURFACE
     pygame.display.set_caption('AirHockey Server')
     self.clock = pygame.time.Clock()
     # set default tool
     self.tool = 'run'
     self.player  = Player.Player(1,r = 30 )   # Синий нижний игрок
     self.player.start_pos(self)
     self.cursor1 = Cursor.Cursor(player=self.player,game=self)
     self.player0 = Player.Player(0,r = 30 )    # Красный верхний игрок
     self.player0.start_pos(self)
     self.cursor0 = Cursor.Cursor(player=self.player0,game=self)
     self.players = (self.player0, self.player)
     self.ball    = Ball.Ball(x = self.width/2, y = self.height/2)
     self.ethik   = 10                                                  # Толщина отступов
     self.ecolor = (255,179,0)
     self.gate = 40                                                     # Полудлина ворот
     self.pressed = pygame.key.get_pressed()
     self.cursor_text = 5
     self.start_server()
     self.cursors = (self.cursor0,self.cursor1)
     self.mode = 3
Exemplo n.º 29
0
	def __init__(self, file_path):
		super(Scene, self).__init__()

		pygame.mixer.init(44100, -16, 4, 2048)
		self.position = ['goalkeeper', 'defender', 'midfielder', 'attacker']
		self.all_object_list = pygame.sprite.LayeredUpdates()
		self.selection_circle = [] # Prototype
		self.left_player = Player() # Prototype
		self.right_player = Player() # Prototype
		self.teams = collections.defaultdict(dict)
		self.field = Object()
		self.field_border = Object()
		self.goal = []
		self.ball = Ball()
		self.hud = HUD()
		self.goal_image = EffectObject()
		self.formation = {Team_side.LEFT: [1, 4, 3, 3], Team_side.RIGHT: [1, 4, 4, 2]}
		self.sound_list = dict()

		# Game config
		self.game_mode = Game_mode.PvP
		self.P1_controlled_team = Team_side.LEFT
		self.P1_controlled_position = 'midfielder'
		self.P2_controlled_team = Team_side.RIGHT
		self.P2_controlled_position = 'midfielder'

		# Load scene's resources
		self.read_scene(file_path)
Exemplo n.º 30
0
    def resetLevel(self):
        balls.clear()
        bonuses.clear()

        #bonuses.clear()
        if players[0].lives == 0 and players[1].lives == 0:
            return

        for x in range(self.previousBalls):
            temp = x + 2
            balls.append(Ball(self.startingBallSize))

            if x % 2 == 0:
                balls[x].x = int(balls[x].x) - 35 * temp
                balls[x].counter = int(balls[x].x)
                balls[x].forward = False
            elif x % 2 == 1:
                balls[x].x = int(balls[x].x) + 35 * temp
                balls[x].counter = int(balls[x].x)

        self.Weapon1 = False
        self.Weapon2 = False
        self.w1Y = PLAYER_HEIGTH
        self.w2Y = PLAYER_HEIGTH
        queue.put(Qt.Key_Minus)
Exemplo n.º 31
0
    def __init__(self):
        self.gun = Gun.Gun(gameDisplay)

        #creating ten balls for game, we can make it configurable later
        for i in range(1, self.ball_count):
            self.balls.append(
                Ball.RandomBall(gameDisplay, gc.screen_width, gc.screen_height,
                                ""))
Exemplo n.º 32
0
def init_all(score):
    right = Player.Player(True)
    left = Player.Player(False)
    parts = [right, left, Ball.Ball((right, left))]
    update_screen(score, parts)

    threads = [i.start_thread() for i in parts]
    return parts, threads
Exemplo n.º 33
0
 def __init__(self):
     self.gameStatus = MachineOfStates(
     )  # say a game status main, gameOPT, 1pvsCp, 1pvs2p
     self.configureGameStatus()
     # Balls
     self.ballTarget = ""  # Ball to Hit (white, yellow, red)
     self.ballWhite = Ball()
     self.ballYellow = Ball()
     self.ballRed = Ball()
     self.balls = [self.ballWhite, self.ballYellow,
                   self.ballRed]  # Array with all balls
     # Table
     self.SizeOfTable = 0  # Autoconfigure when the game is run >> L
     # Players
     self.target = Target(
     )  # This is a interface usert to hit the ball and configures
     self.Players = []
Exemplo n.º 34
0
 def __init__(self, parent1=None, parent2=None):
     #the neural net and ball agent of this agent
     self.net = Net.Net(parent1, parent2)
     self.ball = Ball.Ball()
     #random identifier to identify the agent for debug
     self.identifier = random.randint(0, 50)
     #true if the user won the game
     self.agentWon = False
Exemplo n.º 35
0
 def loadBallinContainer(number, my_canvas):
     """ creates object of Ball class, stores in a list and returns the list"""
     store_ball_objects = []
     for i in range(number):
         container_Height = 180
         ball = Ball(my_canvas, 20, container_Height - 20 * i, 20, 0, 0,
                     "white", ("ball", str(i)))
         store_ball_objects.append(ball)
     return store_ball_objects
Exemplo n.º 36
0
    def __init__ (self, parent):
        ##=====DATA RELEVANT TO BALL===============
        ##  We are going to repeatedly draw a ball object on the canvas,
        ##  "moving" it across the canvas.  The ball object is specified
        ## by (a) its x and y center coordinates (a tuple), (b) its radius,
        ##  (c) the delta x and delta y to move the ball in each time
        ## increment, and (d)  its color.
        
        colorList = ["blue", "red", "green", "yellow", "magenta", "orange"]
        self.ballobjs = []
        for i in range(10):
            xrand = random.randint(10, 390)
            yrand = random.randint(10, 390)
            dxrand = random.randint(-8, 8)
            dyrand = random.randint(-8, 8)
            radrand = random.randint(5, 10)
            randcolor = random.choice(colorList)
            self.ballobjs.append(Ball(xrand, yrand, dxrand, dyrand, radrand, randcolor))

        #========DATA NEEDED FOR ANIMATION=========
        #  Here is the time in milliseconds between consecutive instances
        #  of drawing the ball.  If this time is too small the ball will
        #  zip across the canvas in a blur.
        self.wait_time = 100 

        #this will allow us to stop moving the ball when the program quits
        self.isstopped = False 

        self.maxx = 400 # canvas width, in pixels
        self.maxy = 400 # canvas height, in pixels

        #=============CREATE THE NEEDED GUI ELEMENTS===========
        ##  Create a frame, attach a canvas and a button to this frame
        ##  Button is used to cleanly exit the program
        ##  Canvas, like an image, is an object that we can draw objects on.
        ##  This canvas is called chart_1.  
        ##  Parent = root window, contains a frame
        ##  The frame contains the canvas and the quit button.
        ##  We only care about the canvas in our animation
        self.parent = parent
        self.frame = Frame(parent)
        self.frame.pack()
        self.top_frame = Frame(self.frame)
        self.top_frame.pack(side=TOP)
        self.canvas = Canvas(self.top_frame, background="white", \
                             width=self.maxx, height=self.maxy )
        self.canvas.pack()
        self.bottom_frame = Frame(self.frame)
        self.bottom_frame.pack(side=BOTTOM)
        self.restart = Button(self.bottom_frame, text="Restart", command=self.restart)
        self.restart.pack(side=LEFT)
        self.slow = Button(self.bottom_frame, text="Slower", command=self.slower)
        self.slow.pack(side=LEFT)
        self.fast = Button(self.bottom_frame, text="Faster", command=self.faster)
        self.fast.pack(side=LEFT)
        self.quit = Button(self.bottom_frame, text="Quit", command=self.quit)
        self.quit.pack(side=RIGHT)
Exemplo n.º 37
0
 def __init__(self,message_handler,xsize,ysize,puff_fac=1.,damage_fac=1.):
     super(Pitch,self).__init__(message_handler)
     self.xsize=float(xsize)
     self.ysize=float(ysize)       
     self.ball=Ball(message_handler,self)
     self.moves=list()
     self.puff_fac=puff_fac
     self.damage_fac=damage_fac
     self.contacts=dict()
     self.game_time=0.
     # Add Helpers
     self.helpers=dict()
     self.helpers['AttackerDefenderPBeqs']=Helper.AttackerDefenderPBeqs()
Exemplo n.º 38
0
	def __init__(self):
		self.pic = Image(Point(500,250),"background.gif")
		width = self.pic.getWidth()
		height = self.pic.getHeight()

		self.pongWin = GraphWin("Pong", width, height)
		self.pic.draw(self.pongWin)

		#create an instance of the Ball Class
		self.ball = Ball(self.pongWin)

		#create an instance of the Paddle Class
		self.paddle = Paddle(self.pongWin)
Exemplo n.º 39
0
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        self.W = self.parent.winfo_screenwidth() - bbc.MIN_W
        self.H = self.parent.winfo_screenheight() - bbc.MIN_H
        if self.W < bbc.MIN_W:
            self.W = bbc.MIN_W
        if self.H < bbc.MIN_H:
            self.H = bbc.MIN_H

        self.board = Board(self)
        self.ball = Ball(self.board)
        self.barTop = Bar(self.board, bbc.BAR_T)
        self.barBottom = Bar(self.board, bbc.BAR_B)

        self.initialize()
Exemplo n.º 40
0
    def __init__(self):
        window = Tk()
        window.title("Pong") # Set a title

        # set callback routine when mouse is moved
        window.bind("<Motion>", self.callback)

        # establish the canvas
        self.__width = 400 # Width of the self.canvas
        self.__height = 400 # Width of the self.canvas
        self.__canvas = Canvas(window, bg = "white",
            width = self.__width, height = self.__height)
        self.__canvas.pack()
        self.__color="red"

        # create ball and paddle objects
        self.__ball = Ball(130,40,self.__color, self.__canvas, 30)
        self.__paddle = Paddle(380,380,"black", self.__canvas, 100, 20)

        # start the animation loop
        self.animate()
Exemplo n.º 41
0
class MyGame(object):
    
    def __init__(self):
        ###create
        self.numBaskets = 5
        #self.numAntiBaskets = 5
        self.gameScore = 0
        self.level = 1
        self.timeLeftSeconds = 112 #standard 112 seconds
        self.timeLeft = self.timeLeftSeconds
        self.timeLeftFill = 'yellow'
        self.tLFontSize = 14 #font size for time left
        self.cW = self.canvasWidth = 500
        self.cH = self.canvasHeight = 500
        
    def reInitialize(self):
        self.gameScore = 0
        self.level = 1
        self.timeLeft = self.timeLeftSeconds
        self.initBall()
        self.initBaskets()
        self.initialCollisionResponse()
        self.gameDone = False
        self.timerRunning = True
        self.decTime()
        
    def initBall(self):
        #initialize ball and let it know about data
        self.ball = Ball() #just ball works too?
        
    def initBaskets(self):    
        #basket list
        baskets = []
        numBaskets = self.numBaskets
        for i in xrange(numBaskets):
            baskets.append(Basket.Basket())
        self.baskets = baskets
        
    
    def drawBall(self):
        #middle of canvas, radius 10
        self.ball.drawBall(self.canvas)
        
    def moveBall(self):
        def almostEquals(x2,x1):
            epsilon = .001
            return abs(x2-x1) < epsilon
        
        if (self.ball.newCx!=None and self.ball.newCy!=None):
            if (not almostEquals(self.ball.newCx, self.ball.oCx)
                and not almostEquals(self.ball.newCy, self.ball.oCy)):
                self.ball.oCx+=self.ball.dx
                self.ball.oCy += self.ball.dy
        
    def drawBaskets(self):
        for basket in self.baskets:
            basket.drawBasket(self.canvas)
            
    def moveBaskets(self):
        '''This function also accounts for wall collision'''
        for basket in self.baskets:
            cx = basket.cx
            cy = basket.cy
            r = basket.basketR
            speed = basket.basketSpeed
            # don't want statinary baskets
            if (basket.dx == 0 and basket.dy == 0):
                (basket.dx, basket.dy) = (1,1)
            basket.cx+= speed*basket.dx
            basket.cy+= speed*basket.dy
            #WALL COLLISION
            if cx-r < 0:
                #in this case, w/e the value, make it +
                basket.dx = abs(basket.dx)
            elif cx+r > self.canvasWidth:
                #in this case, w/e the value, make it -
                basket.dx = -abs(basket.dx)
            if cy-r < 0:
                basket.dy = abs(basket.dy)
            elif cy+r > self.canvasHeight:
                basket.dy = -abs(basket.dy)
                
    def initialCollisionResponse(self):
        '''for any two colliding baskets, keep picking new location until
        there are no collisions'''
        cW = self.cW
        cH = self.cH
        baskets = self.baskets
        r = baskets[0].basketR
        for i in xrange (len(baskets)):
            for j in xrange(i):
                while (baskets[i].collidesWith(baskets[j])):
                    baskets[i].cx = random.randint(0+r,cW-r)
                    baskets[i].cy = random.randint(0+r,cH-r)
                    
    #def replaceCollision(self):
        
    def collisionResponse(self):
        baskets = self.baskets
        for i in xrange (len(baskets)):
            for j in xrange(i):
                if baskets[i].collidesWith(baskets[j]):
                    #move one basket back
                    baskets[i].cx -= baskets[i].dx
                    baskets[i].cy -= baskets[i].dy                
                    # move the other basket back
                    baskets[j].cx -= baskets[j].dx
                    baskets[j].cy -= baskets[j].dy  
                    ## reverse the dirs to sim collision
                    baskets[i].dx = -(baskets[i].dx)
                    baskets[j].dx = -(baskets[j].dx)
                    baskets[i].dy = -(baskets[i].dy)
                    baskets[j].dy = -(baskets[j].dy)              
                    
    def detectAScore(self):
        '''determines a score depending on how far ball's in basket'''
        self.amtBallNotInBasket = .4 #lower this multiplicator for less leniency
        baskets = self.baskets
        for basket in self.baskets:
            if self.ball.newCx!=None:
                centerDistance = math.sqrt((basket.cx-self.ball.newCx)**2
                    +(basket.cy-self.ball.newCy)**2)
                if centerDistance < self.amtBallNotInBasket * self.baskets[0].basketR:
                    if self.timerRunning == True:
                        self.gameScore+=1
                        self.highScore() #determine hs
                        time.sleep(.5)
                    return True
        return False #penalty in mousePressed function
                    
    def highScore(self):
        highScore = self.highestScore
        if self.gameScore > highScore:
            self.highestScore = self.gameScore
            
                    
    def updateLevel(self):
        if self.gameScore  > 4 and self.gameScore <= 9: #level 2 after 5 baskets
            self.level = 2 #Currently just for display
            for basket in self.baskets:
                basket.basketR = 48
                basket.basketSpeed = 7.0
        elif self.gameScore > 9 and self.gameScore <= 14:
            self.level = 3
            self.ball.ballSpeed = 3.0
            for basket in self.baskets:
                basket.basketR = 46
                basket.basketSpeed = 12.0
                
    def determineTimeOver(self):
        if self.timeLeft == 0:
            self.gameOver()
    
    def drawScoreAndLevel(self):
        hs = self.highestScore
        if self.timeLeft < 11: #show that time's running out
            self.timeLeftFill = 'red'
            self.tLFontSize = 22
        self.canvas.create_text(self.canvasWidth/2,15,text="Score: "+str(self.gameScore),
                           font=("Helvatica", 14, "bold"), fill='orange')
        self.canvas.create_text(self.canvasWidth/5,15,text="Level: "+str(self.level),
                            font=("Helvetica", 14, "bold"), fill='orange')
        self.canvas.create_text(self.canvasWidth*(4.0/5),15,text="High Score: "+str(hs),
                            font=("Helvetica", 14, "bold"),fill='orange')
        self.canvas.create_text(self.canvasWidth/2,40,text="Time left: "+str(self.timeLeft),
                           font=("Helvatica", self.tLFontSize, "bold"), fill=self.timeLeftFill)
        
    def mousePressed(self, event):
        if self.timerRunning:
            self.ball.newCx = event.x 
            self.ball.newCy = event.y 
            dx = self.ball.dx = (self.ball.newCx-self.ball.oCx)/self.ball.speed
            dy = self.ball.dy = (self.ball.newCy-self.ball.oCy)/self.ball.speed
            self.detectAScore()
        #if (not self.detectAScore()):
            #self.gameScore-=1
            
    def keyPressed(self, event):
        if event.keysym == "p":
            self.gameDone = False
            if self.timerRunning == True:
                self.timerRunning = False
                self.pausePlay = True
                self.redrawAll()
            else: #timer isn't running
                self.pausePlay = False
                self.timerRunning = True
                self.canvas.create_rectangle(0,0,
                    self.canvasWidth,self.canvasHeight, fill='dodger blue')
                self.drawBaskets()
                self.drawBall()
                self.decTime()
                self.drawScoreAndLevel()
        if event.keysym == "c": #change positions
            if self.timerRunning:
                for basket in self.baskets:
                    r = self.baskets[0].basketR 
                    basket.cx = random.randint(0+r,self.cW-r)
                    basket.cy = random.randint(0+r,self.cH-r)
                    self.initialCollisionResponse()
                    basket.dx = random.randint(-1,1)
                    basket.dy = random.randint(-1,1)
                    self.redrawAll()
        if event.keysym == "r":
            self.reInitialize()
            self.redrawAll()
        if event.keysym == "q":
            self.gameOver()
            
    def drawPausePlayScreen(self):
        self.gameDone = False
        self.canvas.create_rectangle(0,0,self.canvasWidth,self.canvasHeight,fill='dodger blue')
        self.canvas.create_image(250,250,image = self.resizeBkg2)
        self.canvas.create_text(self.canvasWidth/2,200,
                                text="Welcome to KozB-ball !\
                                \nIn-game: click a basket for +1.\
                                \nThere are 3 levels;\
                                \nPress 'p' to play then 'p' to pause,\
                                \n'r' to restart,\
                                \n'q' to quit,\nand for fun,\
                                \n'c' to change basket positions!\
                                \nYOU have 112 seconds to change the game.",
                                fill="black", font=("Helvatica", 14, "bold"))
            
    def decTime(self):
        if self.timerRunning == True:
            self.timeLeft-=1
            self.canvas.after(1000, self.decTime)
            
    def timerFired(self): #actually does my movement        
        if self.timerRunning == True:
            self.moveBaskets()
            self.moveBall()
            self.collisionResponse()
            self.updateLevel()
            self.redrawAll()
            self.determineTimeOver()
        self.canvas.after(self.timerFiredDelay, self.timerFired)
    
    def redrawAll(self): #called in run
        self.canvas.delete(ALL)           
        if self.timerRunning:
            self.drawGame()
        elif self.gameDone:
            self.gameOver()
        else:
            self.drawPausePlayScreen()
    
    def drawGame(self):
        self.canvas.create_rectangle(0,0,
                self.canvasWidth,self.canvasHeight, fill='dodger blue')
        self.drawBaskets()
        self.drawBall()
        self.drawScoreAndLevel()
            
    def gameOver(self):
        self.gameDone = True
        self.timerRunning = False
        hsList = self.hsList
        if (self.gameScore not in hsList and self.gameScore!=0):
            hsList.append(self.gameScore)
        hsList.sort()
        if (len(hsList) > 3):
            hsList.pop(0)
        if len(hsList)==0:
            hsList = [None]
        #draw the page
        self.canvas.create_image(self.canvasWidth/2, self.canvasHeight/2
                                 ,image=self.resizeBkg)
        self.canvas.create_text(self.canvasWidth/2,self.canvasHeight/3,
            text="KozB-ball is now over :(\nHere is a little list of the high scores\n\
                : "+str(hsList),fill='yellow',font=("Helvatica", 14, "bold"))
        self.timeLeft = self.timeLeftSeconds #don't forget to start it back up for next game
        
    #def startPage(self):
        
    def run(self):
        # create the root and the canvas
        root = Tk()
        width = self.canvasWidth
        height = self.canvasHeight
        self.canvas = Canvas(root, width=width, height=height)
        self.canvas.pack()
         # set up events
        def f(event):
            self.mousePressed(event)
            self.redrawAll()
        root.bind("<Button-1>", f)
        root.bind("<Key>", lambda event: self.keyPressed(event))
        ###images
        bkg = self.background = PhotoImage(file="screenOfBalls.gif")
        wH = self.wantHeight = bkg.height()
        wW = self.wantWidth = bkg.width()
        self.resizeBkg = bkg.subsample(wH/self.canvasHeight)
        bkg2 = self.background2 = PhotoImage(file="images-jpeg.gif")
        wH = self.wantHeight = bkg2.height()
        wW = self.wantWidth = bkg2.width()
        self.resizeBkg2 = bkg2.zoom(self.canvasHeight/wH)#,
        self.initBall()
        self.initBaskets()
        self.initialCollisionResponse()
        #SET UP TIMER FIRED
        self.timerFiredDelay = 20 # milliseconds
        #self.timerRunning = True #get timerFired running
        self.timerRunning = False
        self.gameDone = False
        self.canvas.create_rectangle(0,0,width,height,
                                     fill='dodger blue')
        self.drawPausePlayScreen()
        self.highestScore = 0
        self.hsList = []
        self.timerFired()
        # and launch the app
        root.mainloop()  # This call BLOCKS (so your program waits until you close the window!)
Exemplo n.º 42
0
import sys, pygame, math
from Ball import *
pygame.init()

clock = pygame.time.Clock()

width = 900 
height = 600
size = width, height

bgColor = r,g,b = 0, 0, 0

screen = pygame.display.set_mode(size)

ball1 = Ball("ball1.png", [4, 6])
ball2 = Ball("ball2.png", [2, 6], [200, 200])
ball3 = Ball("ball1.png", [6, 5], [400, 0])
ball4 = Ball("ball.png", [3, 6], [600, 0])
ball5 = Ball("ball1 .png", [4, 6], [800, 800])

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            sys.exit()
    
    ball1.move()
    ball1.collideScreen(size)
    
    ball2.move()
    ball2.collideScreen(size)
    
Exemplo n.º 43
0
class BingBall(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        self.W = self.parent.winfo_screenwidth() - bbc.MIN_W
        self.H = self.parent.winfo_screenheight() - bbc.MIN_H
        if self.W < bbc.MIN_W:
            self.W = bbc.MIN_W
        if self.H < bbc.MIN_H:
            self.H = bbc.MIN_H

        self.board = Board(self)
        self.ball = Ball(self.board)
        self.barTop = Bar(self.board, bbc.BAR_T)
        self.barBottom = Bar(self.board, bbc.BAR_B)

        self.initialize()

    def initialize(self):
        self.reset_score()
        self.parent.title("BingBall Game")
        self.parent.config(bg="#324b21")

        self.pack(side=RIGHT, padx=5, pady=5)

    def reset_score(self):
        bbc.BAR_SCORE_G = 0
        bbc.BAR_SCORE_R = 0

    def direct_bar_auto(self):
        if bbc.IS_AUTO is False:
            return 1
        fx, fy, lx, ly = self.ball.get_current_coords()
        if fy + self.H*bbc.SPEED[1] <= 0:
            self.barTop.do_moving(10 + fx + 2*bbc.SPEED[0])
        if ly + self.H*bbc.SPEED[1] >= self.H:
            self.barBottom.do_moving(lx + 2*bbc.SPEED[0] - 10)
        self.after(5, self.direct_bar_auto)

    def bar_top_event_left(self, event):
        self.barTop.to_move(bbc.DIRECT_TO_LEFT)

    def bar_top_event_right(self, event):
        self.barTop.to_move(bbc.DIRECT_TO_RIGHT)

    def bar_bottom_event_left(self, event):
        self.barBottom.to_move(bbc.DIRECT_TO_LEFT)

    def bar_bottom_event_right(self, event):
        self.barBottom.to_move(bbc.DIRECT_TO_RIGHT)

    def bar_top_event(self, event):
        self.barTop.do_moving(event.x)

    def play_event(self, event):
        if bbc.IS_PLAYING is True:
            bbc.IS_PLAYING = False
        else:
            bbc.IS_PLAYING = True
            self.play()

    def play(self):
        self.direct_bar_auto()
        self.ball.do_moving()

    def auto_play_event(self, event):
        if bbc.IS_PLAYING is False:
            if bbc.IS_AUTO is False:
                self.reset_score()
            bbc.IS_AUTO = True
            self.reset_event_switch()

    def manual_play_event(self, event):
        if bbc.IS_PLAYING is False:
            if bbc.IS_AUTO is True:
                self.reset_score()
            bbc.IS_AUTO = False
            self.reset_event_switch()

    def up_delay_event(self, event):
        if bbc.DELAY < MAX_DELAY:
            bbc.DELAY += 1

    def down_delay_event(self, event):
        if bbc.DELAY > MIN_DELAY:
            bbc.DELAY -= 1

    def main(self):
        self.parent.bind("<space>", self.play_event)
        self.parent.bind("<F1>", self.auto_play_event)
        self.parent.bind("<F2>", self.manual_play_event)
        self.parent.bind("<Up>", self.down_delay_event)
        self.parent.bind("<Down>", self.up_delay_event)
        self.reset_event_switch()
        self.play()

    def reset_event_switch(self):
        if bbc.IS_AUTO is True:
            self.parent.unbind("<Left>")
            self.parent.unbind("<Right>")
            self.parent.unbind("<a>")
            self.parent.unbind("<d>")
            self.board.unbind("<1>")
        else:
            self.parent.bind("<a>", self.bar_top_event_left)
            self.parent.bind("<d>", self.bar_top_event_right)
            self.parent.bind("<Left>", self.bar_bottom_event_left)
            self.parent.bind("<Right>", self.bar_bottom_event_right)
            self.board.bind("<1>", self.bar_top_event)
Exemplo n.º 44
0
class Pong:
    def __init__(self):
        window = Tk()
        window.title("Pong") # Set a title

        # set callback routine when mouse is moved
        window.bind("<Motion>", self.callback)

        # establish the canvas
        self.__width = 400 # Width of the self.canvas
        self.__height = 400 # Width of the self.canvas
        self.__canvas = Canvas(window, bg = "white",
            width = self.__width, height = self.__height)
        self.__canvas.pack()
        self.__color="red"

        # create ball and paddle objects
        self.__ball = Ball(130,40,self.__color, self.__canvas, 30)
        self.__paddle = Paddle(380,380,"black", self.__canvas, 100, 20)

        # start the animation loop
        self.animate()

    # callback method
    # when mouse is moved, get the x-position of the mouse
    # set it to be the paddle x position
    def callback(self, event):
        x = event.x
        self.__paddle.set_x(x)

    # animation
    def animate(self):
        score=0
        while True:

            self.__canvas.after(20) # Speed
            self.__canvas.update() # Update self.canvas


            # colision detection code will go here
            if self.__ball.get_going_up()==False and \
                self.__ball.get_x()+self.__ball.get_diameter()>self.__paddle.get_x() and \
                self.__ball.get_x()<self.__paddle.get_x() + self.__paddle.get_width() and \
                self.__ball.get_y()+self.__ball.get_diameter()>self.__paddle.get_y():
                self.__canvas.delete("gameOver")
                self.__ball.bounce_vertical()
                score += 1
                self.__canvas.create_text(250, 20, text = ("Scored "+str(score)), font=("Helvetica", 12, "bold"), fill = "red", tags = ("gameOver"))
                winsound.PlaySound('boing.wav',winsound.SND_ASYNC)

            if score % 2 == 0:
                self.__ball.set_color("blue")
            else:
                self.__ball.set_color("red")


            if self.__ball.get_y()+ self.__ball.get_diameter() == 400:
                self.__ball.set_speed(0)
                self.__canvas.delete("gameOver")
                self.__canvas.create_text(250, 20, text = ("Game Over! You scored "+str(score)), font=("Helvetica", 12, "bold"), fill = "red", tags = ("gameOver"))


            # move the ball and draw the objects
            self.__ball.move()
            self.__ball.draw()
            self.__paddle.draw()
Exemplo n.º 45
0
def test_move2():
    b = Ball(190,100,-10,18,25,'green')
    b.move()
    assert b.position() == (180,118) and b.get_color() == 'green'
Exemplo n.º 46
0
def Game(level, lives, score):
    
    try:
        x360 = pygame.joystick.Joystick(0)
        x360.init()
        joypad_status = True
    except pygame.error:
        pass
        joypad_status = False
        
    sys_name = os.path.join(sys.path[0], 'Pybreaker-images', 'ACTIONIS.TTF')        
    score_font = pygame.font.Font(sys_name, 35)
    
    sys_name = os.path.join(sys.path[0], 'Pybreaker-images', 'COOLFONT.ttf')
    upgrade_font = pygame.font.Font(sys_name, 60) 
    
    size = (800, 640)
    screen = pygame.display.set_mode(size)
    
    sys_name = os.path.join(sys.path[0], 'Pybreaker-images', 'Background.jpg')
    background = pygame.image.load(sys_name).convert()
    
    pygame.display.set_caption('PYBREAKER =D')
    
    upgrade_message = 0
    upgrade_check = 0
    death_check = 0
    laser_check = 0
    
    sys_name = os.path.join(sys.path[0], 'Pybreaker-sounds', 'Powerup.ogg')
    upgrade_sound = pygame.mixer.Sound(sys_name) 
    upgrade_sound.set_volume(0.5)
    
    sys_name = os.path.join(sys.path[0], 'Pybreaker-sounds', 'ThechnoTheme.mp3')
    pygame.mixer.music.load(sys_name)
    pygame.mixer.music.set_volume(0.15)
    pygame.mixer.music.play(10)
    
#########################Creation of Groups/Sprites#############################
    
    player1 = Paddle(lives, score)
    
    paddle = pygame.sprite.GroupSingle()
    paddle.add(player1)
    
    ball = Ball(player1.rect.centerx, (player1.rect.top - 24))
    ball.SPAWNSTATE = True
    
    ball_group = pygame.sprite.Group()
    ball_group.add(ball)
    
    upgrade_group = pygame.sprite.Group()
    
    laser_group = pygame.sprite.Group()
    
    text_group = pygame.sprite.Group()
    
    clock = pygame.time.Clock()
    keep_going = True
    
    time_passed = 0
    timer = 0
    sticky_timer = 0
    time_check = 1
    
    pygame.key.set_repeat(100)
    
#################################Level Importing########################
    
    brick_group = pygame.sprite.Group()
    
    brick_group = level_importer(level)
      
#################################Starting the Loop##############################
    
    score_label = Text(40, 603, 'Score: {0}      Lives: {1}' . format(player1.get_score(), player1.lives), (201, 192, 187), score_font)
    text_group.add(score_label)
    
    screen.blit(background, (0, 0))
    
    start = 1
    
    while keep_going:
        clock.tick(30)        
###############################Ball Spawn/Sticky States#########################
        
        if ball.SPAWNSTATE:
            ball.rect.centerx = player1.rect.centerx
            ball.rect.bottom = player1.rect.top
            if player1.STICKY:
                sticky_timer += clock.get_time() / (1000.0)
                if sticky_timer > 2.0:
                    ball.SPAWNSPEEDS()
                    ball.SPAWNSTATE = False
                    sticky_timer = 0
        
#######################COLLISION DETECTION & Handling###########################          
        
        #Temp Stored Collision Values
        if pygame.sprite.spritecollide(player1, ball_group, False):
            ball_list = pygame.sprite.spritecollide(player1, ball_group, False)
            for temp_ball in ball_list:
                if not temp_ball.SPAWNSTATE:
                    ball_paddle_collision(temp_ball, player1)
                if player1.STICKY:
                    temp_ball.dx, temp_ball.dy = 0,0
                    temp_ball.rect.bottom = player1.rect.top 
                    
                    temp_ball.SPAWNSTATE = True
        
        if pygame.sprite.groupcollide(ball_group, brick_group, False, False):
            ball_brick_dict = pygame.sprite.groupcollide(ball_group, brick_group, False, False)
            
            for ball, brick_list in ball_brick_dict.iteritems():
                ball_brick_collision(ball, brick_list[0])
                for brick in brick_list:
                    if brick.hit == 0:
                        brick_group.remove(brick)
                        temp_score = brick.get_score()
                        player1.add_score(temp_score)
                            
                        if brick.upgrade == 1:
                                
                            upgrade = Upgrade(brick.rect.centerx, brick.rect.centery)
                            upgrade_group.add(upgrade)
                            
                    elif brick.hit > 0:
                        brick.hit -= 1
            
        if pygame.sprite.spritecollide(player1, upgrade_group, False):
            temp_upgrade = pygame.sprite.spritecollide(player1, upgrade_group, True)
            screen.blit(background, (0,0))
            
            upgrade_sound.play()
            upgrade_check = 0
            upgrade_message = 1
            
            for upgrade_text in text_group:
                if upgrade_text != score_label:
                    text_group.remove(upgrade_text)
                    
            if temp_upgrade[0].number_upgrade != 1:
                player1.DOWNGRADE()
                
            if player1.paddle_size == -1:
                player1.DOWNGRADE()
                
            timer = 0 
            player1.laser_amount = 0
            player1.STICKY = False
                   
            if temp_upgrade[0].number_upgrade == 0:
                laser_check = 1
                
            if temp_upgrade[0].number_upgrade == 1 or temp_upgrade[0].number_upgrade == 2 or temp_upgrade[0].number_upgrade == 5:
                upgrade_check = 1
                
            if temp_upgrade[0].number_upgrade == 3:
                ball_group = MULTIBALL(ball_group)
                    
            temp_upgrade[0].sound.play()    
            decide_upgrade(player1, temp_upgrade[0], ball)
        
        if pygame.sprite.groupcollide(laser_group, brick_group, False, False):
            laser_brick_dict = pygame.sprite.groupcollide(laser_group, brick_group, False, False)
            for laser, brick_list in laser_brick_dict.iteritems():
                for brick in brick_list:
        
                    if brick.hit == 0:
                        
                        pygame.sprite.groupcollide(laser_group, brick_group, True, True)
                        temp_score = brick.get_score()
                        player1.add_score(temp_score)
                        
                        if brick.upgrade == 1:
                        
                            upgrade = Upgrade(brick.rect.centerx, brick.rect.centery)
                            upgrade_group.add(upgrade)
                        
                    elif brick.hit > 0:
                        
                        pygame.sprite.groupcollide(laser_group, brick_group, True, False)
                        brick.hit -= 1
                          
##################################DEALING WITH UPGRADES#########################
        
        if upgrade_message == 1:
            time_passed += clock.get_time() / (1000.0)
            if len(temp_upgrade) > 0:
                
                if temp_upgrade[0].number_upgrade == 0:
                    upgrade_label = Text(10, 300, 'ZOMG LOLZ YOU GOT THE LAZAWRS!', (199, 211, 235), upgrade_font)
                    
                    laser_label = Text(400, 603,'Laser: {0}' .format(player1.laser_amount), (201, 192, 187), score_font)
                    text_group.add(laser_label)
                    
                elif temp_upgrade[0].number_upgrade == 1:
                    upgrade_label = Text(250, 300, 'SUPER PADDLE!', (199, 211, 235), upgrade_font)
                    
                    time_label = Text(400, 603,'Upgrade Time Left: 15', (201, 192, 187), score_font)
                    text_group.add(time_label)
                
                elif temp_upgrade[0].number_upgrade == 2:
                    upgrade_label = Text(250, 300, 'SHRINK PADDLE!', (199, 211, 235), upgrade_font)
                    
                    time_label = Text(400, 603,'Upgrade Time Left: 15', (201, 192, 187), score_font)
                    text_group.add(time_label)
                    
                elif temp_upgrade[0].number_upgrade == 3:
                    upgrade_label = Text(75, 300, 'MULTIBALL!        MULTIBALL!', (199, 211, 235), upgrade_font)
                
                elif temp_upgrade[0].number_upgrade == 4:
                    upgrade_label = Text(395, 300, '1up!', (199, 211, 235), upgrade_font)
                
                elif temp_upgrade[0].number_upgrade == 5:
                    upgrade_label = Text(280, 300, 'STICKY BALL!', (199, 211, 235), upgrade_font)
                    
                    time_label = Text(400, 603,'Sticky Time Left: 25', (201, 192, 187), score_font)
                    text_group.add(time_label)
                    
                text_group.add(upgrade_label)
                for upgrade in temp_upgrade:
                    temp_upgrade.remove(upgrade)
            if time_passed > 2.0:
                
                text_group.remove(upgrade_label)
                upgrade_message = 0
                time_passed = 0
                
        if upgrade_check == 1:
            timer += clock.get_time() / (1000.0)
                
            if int(timer) > 14 and not player1.STICKY:
                player1.DOWNGRADE()
                text_group.remove(time_label)
                upgrade_check = 0
                timer = 0
                
            elif int(timer) > 20:
                player1.STICKY = False
                timer = 0
                text_group.remove(time_label)
                upgrade_check = 0
                     
        if laser_check == 1:
            if player1.laser_amount == 0:
                laser_check = 0
                text_group.remove(laser_label)
                
#################################EVENTS#########################################
        
        key_list = pygame.key.get_pressed()
        
        if joypad_status:
            xaxis = x360.get_axis(0)
        
            if xaxis > 0.5 and (int(xaxis) + 1) == 1:
                player1.move_paddle(7)
            elif int(xaxis) == -1:
                player1.move_paddle(-7)
    
        if key_list[K_RIGHT] == 1:
            player1.move_paddle(7)
        elif key_list[K_LEFT] == 1:
            player1.move_paddle(-7)
        
        for ev in pygame.event.get():
            
            if ev.type == pygame.JOYBUTTONDOWN:
                if ev.button == 0:
                    if player1.get_laser_amount() > 0:
                        spawnandshoot(player1, laser_group)
                    if ball.SPAWNSTATE or player1.STICKY:
                        ball.SPAWNSPEEDS()
                        ball.SPAWNSTATE = False
            
            if ev.type == pygame.KEYDOWN:
                 
                if ev.key == pygame.K_ESCAPE:
                    keep_going = False
                    return False, player1.lives, player1.score
                
                if ev.key == pygame.K_SPACE:
                    if player1.get_laser_amount() > 0:
                        spawnandshoot(player1, laser_group)
                    if ball.SPAWNSTATE or player1.STICKY:
                        ball.SPAWNSPEEDS()
                        ball.SPAWNSTATE = False
                    
            if ev.type == pygame.QUIT:
                keep_going = False
                return False, player1.lives, player1.score
                       
##############################EXTRANEOUS SPRITES################################      
    
    #I was having Laser's 'pop' up from the bottom of the screen, obviously when the integer value;
    #for their 'rect.centery' was guetting too small and so became positive (silly Python), so I had to;
    #come up with this code to correct the issue...kinda detracts from efficiency, but still necessary
    
        if len(laser_group) > 0:
            for laser in laser_group:
                if laser.rect.centery < 0:
                    laser_group.remove(laser)
                
        if len(ball_group) > 0:
            for ball in ball_group:
                if ball.rect.centery > 600:
                    if len(ball_group) == 1:
                        
    #'DEATH' CALCULATIONS
                        timer = 0
                        player1.lives -= 1                    
                        player1.DOWNGRADE()
                        player1.STICKY = False
                        screen.blit(background, (0, 0))
                        'Clearing Extraneous Upgrades'
                        player1.laser_amount = 0
                        upgrade_check = 0
                        death_check = 1
                        for upgrade_text in text_group:
                            if upgrade_text != score_label:
                                text_group.remove(upgrade_text)
                        if player1.lives > 0:
                            time_label = Text(400, 603,'Time Until Next Life: 3', (201, 192, 187), score_font)
                            text_group.add(time_label)
                        
                    ball_group.remove(ball)
                    
        if len(ball_group) > 0:
            for upgrade in upgrade_group:
                if upgrade.rect.centery > 640:
                    upgrade_group.remove(upgrade)
                    
#####################################DEATH & COMPLETION#########################
        
        if len(ball_group) == 0:
            if death_check == 0:
                ball = Ball(player1.rect.centerx, (player1.rect.centery))
                ball.SPAWNSTATE = True
                ball_group.add(ball)
        
        if len(brick_group) == 0:
            timer += clock.get_time() / (1000.0)
            if timer < 3.0:
                new_level_label = upgrade_font.render('LEVEL {0} COMPLETED! =D' .format(level), True, (201, 192, 187))
                screen.blit(new_level_label, (150, 300))
                
            elif timer > 3.0 and level == 10:
                keep_going = False
                Menu.HighScores(player1.score)
                return False, player1.lives, player1.score
            
            elif timer > 3.0 and level != 10:
                keep_going = False
                return True, player1.lives, player1.score
            
        if death_check == 1 and player1.lives == 0:
            timer += clock.get_time() / (1000.0)
            if timer < 3.0:
                gameover_label = upgrade_font.render('GAME OVER! Try again next time!', True, (201, 192, 187))
                screen.blit(gameover_label, (15, 300))
            else:
                keep_going = False
                Menu.HighScores(player1.score)
                return False, player1.lives, player1.score
        
        if death_check == 1 and player1.lives > 0:
            timer += clock.get_time() / (1000.0)
            upgrade_group.empty()
            if timer > 3.0:
                ball_group.remove(ball)
                timer = 0
                death_check = 0
                text_group.remove(time_label)

####################################LABEL UPDATING##############################
       
        score_label.message = 'Score: {0}      Lives: {1}' .format(player1.get_score(), player1.lives)
        
        if player1.laser_amount > 0:
            laser_label.message = 'Laser: {0}' .format(player1.laser_amount)
            
        if player1.paddle_size != 0:
            if timer < 15 and timer > 0.0:
                time = (15 - int(timer))
                time_label.message = 'Upgrade Time Left: {0}' .format(time)
        if player1.STICKY:
            if timer < 30 and timer > 0.0:
                time = (20 - int(timer))
                time_label.message = 'Sticky Time Left: {0}' .format(time)
        if death_check == 1 and player1.lives > 0:
            if timer < 3 and timer > 0.0:
                time = (3 - int(timer))
                time_label.message = 'Time Until Next Life: {0}' .format(time)
                
######################################UPDATES###################################
        
        text_group.clear(screen, background)
        text_group.update()
        text_group.draw(screen)
        
        paddle.clear(screen, background)
        paddle.update()
        paddle.draw(screen)
        
        ball_group.clear(screen, background)
        ball_group.update()
        ball_group.draw(screen)
        
        brick_group.clear(screen, background)
        brick_group.update()
        brick_group.draw(screen)
        
        upgrade_group.clear(screen, background)
        upgrade_group.update()
        upgrade_group.draw(screen)
        
        laser_group.clear(screen, background)
        laser_group.update()
        laser_group.draw(screen)
        
        pygame.display.flip()
Exemplo n.º 47
0
class Pitch(Entity):
    """
    Manager class holding both teams and the ball. Runs the game.
    """
    def __init__(self,message_handler,xsize,ysize,puff_fac=1.,damage_fac=1.):
        super(Pitch,self).__init__(message_handler)
        self.xsize=float(xsize)
        self.ysize=float(ysize)       
        self.ball=Ball(message_handler,self)
        self.moves=list()
        self.puff_fac=puff_fac
        self.damage_fac=damage_fac
        self.contacts=dict()
        self.game_time=0.
        # Add Helpers
        self.helpers=dict()
        self.helpers['AttackerDefenderPBeqs']=Helper.AttackerDefenderPBeqs()

    def register_teams(self,home,away):
        self.register(home)
        self.register(away)
        self.home=home
        self.away=away
        home.pitch=self
        away.pitch=self
        home.opposite_team=away
        away.opposite_team=home
        self.players=dict()
        for p in home.players.values():
            self.players[p.uid]=p
        for p in away.players.values():
            self.players[p.uid]=p
        # Register teams and players to the Ball
        self.ball.register(self.home)
        self.ball.register(self.away)
        for p in away.players.values():
            self.ball.register(p)
        for p in home.players.values():
            self.ball.register(p)

    def setup(self):
        self.ball.broadcast('setup',delay=-1)
        self.ball.broadcast('ball_loose',delay=-1)
        self.message_handler.clear()        
        self.ball.setup()
        self.contacts.clear()

    def run_game(self,game_length,dt=0.1,display=True):
        " Run the game "
        self.display=display
        self.dt=dt
        # Setup move storage
        self.player_header=dict()
        for p in self.home.players.values():
            self.player_header[p.uid]=make_player_dict(1,'null')
        for p in self.away.players.values():
            self.player_header[p.uid]=make_player_dict(-1,'null')            
        # Add ball to player_header
        self.player_header[self.ball.uid]=make_player_dict(0,'null')
        # Init player states using a ball state broadcast
        self.setup()
        if display:
            fig1=plt.figure()
            plt.xlim([0,self.xsize])
            plt.ylim([0,self.ysize])
            self.plots=list()
            for p in self.home.players.values():
                plot_now, = plt.plot([], [], 'ro',markersize=15)
                self.plots.append(plot_now)
            for p in self.away.players.values():
                plot_now, = plt.plot([], [], 'bo',markersize=15)
                self.plots.append(plot_now)
            plot_now, =  plt.plot([],[],'go')
            self.plots.append(plot_now)
        # Run it
        self.game_time=0.
        while self.game_time < game_length:
            # Add time FIRST, since tick() will get state to end of this interval (not start).
            self.game_time += self.dt           
            self.tick()
            if self.check_scoring():
                self.setup()
        # Dump to JSON
        jfile = "/home/matt/src/smash/games/test_header.js"
        with open(jfile,'w') as f:
            f.write(json.dumps(self.player_header))
        jfile = "/home/matt/src/smash/games/test.js"
        with open(jfile,'w') as f:
            f.write(json.dumps(self.moves))        
        if display:
            line_ani = animation.FuncAnimation(fig1,self.frame_display,self.frame_data,interval=20,blit=False,repeat=True)
            plt.show()
            
    def tick(self):
        """
        Iterate one tick.
        """
        # Process any pending messages
        self.message_handler.process()
        # Stand prone players up
        for p in self.players.values():
            p.standup()
        # Team state resolve
        self.home.state.execute()
        self.away.state.execute()
        # Move all players
        for p in self.players.values():
            p.state.execute()
            p.move()
        self.resolve_pushes()     
        self.detect_collisions()
        self.resolve_collisions()
        self.ball.move()
        # Store moves
        tick_moves=list()
        for p in self.players.values():
            add_move=make_move_dict(p.uid,p.pos.x,p.pos.y,0.,p.has_ball,int(p.standing))
            tick_moves.append(add_move)
        # Ball position
        ball_carried = self.ball.carrier != None
        add_move=make_move_dict(self.ball.uid,self.ball.pos.x,self.ball.pos.y,0,ball_carried,0)
        tick_moves.append(add_move)
        #
        self.moves.append(tick_moves)
        # Display results
        if self.display:
            self.frame_display(tick_moves)
            plt.show(block=False)
    
    def check_scoring(self):
        # Magic numbers
        end_zone_size=2.
        if self.ball.carrier == None:
            return False
        else:
            if self.ball.pos.x < end_zone_size or self.ball.pos.x > (self.xsize - end_zone_size):
                return True
            else:
                return False


    def detect_collisions(self):
        self.collisions=list()
        for this,that in itertools.combinations(self.players.values(),2):
            if not (this.standing and that.standing):
                # Prone players can be run over
                continue
            if this.in_contact and that in self.contacts[this]:
                # Don't resolve a collision for players already in contact
                continue
            else:
                if (this.pos - that.pos).mag2() - (this.size + that.size)**2 < 0:
                    # collision occured
                    collision = this, that
                    self.collisions.append(collision)

    def resolve_collisions(self):
        # NOTE: magic numbers. Where to set them?
        loser_down_diff = 0.2
        knock_down_time = 3.0 # in seconds
        loser_down_damage = 5.
        loser_up_damage = 2.
        vdiff_zero=3.
        max_post_speed = 5.
        for c in self.collisions:
            this, that = c
            if this.team == that.team:
                # NOTE: For now, ignore friendly collisions.
                continue
            else:
                # Opposing team players. Game on.
                # Find elasticity factor, runs from [0,1]
                elasticity= (this.vel.angle_factor(that.vel)+1)/2.
                this_vel_norm = this.vel.norm()
                that_vel_norm = that.vel.norm()
                # Find the direction each player will exert an extra push (directly at opponent)
                this_force_dir = (this_vel_norm - that_vel_norm).norm()
                that_force_dir = this_force_dir * -1
                # Compute initial momentum, including additional pushes along opponents bearing
                this_push=this_force_dir * this.strength * this.block_skill * random.random()
                that_push=that_force_dir * that.strength * that.block_skill * random.random()
                this_pi = this.vel * this.mass
                that_pi = that.vel * that.mass
                # Cap total push magnitude by total momentum magnitude
                p_mag = this_pi.mag() + that_pi.mag()
                push_mag = this_push.mag() + that_push.mag()
                if push_mag > p_mag:
                    this_push *= p_mag/push_mag
                    that_push *= p_mag/push_mag
                p_ini_this = this_pi + this_push
                p_ini_that = that_pi + that_push
                p_total = p_ini_this + p_ini_that
                # Whose velocity is most aligned with the total momentum? This guy has 'won' the collision.
                this_dir_fac = this.vel.angle_factor(p_total)+1
                that_dir_fac = that.vel.angle_factor(p_total)+1
                # Largest factor wins
                if this_dir_fac > that_dir_fac:
                    loser=that
                    winner=this
                    dir_fac_ratio=this_dir_fac/that_dir_fac
                else:
                    loser=this
                    winner=that
                    dir_fac_ratio=that_dir_fac/this_dir_fac
                # Determine fate of loser
                # NOTE: Chance to apply skills here
                # Damage?
                # NOTE: Very simple for now, look to uses KE lost as damage done (and use skills...)
                loser_down=compare_roll(dir_fac_ratio,loser_down_diff)
                if loser_down == -1:
                    loser.prone = knock_down_time
                    loser.health -= loser_down_damage
                else:
                    loser.health -= loser_up_damage
                # Final velocities, use elasticity
                # Find the impulse for the two extreme versions of the collision
                vfinal_inelastic = p_total/(this.mass + that.mass)
                this_inelastic_impulse = vfinal_inelastic * this.mass - p_ini_this
                that_inelastic_impulse = vfinal_inelastic * that.mass - p_ini_that
                # Elastic collision is twice impulse of an inelastic one.
                this_impulse = this_inelastic_impulse * (1.+elasticity)
                that_impulse = that_inelastic_impulse * (1.+elasticity)
                # Find final velcotiies and update
                this.vel = ((p_ini_this + this_impulse)/this.mass).truncate(max_post_speed)
                that.vel = ((p_ini_that + that_impulse)/that.mass).truncate(max_post_speed)
                # If final velocities small enough, lock players in a tussle (if both still standing)
                if loser_down != -1:
                    v_diff = (this.vel - that.vel).mag()
                    if v_diff < vdiff_zero:
                        # NOTE: IS THIS SILLY? STOPPING BOTH COMPLETELY?
                        loser.vel = Vector(0,0)
                        winner.vel = Vector(0,0)
                        self.add_contact(this,that)
    
    def resolve_pushes(self):
        # NOTE: Very simplistic, doesn't take into account angle between players, so will look weird.
        # Assumes we can have double or triple teams, but not day 2v2, so we need to prevent that elsewhere.
        # NOTE: Not losing puff for pushing, need to change that!
        # NOTE: Down chance not a comparison of skill, should be
        # Magic numbers
        down_rate = 0.2 # prob per second
        down_damage = 5.
        down_time = 3.
        clist=list()
        # Generate one push per contact player
        for p in self.players.values():
            if not p.in_contact: continue
            p.my_push = Vector( random.random() * p.strength * p.direction,0)
            p.all_pushes = [p.my_push]
            clist.append(p)
        if len(clist) == 0: return
        # Apply pushes to opponents
        for p in clist:
            # Normalise push by number of opponents
            norm = len(self.contacts[p])
            for opp in self.contacts[p]:
                opp.all_pushes.append(p.my_push / norm)
        # Sum pushes for each player and apply resultant acceleration
        for p in clist:
            acc = np.array(p.all_pushes).sum()
            temp_vel = acc * self.dt
            p.pos += temp_vel * self.dt
            # Roll for down
            # NOTE: I don't think this is correct Poisson stats!
            if random.random() < (down_rate*self.dt):
                p.prone = down_time
                p.health -= down_damage 

    def add_contact(self,a,b):
        """
        Registers that two standing players are now in a contact contest.
        """
        if not self.contacts.has_key(a):
            self.contacts[a]=set()
        self.contacts[a].add(b)
 
        if not self.contacts.has_key(b):
            self.contacts[b]=set()
        self.contacts[b].add(a)

    def remove_contact(self,a,b):
        """
        Removes the two players from the list of current contests.
        """
        self.contacts[a].discard(b)
        if len(self.contacts[a]) == 0:
            self.contacts.pop(a)
        
        self.contacts[b].discard(a)
        if len(self.contacts[b]) == 0:
            self.contacts.pop(b)            

    def remove_all_contact(self,p):
        """
        Removes the player from all contests.
        """
        # Take this player of all opponents lists
        opps = self.contacts[p]
        for opp in opps:
            self.contacts[opp].discard(p)
            if len(self.contacts[opp]) == 0:
                self.contacts.pop(opp)
        # Remove the record for this player
        self.contacts.pop(p)

    def frame_data(self):
        nticks=len(self.moves)
        iframe=0
        while iframe < nticks:
            moves=self.moves[iframe]
            iframe = iframe + 1
            yield moves

    def frame_display(self,frame_data):
        for move, p in zip(frame_data,self.plots):
            if move['state'] == 0:
                shape='v'
            else:
                shape='o'

            if self.player_header[move['uid']]['team'] == 1:
                col='r'
            elif self.player_header[move['uid']]['team'] == -1:
                col='b'
            else:
                col='g'
                shape='o'
            p.set_data(move['x'],move['y'])
            p.set_marker(shape)
            p.set_color(col)
Exemplo n.º 48
0
def test_bounce2():
    b = Ball(190,100,-10,18,25,'green')
    b.move()
    b.check_and_reverse(300,118)
    assert b.dy == -18 and b.dx == -10
Exemplo n.º 49
0
def test_bounce1():
    b = Ball(10,100,-10,18,25,'green')
    b.move()
    b.check_and_reverse(200,200)
    assert b.dx == 10 and b.dy == 18
Exemplo n.º 50
0
def test_inside2():
    b = Ball(190,100,-10,18,25,'green')
    assert not b.some_inside(164,190)
Exemplo n.º 51
0
def test_inside1():
    b = Ball(190,100,-10,18,25,'green')
    assert b.some_inside(170,90)
Exemplo n.º 52
0
def test_box1():
    b = Ball(190,100,-10,18,25,'green')
    assert b.bounding_box() == (165,75,215,125)
Exemplo n.º 53
0
class Scene(State):
	def __init__(self, file_path):
		super(Scene, self).__init__()

		pygame.mixer.init(44100, -16, 4, 2048)
		self.position = ['goalkeeper', 'defender', 'midfielder', 'attacker']
		self.all_object_list = pygame.sprite.LayeredUpdates()
		self.selection_circle = [] # Prototype
		self.left_player = Player() # Prototype
		self.right_player = Player() # Prototype
		self.teams = collections.defaultdict(dict)
		self.field = Object()
		self.field_border = Object()
		self.goal = []
		self.ball = Ball()
		self.hud = HUD()
		self.goal_image = EffectObject()
		self.formation = {Team_side.LEFT: [1, 4, 3, 3], Team_side.RIGHT: [1, 4, 4, 2]}
		self.sound_list = dict()

		# Game config
		self.game_mode = Game_mode.PvP
		self.P1_controlled_team = Team_side.LEFT
		self.P1_controlled_position = 'midfielder'
		self.P2_controlled_team = Team_side.RIGHT
		self.P2_controlled_position = 'midfielder'

		# Load scene's resources
		self.read_scene(file_path)

	def init(self):
		# Set teams info
		# Left team
		self.game_mode = self.get_shared_var('mode')
		self.formation[self.P1_controlled_team] = self.get_shared_var('P1_formation')
		team1_id = self.get_shared_var('P1_team_ID')
		self.hud.set_left_team_name(Team_name[team1_id])
		self.left_player.setImage(ResourceManager.instance().image_path_list[56 + team1_id])

		# Right team
		self.formation[self.P2_controlled_team] = self.get_shared_var('P2_formation')
		team2_id = self.get_shared_var('P2_team_ID')
		self.hud.set_right_team_name(Team_name[team2_id])
		self.right_player.setImage(ResourceManager.instance().image_path_list[56 + team2_id])
		
		# Calculate players and ball position
		self.calculate_position()

		# Set controlled team
		self.controlled_team = Team_side.LEFT

		# Randomize ball direction
		self.ball.set_angle(random.randrange(0, 360, 20))

		# Game control
		self.game_over = False
		self.match_state = Match_state.KICKOFF
		self.match_time = 120000
		self.time = self.match_time

		# Reset score
		self.hud.reset_score()

		# Set background music
		pygame.mixer.stop()
		self.sound_list['background'].play().set_endevent(pygame.constants.USEREVENT)

	def process_key_press(self, key):
		if key[pygame.K_w]:
			apply_all(self.teams[self.P1_controlled_team][self.P1_controlled_position], 'move_up')
		if key[pygame.K_s]:
			apply_all(self.teams[self.P1_controlled_team][self.P1_controlled_position], 'move_down')
		if key[pygame.K_UP]:
			apply_all(self.teams[self.P2_controlled_team][self.P2_controlled_position], 'move_up')
		if key[pygame.K_DOWN]:
			apply_all(self.teams[self.P2_controlled_team][self.P2_controlled_position], 'move_down')

	def process_events(self, event):
		if event.type == pygame.USEREVENT:
			self.sound_list['background'].play()
		elif event.type == pygame.MOUSEBUTTONDOWN:
			return ''
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_ESCAPE:
				if self.is_running:
					self.pause()
				else:
					self.resume()
			elif event.key == pygame.K_a:
				apply_all(self.teams[self.P1_controlled_team][self.P1_controlled_position], 'stop')
				self.P1_controlled_position = self.position[max(0, self.position.index(self.P1_controlled_position) - 1)]
			elif event.key == pygame.K_d:
				apply_all(self.teams[self.P1_controlled_team][self.P1_controlled_position], 'stop')
				self.P1_controlled_position = self.position[min(3, self.position.index(self.P1_controlled_position) + 1)]
			elif event.key == pygame.K_LEFT:
				apply_all(self.teams[self.P2_controlled_team][self.P2_controlled_position], 'stop')
				self.P2_controlled_position = self.position[min(3, self.position.index(self.P2_controlled_position) + 1)]
			elif event.key == pygame.K_RIGHT:
				apply_all(self.teams[self.P2_controlled_team][self.P2_controlled_position], 'stop')
				self.P2_controlled_position = self.position[max(0, self.position.index(self.P2_controlled_position) - 1)]
		elif event.type == pygame.KEYUP:
			if event.key == pygame.K_w or event.key == pygame.K_s:
				apply_all(self.teams[self.P1_controlled_team][self.P1_controlled_position], 'stop')
			elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
				if self.game_mode is Game_mode.PvP:
					apply_all(self.teams[self.P2_controlled_team][self.P2_controlled_position], 'stop')

	def update(self):
		if (not self.is_running):
			return

		if self.match_state == Match_state.KICKOFF:
			self.sound_list['whistle'].play()
			pygame.time.delay(1500)
			self.match_state = Match_state.PLAYING
		elif self.match_state == Match_state.PLAYING:
			# Logic processing
			self.time -= 1000 / 60

			if self.time <= 0.0:
				self.match_state = Match_state.KICKOFF
				self.reset_game()

			self.hud.set_time(int(self.time))

			self.process_ball()
		elif self.match_state == Match_state.GOAL:
			goal_image = self.goal_image.clone()
			goal_image.set_appear_time(500)
			goal_image.show()
			self.all_object_list.add(goal_image)
			self.match_state = Match_state.KICKOFF
			self.reset_game()

		# Update all objects
		self.all_object_list.update()
		self.hud.update()

	def draw(self, screen):
		screen.fill(BLACK)
		self.all_object_list.draw(screen)
		apply_all(self.teams[self.P1_controlled_team][self.P1_controlled_position], 'show_selection_circle', screen)

		if self.game_mode is Game_mode.PvP:
			apply_all(self.teams[self.P2_controlled_team][self.P2_controlled_position], 'show_selection_circle', screen)

		self.hud.draw(screen)

	def reset_game(self):
		self.calculate_position()
		self.match_state = Match_state.KICKOFF

	#--------------------------------------LOGIC PROCESSING SECTION-----------------------------------------------
	def process_ball(self):
		# Check if hit goals
		if (pygame.sprite.collide_mask(self.ball, self.goal[0])) is not None:
			self.sound_list['goal'].play()
			self.hud.update_right_score()
			self.match_state = Match_state.GOAL
			return
		elif pygame.sprite.collide_mask(self.ball, self.goal[1]) is not None:
			self.sound_list['goal'].play()
			self.hud.update_left_score()
			self.match_state = Match_state.GOAL
			return

		# Check if hit field's border
		self.process_collide_border()

		# Check if hit players 
		player_list = [players for sublist in (list(self.teams[Team_side.LEFT].values()) + list(self.teams[Team_side.RIGHT].values())) for players in sublist]
		hit_player = pygame.sprite.spritecollideany(self.ball, player_list, pygame.sprite.collide_circle)

		if hit_player is not None:
			self.sound_list['ball_kick'].play()
			self.ball.collide_object(hit_player)

		# Process AI list(chain(*self.teams[Team_side.LEFT].values()))
		"""for position in self.teams[Team_side.RIGHT].keys():
			action = 'move_up' if random.randrange(0, 2) is 0 else 'move_down'
			apply_all(self.teams[Team_side.RIGHT][position], action)"""

	def process_collide_border(self):
		"""Check if ball touch field's border and calculate rebound direction
		"""
		ball_pos = self.ball.get_pos()

		if ball_pos[0] < 50:
			self.ball.move_to(51, self.ball.get_pos()[1])
			self.ball.toggle_x_vel()
		elif  (ball_pos[0] + self.ball.get_width()) > SCREEN_WIDTH - 50:
			self.ball.move_to(SCREEN_WIDTH - 51 - self.ball.get_width(), self.ball.get_pos()[1])
			self.ball.toggle_x_vel()
		elif ball_pos[1] < 20:
			self.ball.move_to(self.ball.get_pos()[0], 21)
			self.ball.toggle_y_vel()
		elif (ball_pos[1] + self.ball.get_height()) > SCREEN_HEIGHT - 20:
			self.ball.move_to(self.ball.get_pos()[0], SCREEN_HEIGHT - 21 - self.ball.get_height())
			self.ball.toggle_y_vel()

	def calculate_position(self):
		"""Calculate and move ball and players to the right position
		"""

		# Calculate ball postion
		x = (SCREEN_WIDTH - self.ball.get_width()) // 2
		y = (SCREEN_HEIGHT - 8 - self.ball.get_height()) // 2
		self.ball.move_to(x, y)

		# Generate and calculate red team players
		for i in range(len(self.formation[Team_side.LEFT])):
			if len(self.teams[Team_side.LEFT]) == 4:
				apply_all(self.teams[Team_side.LEFT][self.position[i]], 'kill')

			self.teams[Team_side.LEFT].update({self.position[i]: []})

			# Calculate offset
			x_offset = 100
			y_offset = (self.field.get_height() - 8 - self.left_player.get_height() * self.formation[Team_side.LEFT][i]) // (self.formation[Team_side.LEFT][i] + 1)

			for j in range(self.formation[Team_side.LEFT][i]):
				# Calculate position
				x = self.left_player.get_pos()[0] + (x_offset * (i ** 1.69))
				y = y_offset * (j + 1) + self.left_player.get_height() * j + 4

				self.teams[Team_side.LEFT][self.position[i]].append(self.left_player.clone())
				self.teams[Team_side.LEFT][self.position[i]][j].move_to(x, y)
				self.teams[Team_side.LEFT][self.position[i]][-1].set_layer(1)
				self.teams[Team_side.LEFT][self.position[i]][-1].set_radius()
				self.teams[Team_side.LEFT][self.position[i]][j].set_max_offset(y_offset - 20)
				self.all_object_list.add(self.teams[Team_side.LEFT][self.position[i]][-1])

		# Generate and calculate blue team players
		for i in range(len(self.formation[Team_side.RIGHT])):
			if len(self.teams[Team_side.RIGHT]) == 4:
				apply_all(self.teams[Team_side.RIGHT][self.position[i]], 'kill')

			self.teams[Team_side.RIGHT].update({self.position[i]: []})

			# Calculate offset
			x_offset = 100
			y_offset = (self.field.get_height() - 8 - self.right_player.get_height() * self.formation[Team_side.RIGHT][i]) // (self.formation[Team_side.RIGHT][i] + 1)

			for j in range(self.formation[Team_side.RIGHT][i]):
				# Calculate position
				x = self.right_player.get_pos()[0] - (x_offset * (i ** 1.69))
				y = y_offset * (j + 1) + self.right_player.get_height() * j + 4

				self.teams[Team_side.RIGHT][self.position[i]].append(self.right_player.clone())
				self.teams[Team_side.RIGHT][self.position[i]][j].move_to(x, y)
				self.teams[Team_side.RIGHT][self.position[i]][-1].set_layer(1)
				self.teams[Team_side.RIGHT][self.position[i]][-1].set_radius()
				self.teams[Team_side.RIGHT][self.position[i]][j].set_max_offset(y_offset - 20)
				self.all_object_list.add(self.teams[Team_side.RIGHT][self.position[i]][-1])

		# Assign selection_circle to each player
		# Left team
		for player in [players for sublist in list(self.teams[Team_side.LEFT].values()) for players in sublist]:
			player.selection_circle = self.selection_circle[0].clone()

		# Right team
		for player in [players for sublist in list(self.teams[Team_side.RIGHT].values()) for players in sublist]:
			player.selection_circle = self.selection_circle[1].clone()

	#----------------------------------------READ FILE SECTION-----------------------------------------------------
	def read_scene(self, file_path):
		with open(file_path) as file:
			self.read_hud(file)
			self.read_field(file)
			self.read_red_team(file)
			self.read_blue_team(file)
			self.read_selection_circle(file)
			self.read_ball(file)
			self.read_effect(file)
			self.read_sound(file)

	def read_hud(self, file):
		file.readline()
		hud_id = int(file.readline().strip().split(' ')[1])
		self.hud.init(ResourceManager.instance().hud_path_list[hud_id])

	def read_field(self, file):
		# Read field
		file.readline()
		image_id = int(file.readline().strip().split(' ')[1])
		self.field.init('Image', file_name = ResourceManager.instance().image_path_list[image_id])
		self.field.scale_to(SCREEN_WIDTH, SCREEN_HEIGHT)
		self.all_object_list.add(self.field)

		# Read goal
		file.readline()
		image_id_1, image_id_2 = list(map(int, file.readline().strip().split(' ')[1:]))
		self.goal.append(Object())
		self.goal[-1].init('Image', file_name = ResourceManager.instance().image_path_list[image_id_1])
		self.goal[-1].scale_to(SCREEN_WIDTH, SCREEN_HEIGHT)
		self.goal[-1].set_layer(-1)
		self.goal.append(Object())
		self.goal[-1].init('Image', file_name = ResourceManager.instance().image_path_list[image_id_2])
		self.goal[-1].scale_to(SCREEN_WIDTH, SCREEN_HEIGHT)
		self.goal[-1].set_layer(-1)
		self.all_object_list.add(self.goal)
		
	def read_red_team(self, file):
		self.teams[Team_side.LEFT] = dict()
		file.readline()
		image_id = int(file.readline().strip().split(' ')[1])

		# Prototype
		self.left_player.init('Image', file_name = ResourceManager.instance().image_path_list[image_id])
		self.left_player.rotate(float(file.readline().strip().split(' ')[1]))
		self.left_player.scale(*map(float, file.readline().strip().split(' ')[1:]))
		self.left_player.translate(*map(int, file.readline().strip().split(' ')[1:]))

	def read_blue_team(self, file):
		self.teams[Team_side.RIGHT] = dict()
		file.readline()
		image_id = int(file.readline().strip().split(' ')[1])

		# Prototype
		self.right_player.init('Image', file_name = ResourceManager.instance().image_path_list[image_id])
		self.right_player.rotate(float(file.readline().strip().split(' ')[1]))
		self.right_player.scale(*map(float, file.readline().strip().split(' ')[1:]))
		self.right_player.translate(*map(int, file.readline().strip().split(' ')[1:]))

	def read_selection_circle(self, file):
		file.readline()
		image_id = list(map(int, (file.readline().strip().split(' ')[1:])))
		image_id_green = image_id[0]
		image_id_red = image_id[1]

		# Green circle
		self.selection_circle.append(Object())
		self.selection_circle[-1].init('Image', file_name = ResourceManager.instance().image_path_list[image_id_green], alpha = True)
		self.selection_circle[-1].rotate(float(file.readline().strip().split(' ')[1]))
		self.selection_circle[-1].scale(*map(float, file.readline().strip().split(' ')[1:]))
		self.selection_circle[-1].translate(*map(int, file.readline().strip().split(' ')[1:]))

		# Red circle
		self.selection_circle.append(self.selection_circle[-1].clone())
		self.selection_circle[-1].setImage(ResourceManager.instance().image_path_list[image_id_red])

	def read_ball(self, file):
		file.readline()
		image_id = int(file.readline().strip().split(' ')[1])
		self.ball.init('Image', file_name = ResourceManager.instance().image_path_list[image_id], alpha = True)
		self.ball.rotate(float(file.readline().strip().split(' ')[1]))
		self.ball.scale(*map(float, file.readline().strip().split(' ')[1:]))
		self.ball.translate(*map(int, file.readline().strip().split(' ')[1:]))
		self.ball.set_radius()
		self.all_object_list.add(self.ball)

	def read_effect(self, file):
		file.readline()
		image_id = int(file.readline().strip().split(' ')[1])
		self.goal_image.init('Image', file_name = ResourceManager.instance().image_path_list[image_id], alpha = True)
		self.goal_image.rotate(float(file.readline().strip().split(' ')[1]))
		self.goal_image.scale(*map(float, file.readline().strip().split(' ')[1:]))
		self.goal_image.translate(*map(int, file.readline().strip().split(' ')[1:]))
		self.goal_image.set_layer(5)

	def read_sound(self, file):
		sound_num = int(file.readline().strip().split(' ')[1])

		for i in range(sound_num):
			sound_type = file.readline().strip().replace('#', '')
			sound_id = int(file.readline().strip().split(' ')[1])
			sound = pygame.mixer.Sound(ResourceManager.instance().sound_path_list[sound_id])
			self.sound_list.update({sound_type: sound})
Exemplo n.º 54
0
from Map import *

from Scoreboard import *
pygame.init()

p1_Banner = red
p2_Banner = blue

size = [700,600]
display = pygame.display.set_mode(size)
pygame.display.set_caption("PyPong")
clock = pygame.time.Clock()

player1 = Racquet(display,red,right)
player2 = ai_Racquet(display,blue,left)
ball1 = Ball(display,purple,center)
arena1 = Arena(display,lime_green)
scoreboard1 = Scoreboard(display,orange,p1_Banner,p2_Banner)

done = False
''' -------- Main Program Loop STARTS -------- '''
while done == False:
	display.fill(black)
	''' EVENT PROCESSING STARTS '''
	for event in pygame.event.get():
		if event.type == pygame.QUIT: # If user clicked close
			done = True # Flag that we are done so we exit this loop
	keys_held = pygame.key.get_pressed()
	if keys_held[K_UP]:
		player1.moveUp()
	if keys_held[K_DOWN]:
Exemplo n.º 55
0
class Pong:

	def __init__(self):
		self.pic = Image(Point(500,250),"background.gif")
		width = self.pic.getWidth()
		height = self.pic.getHeight()

		self.pongWin = GraphWin("Pong", width, height)
		self.pic.draw(self.pongWin)

		#create an instance of the Ball Class
		self.ball = Ball(self.pongWin)

		#create an instance of the Paddle Class
		self.paddle = Paddle(self.pongWin)


	def checkContact(self, ball, paddle):
		FrontTop = paddle.getfTop()
		FrontBottom = paddle.getfBottom()
		ballEdge = ball.getCenter()
		#print "paddleFront", paddle.getfTop(), paddle.getfBottom()
		#print "ballEdge", ballEdge.getX(), ballEdge.getY()

		#checks if the ball makes contact with the paddle
		if (ballEdge.getX() >= 940 and ballEdge.getX() <= 950) and ((ballEdge.getY() >= FrontTop) and (ballEdge.getY() <= FrontBottom)):
			ball.reverseX()
			ball.reverseY()
			return True

	def gameOver(self):
		if self.ball.getCenter().getX() > 990:
			return False
		else:
			return True

	def play(self):
		message = Text(Point(500,250), "")
  		message.setSize(30)
  		message.setTextColor("white")
  		message.setText("Welcome to 1 player Pong! Click anywhere to play!")
  		message.draw(self.pongWin)
  		self.pongWin.getMouse()
  		message.undraw()
  		Level = Text(Point(500, 110), "Level: 0")
		Level.setSize(20)
		Level.setTextColor("light blue")
		Level.draw(self.pongWin)
		scoreTxt = Text(Point(553,58), "0")
		scoreTxt.setSize(30)
		scoreTxt.setTextColor("red")
		scoreTxt.draw(self.pongWin)
		numHits = 0
		lvl = 1
		while self.gameOver() == True:
			clickPoint = self.pongWin.checkMouse()
			if clickPoint != None:
				dy = clickPoint.getY()
				self.paddle.move(self.pongWin, dy)
			self.ball.move(self.pongWin)
			if self.checkContact(self.ball, self.paddle) == True:
				numHits = numHits + 1
				#update the scoreboard
				scoreTxt.undraw()
				scoreTxt.setText(numHits)
				scoreTxt.setSize(30)
				scoreTxt.setTextColor("red")
				scoreTxt.draw(self.pongWin)
				if lvl == 1 and numHits == 1:
					Level.undraw()
					Level.setText("Level:")
					Level.draw(self.pongWin)
					lvlTxt = Text(Point(533, 110), lvl)
					lvlTxt.setSize(20)
					lvlTxt.setTextColor("light blue")
					lvlTxt.draw(self.pongWin)
				if numHits % 5 == 0:
					lvl = lvl + 1
					Level.undraw()
					lvlTxt.undraw()
					Level.setText("Level:")
					Level.draw(self.pongWin)
					lvlTxt = Text(Point(533, 110), lvl)
					lvlTxt.setSize(20)
					lvlTxt.setTextColor("light blue")
					lvlTxt.draw(self.pongWin)
					self.ball.goFaster()
			sleep(0.01)
		#state that the game is over
  		message.setText("You LOST!!!! Your score is:")
  		message.setTextColor("red")
  		EndScore = Text(Point(700, 250), numHits)
  		EndScore.setTextColor("red")
  		EndScore.setSize(30)
  		EndScore.draw(self.pongWin)
  		message.draw(self.pongWin)
  		self.pongWin.getMouse()
Exemplo n.º 56
0
 def initBall(self):
     #initialize ball and let it know about data
     self.ball = Ball() #just ball works too?
Exemplo n.º 57
0
def test_move1():
    b = Ball(100,150,20,-15,10,'red')
    b.move()
    (x,y) = b.position()
    assert x == 120 and y == 135