Esempio n. 1
0
File: app.py Progetto: mohill/bird
def birds_get(id=None):
	B = Bird()

	result = B.list(id)

	if not result:
		return "Not found", 404

	return dumps(result), 200
Esempio n. 2
0
File: app.py Progetto: mohill/bird
def birds_delete(id=None):
	if id is None:
		return "Error, no id given", 404

	B = Bird()

	if B.delete(id) is True:
		return "OK", 200
	else:
		return "Not found", 404
Esempio n. 3
0
 def __init__(self, *args, **kwargs):
     #Let all of the standard stuff pass through
     window.Window.__init__(self, *args, **kwargs)
     self.initGL()
     self.bird = Bird()
     self.world = World()
     self.enemy = Enemy()
Esempio n. 4
0
File: app.py Progetto: mohill/bird
def birds_post():
	# validate posted json, checks invalid JSON and mandatory fields.
	try:
		content = request.get_json()
		row = (content['name'], content['family'], content['continents'])
	except (ValueError, KeyError, TypeError):
		# mandatory fields missing or invalid json, return 400.
		return "Bad request", 400

	# checks for visible field, if not set default to false. 
	try:
		isinstance(content['visible'], bool)
	except (ValueError, KeyError):
		visible = False
	else:
		visible = content['visible']
		
	# create Bird.
	B = Bird(
		content['name'],
		content['family'],
		content['continents'],
		visible
	)

	# insert bird and return id to user.
	try:
		id = B.insert()
	except:
		return "Error inserting bird into MongoDB.", 400

	# fetch bird-data with id from insert.
	result = B.list(id)

	# if no result, return to user.
	if not result:
		return "Error, bird inserted but not found.", 400

	# return json-data to user..
	return dumps(result), 200
Esempio n. 5
0
def main():
    """The application's entry point.

    If someone executes this module (instead of importing it, for
    example), this function is called.
    """

    pygame.init()
    display_surface = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    pygame.display.set_caption('Pygame Flappy Bird')
    score_font = pygame.font.SysFont(None, 32, bold=True)  # default font
    images = load_images()
    scores = list()
    active = True

    while active:
        clock = pygame.time.Clock()
        bird = Bird(50, int(WIN_HEIGHT / 2 - Bird.HEIGHT / 2), 2,
                    (images['bird-wingup'], images['bird-wingdown']))
        pipes = deque()
        frame_clock = 0
        score = 0

        # Current state
        current_state = None
        action = None
        reward = 0
        collision = False
        while True:
            action_on_this_tick = frame_clock % PICK_ACTION_EVERY == 0

            clock.tick(FPS)

            if action_on_this_tick or collision:
                next_state = GameState(bird, pipes)

                # Update the values for the last state (current_state)
                if (current_state is not None and action is not None):
                    # Get the value for the reward
                    if collision:
                        reward = REWARD_FOR_FAILURE
                    elif active and not collision:
                        reward = PICK_ACTION_EVERY * REWARD_SUCCESS_MULTIPLIER

                    # Log current state
                    with current_state.take_action(action) as u:
                        u.update_utility_value(next_state, reward)

                    # Now that we have updated the state, quit the game after a
                    # collision
                    if collision:
                        break

                    # Reset the action
                    action = None

                # The "next" state will by the "current" state next time around
                current_state = next_state

            if not frame_clock % msec_to_frames(PipePair.ADD_INTERVAL):
                pp = PipePair(images['pipe-end'], images['pipe-body'])
                pipes.append(pp)

            # Handle the user quitting the game
            for event in pygame.event.get():
                action = get_action_from_event(event)
                if action is Action.quit:
                    exit()

            if not action and action_on_this_tick:
                action = current_state.max_value_action
                if action is Action.flap:
                    bird.flap()

            for x in (0, WIN_WIDTH / 2):
                display_surface.blit(images['background'], (x, 0))

            while pipes and not pipes[0].visible:
                pipes.popleft()

            for p in pipes:
                p.update()
                display_surface.blit(p.image, p.rect)

            bird.update()
            display_surface.blit(bird.image, bird.rect)

            if bird.check_collisions(pipes):
                collision = True

            # update and display score
            for p in pipes:
                if p.x + PipePair.WIDTH < bird.x and not p.score_counted:
                    score += 1
                    p.score_counted = True

            score_surface = score_font.render(str(score), True,
                                              (255, 255, 255))
            score_x = WIN_WIDTH / 2 - score_surface.get_width() / 2
            display_surface.blit(score_surface,
                                 (score_x, PipePair.PIECE_HEIGHT))

            pygame.display.flip()
            frame_clock += 1
        scores.append(score)
        print('Game #{}:\t{}'.format(len(scores), score))
    print('Best score: %i' % max(scores))
    pygame.quit()
Esempio n. 6
0
import os.path
import json
from bird import Bird


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Get follower and following for some users')
    parser.add_argument('--user', '-u',
            help='Get user infos')
    parser.add_argument('--list', '-l',
            help='File containing list of user names')
    parser.add_argument('--file', '-f',
            help='File to store followers/following infos')

    args = parser.parse_args()
    bird = Bird()

    if args.user is None and args.list is None:
        print("Please give an username or a file")
        parser.print_help()
        sys.exit(1)

    if args.file:
        try:
            f = open(args.file, "r")
            fdata = f.read()
            f.close()
            if fdata != "":
                data = json.loads(fdata)
            else:
                data = {}
Esempio n. 7
0
def enter():
    global boy
    boy = Bird()
    grass = Grass()
    game_world.add_object(grass, 0)
    game_world.add_object(boy, 1)
Esempio n. 8
0
def main(genomes, config):
    birds = []
    nets = []
    ge = []
    # print(genomes, config)
    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        birds.append(Bird(230, 350, BIRD_IMGS))
        g.fitness = 0
        ge.append(g)
    # print(len(birds))
    # Bird(230, 350)
    ground = Ground(730, GROUND_IMG)
    pipes = [Pipe(600, PIPE_IMG)]
    # print(PIPE_IMG.get_height())
    score = 0
    win = pygame.display.set_mode((WINDOW_W, WINDOW_H))
    pygame.display.set_caption('FLAPPY BIRD')
    run = True
    # i = 0
    clock = pygame.time.Clock()
    while run:
        clock.tick(50)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        pipe_ind = 0
        if len(birds) > 0:
            if len(pipes) > 1 and birds[
                    0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():
                pipe_ind = 1
        else:
            run = False
            break
            # if event.type == pygame.KEYDOWN:
            #     if event.key == pygame.K_SPACE:
            #         bird.jump()

        for x, bird in enumerate(birds):
            bird.move()
            ge[x].fitness += 0.1
            output = nets[x].activate(
                (bird.y, abs(bird.y - pipes[pipe_ind].height),
                 abs(bird.y - pipes[pipe_ind].bottom)))
            if output[0] > 0.5:
                bird.jump()
        # bird.move()
        rem = []
        add_pipe = False
        for pipe in pipes:
            for x, bird in enumerate(birds):
                if pipe.collide(bird):
                    # print('colliding'+str(i))
                    ge[x].fitness -= 1
                    birds.pop(x)
                    nets.pop(x)
                    ge.pop(x)
                    # i += 1
                    # run = False

                if not pipe.passed and pipe.x < bird.x:
                    pipe.passed = True
                    add_pipe = True

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                rem.append(pipe)
            pipe.move()

        for r in rem:
            pipes.remove(r)
        for x, bird in enumerate(birds):
            if bird.y + bird.img.get_height() >= 730 or bird.y < 0:
                # print('hit the g')
                # run = False
                birds.pop(x)
                nets.pop(x)
                ge.pop(x)

        if add_pipe:
            score += 1
            for g in ge:
                g.fitness += 5
            pipes.append(Pipe(600, PIPE_IMG))
        draw_window(win, birds, pipes, ground, score)
from bird import Bird
from penguin import Penguin, find_older
from parrot import Parrot


def print_bird(bird):
    Bird.who_is_this(bird)


# Create instances of the Bird class
some_bird = Bird("Some Bird", 12)
another_bird = Bird("Another Bird", 8)

# > Print the object
print(some_bird)
print(another_bird)

# > Call some methods on the Bird objects

some_bird.fly()
another_bird.eat('rice')
some_bird.dance()

# Create instances of the Parrot class

blu = Parrot("Blu", 2)
woo = Parrot("Woo", 4)

# > Call some methods on the Parrot objects

blu.fly()
Esempio n. 10
0
class Flappy():
    def __init__(self):
        self.state = INIT
        self.best = 0
        self.sound = True

    def increment_score(self):
        self.score = self.score + 1
        self.currentS.set_score(self.score)
        if self.sound_enable and self.sound:
            self._snd_pipe.play()

    def load_all(self):
        self.game_w = GAME_SIZE[0]
        self.game_h = GAME_SIZE[1]
        self.floor_y = self.game_h - FLOOR_Y
        self.bird_x = self.game_w / 3 - FLOOR_Y
        self.bird_y = self.game_h / 2
        self.pipe_w = PIPE_W
        self.build_y = self.floor_y - 229
        self.mes_x = (self.game_w - MES_W) / 2
        self.mes_y = (self.game_h - MES_H) / 2
        self.game_p = self.game_w - DIST - self.pipe_w
        self.max_s = self.floor_y - MIN_PIPE_H - DIST
        self.min_pipe_h = MIN_PIPE_H
        self.end_s_x = (self.game_w - 139) / 2
        self.sc_x = (self.game_w - 70) / 2
        self.score = 0
        self.sprites = pygame.sprite.LayeredUpdates()
        self.tubes = pygame.sprite.LayeredUpdates()
        self.background = make_back(self)
        self.screen.blit(self.background, (0, 0))
        ########################################################################
        self.floor = Floor(0, self.floor_y, self.game_w)
        self.floor.mVel = 0
        self.bird = Bird(self, self.bird_x, self.bird_y)
        self.bird.mAcc = 0
        self.end_scores = EndScore(self.end_s_x, 200)
        self.message = Message(self.mes_x, self.mes_y)
        self.currentS = CurrentScore(self, self.sc_x, 100)
        ########################################################################
        self.sprites.add(self.floor, layer=0)
        self.sprites.add(self.bird, layer=2)
        self.sprites.add(self.message, layer=3)

    def load_game(self):
        pipe1 = Pipe_I(self, self.game_w, PIPE_IH)
        pipe2 = Pipe_S(self, self.game_w, self.floor_y - PIPE_IH - DIST)
        self.sprites.add(pipe1, layer=1)
        self.sprites.add(pipe2, layer=1)
        self.tubes.add(pipe1)
        self.tubes.add(pipe2)
        self.tubes.add(self.floor)
        self.sprites.add(self.currentS, layer=3)
        self.bird.mAcc = 5
        self.bird.count = 20
        self.floor.mVel = -5
        self.sprites.remove(self.end_scores)
        self.sprites.remove(self.message)

    def main(self):
        pygame.display.init()
        pygame.font.init()
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.get_surface()
        if self.screen:
            w = self.screen.get_width()
            h = self.screen.get_height()
            global GAME_SIZE
            GAME_SIZE = [w, h]
        else:
            self.screen = pygame.display.set_mode(GAME_SIZE)
            pygame.display.set_caption('Flappy')
        self.sound_enable = True
        try:
            pygame.mixer.init()
            self._snd_pipe = pygame.mixer.Sound('data/sounds/pipe.ogg')
            self._snd_pipe.set_volume(0.5)
            self._snd_bird = pygame.mixer.Sound('data/sounds/bird.ogg')
            self._snd_bird.set_volume(0.5)
        except:
            self.sound_enable = False
        self.load_all()
        self.state = INIT
        self.running = True
        while self.running:
            while gtk.events_pending():
                gtk.main_iteration()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if self.state == INIT:
                        self.state = PLAY
                        self.load_game()
                    elif self.state == PLAY:
                        self.bird.setVel(8)
                        if self.sound_enable and self.sound:
                            self._snd_bird.play()
                    elif self.state == END:
                        self.state = INIT
                        self.load_all()

            self.sprites.clear(self.screen, self.background)
            self.sprites.update()
            self.sprites.draw(self.screen)

            col = pygame.sprite.spritecollide(self.bird, self.tubes, False)
            if not (col == []):
                self.state = END
                self.bird.mAcc = 0
                self.bird.count = -99
                self.floor.mVel = 0
                for spr in self.tubes:
                    spr.mVel = 0
                if self.score > self.best:
                    self.best = self.score
                self.end_scores.update_scores(self.score, self.best)
                self.sprites.add(self.end_scores, layer=3)
                self.sprites.draw(self.screen)

            pygame.display.flip()
            self.clock.tick(30)
Esempio n. 11
0
size = (width, height) = (int(screen_info.current_w),
                          int(screen_info.current_h))
screen = pygame.display.set_mode(size)

clock = pygame.time.Clock()

background = pygame.image.load('background.png')
background = pygame.transform.scale(background, (width, height))

color = (255, 0, 0)

scorecounters = pygame.sprite.Group()

startPos = (width / 8, height / 2)
pipes = pygame.sprite.Group()
player = Bird(startPos)
gapSize = 200
loopCount = 0
score = 0
gamePlay = True


def lose():
    global score, gamePlay
    score = 0
    font = pygame.font.SysFont(None, 70)
    text = font.render("You died!", True, (0, 0, 255))
    text_rect = text.get_rect()
    text_rect.center = (width / 2, height / 2)
    while True:
        screen.fill(color)
Esempio n. 12
0
 def addBird(self, vitesse):
     birdIndice = random.randint(0, 2)
     bird = Bird(self.imagesBird[birdIndice])
     bird.speed += vitesse
     self.birds.append(bird)
     return bird
Esempio n. 13
0
 def create_bird(self):
     self.bird = Bird(pygame.K_UP, self.width / 5, self.height / 2,
                      self.bird_img.get_width(), self.bird_img.get_height())
Esempio n. 14
0
class Game:
    def __init__(self):
        self.bird = Bird()
        self.pipes = []
        self.distance = 0
        self.score = 0

    def init(self):
        self.generate_pipes()

    def generate_pipes(self):
        top_pipe_config = {
            "x": SCREEN_WIDTH,
            "y": random.randint(-150, -10),
            "image": pygame.image.load(os.path.join("images", "pipeTop.png")),
        }
        bottom_pipe_config = {
            "x": SCREEN_WIDTH,
            "y": top_pipe_config["y"] + GAP,
            "image": pygame.image.load(os.path.join("images",
                                                    "pipeBottom.png")),
        }
        top_pipe = Pipe(top_pipe_config)
        bottom_pipe = Pipe(bottom_pipe_config)
        self.pipes.append({"top": top_pipe, "bottom": bottom_pipe})

    def check_pipe_collision(self, bird, pipe):
        return (bird.x + bird.width / 2 > pipe["top"].x and
                bird.y - bird.height / 2 < pipe["top"].y + pipe["top"].height
                ) or (bird.x + bird.width / 2 > pipe["bottom"].x
                      and bird.y + bird.height / 2 > pipe["bottom"].y)

    def check_road_collision(self, bird, road):
        return bird.y + bird.height / 2 > SCREEN_HEIGHT - road.get_height()

    def check_points(self, bird, pipe):
        return (bird.x + bird.width / 2 > pipe["top"].x and
                bird.y - bird.height / 2 > pipe["top"].y + pipe["top"].height
                and bird.y + bird.height / 2 < pipe["bottom"].y)

    def show_game_over_text(self):
        game_over = game_over_font.render(f"Score: {math.floor(self.score)}",
                                          True, (255, 255, 255))
        screen.blit(game_over, (80, 200))

    def show_score(self):
        score_text = score_font.render(f"Score: {math.floor(self.score)}",
                                       True, (255, 255, 255))
        screen.blit(score_text, (15, 15))

    def start(self):
        home_screen_running = True
        game_screen_running = False
        game_over_screen_running = False

        while home_screen_running:

            screen.fill((0, 0, 0))
            screen.blit(backgroundImg, (0, 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    home_screen_running = False

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if (SCREEN_WIDTH / 2 <= mouse[0] <= SCREEN_WIDTH / 2 + 60
                            and SCREEN_HEIGHT / 2 <= mouse[1] <=
                            SCREEN_HEIGHT / 2 + 180):
                        home_screen_running = False
                        game_screen_running = True

            mouse = pygame.mouse.get_pos()
            if (SCREEN_WIDTH / 2 <= mouse[0] <= SCREEN_WIDTH / 2 + 60 and
                    SCREEN_HEIGHT / 2 <= mouse[1] <= SCREEN_HEIGHT / 2 + 80):
                pygame.draw.rect(
                    screen,
                    button_color,
                    [
                        round(SCREEN_WIDTH / 2 - 70),
                        round(SCREEN_HEIGHT / 2), 140, 40
                    ],
                )

            else:
                pygame.draw.rect(
                    screen,
                    button_color_dark,
                    [
                        round(SCREEN_WIDTH / 2 - 70),
                        round(SCREEN_HEIGHT / 2), 140, 40
                    ],
                )

            screen.blit(
                text,
                (round(SCREEN_WIDTH / 2 - 30), round(SCREEN_HEIGHT / 2 + 5)))
            pygame.display.update()
            clock.tick(60)

            while game_screen_running:
                screen.fill((0, 0, 0))
                screen.blit(backgroundImg, (0, 0))

                self.distance += 1

                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        game_screen_running = False

                    if event.type == pygame.MOUSEBUTTONDOWN:
                        self.bird.flap_wings()
                        flap_sound.play()

                self.bird.draw()
                self.bird.update()

                if self.distance % 120 == 0:
                    self.generate_pipes()

                for pipe in self.pipes:
                    if pipe["top"].x + pipe["top"].width <= 0:
                        self.pipes.pop(0)

                for pipe in self.pipes:
                    if self.check_pipe_collision(self.bird, pipe):
                        hit_sound.play()
                        die_sound.play()
                        time.sleep(0.5)
                        game_screen_running = False
                        game_over_screen_running = True
                    if self.check_points(self.bird, pipe):
                        self.score += 0.024

                if self.check_road_collision(self.bird, foregroundImg):
                    hit_sound.play()
                    die_sound.play()
                    time.sleep(0.5)
                    game_screen_running = False
                    game_over_screen_running = True

                for pipe in self.pipes:
                    pipe["top"].draw()
                    pipe["top"].update()
                    pipe["bottom"].draw()
                    pipe["bottom"].update()

                screen.blit(foregroundImg,
                            (0, SCREEN_HEIGHT - foregroundImg.get_height()))
                self.show_score()
                pygame.display.update()
                clock.tick(60)

            while game_over_screen_running:
                screen.fill((20, 20, 20))

                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        game_over_screen_running = False

                self.show_game_over_text()
                pygame.display.update()
Esempio n. 15
0
class Flappy:
    def __init__(self):
        pygame.init()

        self.size = self.width, self.height = 400, 545
        self.screen = pygame.display.set_mode(self.size)
        self.clock = pygame.time.Clock()
        self.tick_counter = 0

        self.bird_img = pygame.image.load("img/bluebird-downflap.png")
        self.pipe_img = pygame.image.load("img\pipe-red.png")
        self.birdrect = self.bird_img.get_rect()

        self.pipes = []

        self.start_game()

    def create_bird(self):
        self.bird = Bird(pygame.K_UP, self.width / 5, self.height / 2,
                         self.bird_img.get_width(), self.bird_img.get_height())

    def move_bird(self):
        self.bird.move(self.height)

    def draw_bird(self):
        rotated_bird_img = pygame.transform.rotate(self.bird_img,
                                                   self.bird.angle)
        self.screen.blit(rotated_bird_img, self.bird)

    def create_pipe(self):
        offsetCanos = 225
        y_random = random.randrange(
            -(self.pipe_img.get_height() / 2) + offsetCanos + 30,
            (self.height - self.pipe_img.get_height() / 2) - offsetCanos - 30)
        y_top_pipe = y_random - offsetCanos
        y_bottom_pipe = y_random + offsetCanos

        print(f'y_random:{y_random}')
        print(f'y_top_pipe:{y_top_pipe}')
        print(f'y_bottom_pipe:{y_bottom_pipe}')
        print(f'tamanho da pipe = {self.pipe_img.get_height()}')

        top_pipe = Pipe(self.width - self.width / 10, y_top_pipe,
                        self.pipe_img.get_width(), self.pipe_img.get_height())

        bottom_pipe = Pipe(self.width - self.width / 10, y_bottom_pipe,
                           self.pipe_img.get_width(),
                           self.pipe_img.get_height())

        self.pipes.append({
            "top_pipe": top_pipe,
            "bottom_pipe": bottom_pipe,
        })

    def move_pipes(self):
        for pipe_pair in self.pipes:
            pipe_pair["top_pipe"].move(self.width)
            pipe_pair["bottom_pipe"].move(self.width)

    def draw_pipes(self):
        for pipe_pair in self.pipes:
            rotated_pipe_img = pygame.transform.rotate(self.pipe_img, 180)
            self.screen.blit(rotated_pipe_img, pipe_pair["top_pipe"])
            self.screen.blit(self.pipe_img, pipe_pair["bottom_pipe"])

    def game_loop(self):
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT: sys.exit()

            if self.tick_counter == 60:
                self.tick_counter = 0
                self.create_pipe()

            self.tick_counter += 1

            self.move_bird()
            self.move_pipes()

            self.screen.fill(white)
            self.draw_bird()
            self.draw_pipes()

            pygame.display.flip()
            self.clock.tick(60)

    def start_game(self):
        self.create_pipe()

        self.create_bird()
Esempio n. 16
0
import numpy as np
from bird import Bird

N_bird = 100
box = [10., 10.]
bird_list = [Bird() for i in range(N_bird)]
def print_bird(bird):
    Bird.who_is_this(bird)
Esempio n. 18
0
class Game:
    #clock, screen = clock_and_screen()
    def __init__(self, clock, screen):
        self.clock = clock
        self.screen = screen
        self.time_after_end = TIME_AFTER_END
        self.init_bg()
        self.init_nest()
        self.init_flag()
        self.init_bird()
        self.init_worms()
        self.init_cats()
        self.init_parameters()
        self.init_bombs()
        self.init_score_label()
        self.game_ended = False
        self.hit = pygame.mixer.Sound(file_hit)
    def loop(self):
        while not self.game_ended:
                self.end()
                self.events()
                self.update()
                self.draw()
                self.clock.tick(50)


    #The loop functions
    def events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if pygame.mouse.get_pressed()[0]:
                    if self.mouseclick_on_bird():
                        self.bird.mouse_click()
                    else:
                        self.bird.order_fly_to = pygame.mouse.get_pos()[0]
                        if self.mouseclick_on_nest():
                            self.bird.permission_to_land_on_nest = not self.bird.permission_to_land_on_nest

                elif pygame.mouse.get_pressed()[2]:
                    self.bird.drop_bomb()


    def update(self):
        if self.bird.live:
            self.cats_vs_bird()
        self.bombs_vs_cats()
        self.bird.update()
        self.bombs_sprite_group.update()
        self.worms_update()
        self.cats_update()
        self.bird_eat_worm()
        self.parameters.update()
        self.score_label.update(self.score)
        self.clear_cats_if_more_than_30()
    def draw(self):
        self.bg.blit()
        self.nest.blit()
        if self.bird.permission_to_land_on_nest:
            self.flag.blit()
        self.worms_sprite_group.draw(self.screen)
        self.cats_shadows_sprite_group.draw(self.screen)
        self.bird.blit()
        self.cats_sprite_group.draw(self.screen)
        self.bombs_sprite_group.draw(self.screen)
        self.parameters.blit()
        self.score_label.draw(self.screen)
        pygame.display.update()
    #The exit function
    def exit(self):
        pygame.quit()
        sys.exit()
    #The init functions
    def init_bg(self):
        self.bg = Background(self.screen)
    def init_nest(self):
        self.nest = Nest(self.screen, NEST_XY)
    def init_flag(self):
        self.flag = Flag(self.nest)
    def init_bird(self):
        self.bird = Bird(self, self.screen, self.nest)
    def init_worms(self):
        self.worms_sprite_group = pygame.sprite.Group()
        worm = Worm()
        self.worms_sprite_group.add(worm)
        self.time_worm_creation = random.randint(WORM_CREATE_MIN, WORM_CREATE_MAX)

    def init_cats(self):

        #CAT INIT
        cat = Cat()
        self.cats_sprite_group = pygame.sprite.Group()
        self.cats_sprite_group.add(cat)
        self.time_cat_creation = random.randint(CAT_CREATE_MIN, CAT_CREATE_MAX)

        #CAT SHADOW INIT
        shadow = Shadow(cat)
        self.cats_shadows_sprite_group = pygame.sprite.Group()
        self.cats_shadows_sprite_group.add(shadow)

    def init_parameters(self):
        self.parameters = Parameters(self.screen, self.bird, FONT_MAIN, FONT_SIZE_COORD, (RESOLUTION[0], 0))
    def init_bombs(self):
        self.bombs_sprite_group = pygame.sprite.Group()
    def init_score_label(self):
        #self.score_label_group = pygame.sprite.GroupSingle
        self.score_label = Score_label(10,10, 'Scores:', '')
        #self.score_label_group.add(score_label)
        self.score = 0
    #Event functions
    def mouseclick_on_bird(self):
        mouse_xy = pygame.mouse.get_pos()
        click = self.bird.rect.collidepoint(mouse_xy)
        return click
    def mouseclick_on_nest(self):
        mouse_xy = pygame.mouse.get_pos()
        click = self.nest.rect.collidepoint(mouse_xy)
        return click
    #Worms creation function
    def worms_new(self):
        if self.time_worm_creation <= 0:
            worm = Worm()
            self.worms_sprite_group.add(worm)
            self.time_worm_creation = random.randint(WORM_CREATE_MIN, WORM_CREATE_MAX)
    #Worms update function
    def worms_update(self):
        self.worms_new()
        self.worms_sprite_group.update()
        self.time_worm_creation -= 1
    #Bird eat or not eat a worm
    def bird_eat_worm(self):
        worm_eaten = pygame.sprite.spritecollideany(self.bird, self.worms_sprite_group)
        if worm_eaten and self.bird.live:
            worm_eaten.kill()
            del worm_eaten
            self.bird.food += WORM_TO_FOOD
    #Cats creation function
    def cats_new(self):
        if self.time_cat_creation <= 0:
            #CAT CREATE
            cat = Cat()
            self.cats_sprite_group.add(cat)
            self.time_cat_creation = random.randint(CAT_CREATE_MIN, CAT_CREATE_MAX)
            #CAT SHADOW CREATE
            shadow = Shadow(cat)
            self.cats_shadows_sprite_group.add(shadow)
    #Cats update function
    def cats_update(self):
        #CATS UPDATE
        self.cats_new()
        self.cats_sprite_group.update()
        self.time_cat_creation -= 1
        #SHADOWS UPDATE
        self.cats_shadows_sprite_group.update()
    def cats_vs_bird(self):
        bird_eaten = pygame.sprite.spritecollideany(self.bird, self.cats_sprite_group)
        if bird_eaten:
            self.bird.death()
            bird_eaten.speed_x = 0
            bird_eaten.eat = True
    def bombs_vs_cats(self):
        shitted_cats =  pygame.sprite.groupcollide(self.bombs_sprite_group, self.cats_sprite_group, True, True)
        if shitted_cats:
            pygame.mixer.Sound.play(self.hit)
            for x in shitted_cats:
                self.score += len(shitted_cats[x])

    def clear_cats_if_more_than_30(self):
        if len(self.cats_sprite_group.sprites()) > 30:
            self.cats_sprite_group.clear()

    def end(self):
        if not self.bird.live:
            if self.time_after_end < 0:
                self.game_ended = True
            else:
                self.time_after_end -= 1
Esempio n. 19
0
class MainWindow(window.Window):

    def __init__(self, *args, **kwargs):
        #Let all of the standard stuff pass through
        window.Window.__init__(self, *args, **kwargs)
        self.initGL()
        self.bird = Bird()
        self.world = World()
        self.enemy = Enemy()

    def initGL(self):

        glClearColor(0.0, 0.0, 0.0, 0.0)        # This Will Clear The Background Color To Black
        glClearDepth(1.0)                                       # Enables Clearing Of The Depth Buffer
        glDepthFunc(GL_LESS)                            # The Type Of Depth Test To Do
        glEnable(GL_DEPTH_TEST)                         # Enables Depth Testing
        glShadeModel(GL_SMOOTH)                         # Enables Smooth Color Shading
        
        glEnable(GL_TEXTURE_2D)               # Enable Texture Mapping
        glShadeModel(GL_SMOOTH)               # Enable Smooth Shading
        glClearColor(0.0, 0.0, 0.0, 0.5)      # Black Background
        glClearDepth(1.0)                     # Depth Buffer Setup
        glEnable(GL_DEPTH_TEST)               # Enables Depth Testing
        glDepthFunc(GL_LEQUAL)                # The Type Of Depth Testing To Do
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) # Really Nice Perspective Calculations
        
        glLightfv(GL_LIGHT1, GL_AMBIENT, vec(*LightAmbient))
        glLightfv(GL_LIGHT1, GL_DIFFUSE, vec(*LightDiffuse))
        glLightfv(GL_LIGHT1, GL_POSITION, vec(*LightPosition))
        glEnable(GL_LIGHT1)
        
        glColor4f(1.0,1.0,1.0,0.5)
        glBlendFunc(GL_SRC_ALPHA,GL_ONE)

    def rotate_world(self):
        # know bird.roty is off of (1,0)
        ref_angle = self.bird.roty
        
        point1=0
        if (ref_angle >= 0 and ref_angle<=90):
            point1 = math.atan(ref_angle * math.pi/180.0)
        elif (ref_angle >= 90 and ref_angle<=180):
            point1 = math.atan((180-ref_angle) * math.pi/180.0)
        elif (ref_angle >= 180 and ref_angle<=270):
            point1 = -math.atan((ref_angle-180) * math.pi/180.0)
        else:
            point1 = math.atan((ref_angle) * math.pi/180.0)

        point2=0
        if (ref_angle >= 0 and ref_angle<=90):
            point2 = math.atan((90-ref_angle) * math.pi/180.0)
        elif (ref_angle >= 90 and ref_angle<=180):
            point2 = math.atan((90.0-ref_angle) * math.pi/180.0)
        elif (ref_angle >= 180 and ref_angle<=270):
            point2 = math.atan((ref_angle-270) * math.pi/180.0)
        else:
            # between -90 and 0
            point2 = math.atan((ref_angle+90) * math.pi/180.0)

        self.world.rotate(1, point2, -point1)
        
    def animate_bird(self, interval):
        self.bird.flap()
        self.rotate_world()
        self.enemy.move(45)

    def update(self):
        pass

    def draw(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()

        glPushMatrix()
        self.world.draw()
        glPopMatrix()

        glPushMatrix()
        self.bird.draw()
        glPopMatrix()
        
        glPushMatrix()
        self.enemy.draw()
        glPopMatrix()
        
        
    def main_loop(self):
        clock.set_fps_limit(30)
        clock.schedule_interval(self.animate_bird, 0.01)
        
        while not self.has_exit:
            self.dispatch_events()
            self.clear()
        
            self.update()
            self.draw()
        
            #Tick the clock
            clock.tick()
            self.flip()


    
    """******************************************
    Event Handlers
    *********************************************"""
    def on_mouse_motion(self, x, y, dx, dy):
        new_dest_x = (float(x - self.width/2.0) / (self.width/2.0))*4.0
        new_dest_y = (float(y - self.height/2.0) / (self.height/2.0))*4.0
        old_dest_x = 0
        old_dest_y = 0

        y_rot = old_dest_y - new_dest_y
        x_rot = old_dest_x - new_dest_x

        if (y_rot != 0 and new_dest_y < old_dest_y):
            new_roty_dest = 180 + 1.0 * math.atan((x_rot) /
                                    (y_rot)) * 180.0/math.pi
        elif (y_rot != 0):
            new_roty_dest = 1.0 * math.atan((x_rot) /
                            (y_rot)) * 180.0/math.pi

        old_dest_x = self.bird.dest_x
        old_dest_y = self.bird.dest_y

        if (old_dest_x < 0 and new_dest_x < 0):
            if (old_dest_y <= 0 and new_dest_y>=0):
                new_roty_dest = -90
                self.bird.roty = -90
            elif (old_dest_y >=0 and new_dest_y<=0):
                new_roty_dest = 270
                self.bird.roty = 270
            
        if (y_rot):
            self.bird.roty_dest=new_roty_dest
            

        self.bird.dest_x = new_dest_x
        self.bird.dest_y = new_dest_y
        
        if (self.world.oldRotationMatrix):
            self.world.resetMatrix = self.world.oldRotationMatrix


    def on_resize(self, width, height):
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45.0, float(width)/float(height), 0.1, 100.0)
        glMatrixMode(GL_MODELVIEW)
Esempio n. 20
0
 def init_bird(self):
     self.bird = Bird(self, self.screen, self.nest)
Esempio n. 21
0
def main(genomes, config):
    global GEN
    GEN += 1
    networks = []
    genomes_list = []
    birds = []

    for genome_id, genome in genomes:
        # set up an initial fitness of 0 for each genome (bird)
        genome.fitness = 0
        # set up neural network for genome
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        networks.append(net)
        birds.append(Bird(230, 350))
        genomes_list.append(genome)

    base = Base(730)
    pipes = [Pipe(600)]
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    run = True
    clock = pygame.time.Clock()
    score = 0

    while run:
        # 30 ticks every second
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        # look at the first pipe in the pipe list
        pipe_index = 0
        if len(birds) > 0:
            # if the bird passed the first pipe in the list, look at the second pipe in the list
            if len(pipes) > 1 and birds[
                    0].x_pos > pipes[0].x_pos + pipes[0].PIPE_TOP.get_width():
                pipe_index = 1
        else:
            run = False
            break

        for bird_index, bird in enumerate(birds):
            bird.move()
            genomes_list[bird_index].fitness += 0.1
            output = networks[bird_index].activate(
                (bird.y_pos, abs(bird.y_pos - pipes[pipe_index].height),
                 abs(bird.y_pos - pipes[pipe_index].bottom)))
            if output[0] > 0.5:
                bird.jump()

        remove_pipes = []
        add_pipe = False

        for pipe in pipes:
            for bird_index, bird in enumerate(birds):
                if pipe.collide(bird):
                    # subtract fitness from birds that possibly make it far but collide with the pipe
                    genomes_list[bird_index].fitness -= 1
                    # remove that bird from the lists
                    birds.pop(bird_index)
                    networks.pop(bird_index)
                    genomes_list.pop(bird_index)

                # if the bird has passed the pipe, change the bird passed variable to true and add the next pipe
                if not pipe.bird_passed and pipe.x_pos < bird.x_pos:
                    pipe.bird_passed = True
                    add_pipe = True

            # if the pipe is off the screen, add the pipe to the remove list
            if pipe.x_pos + pipe.PIPE_TOP.get_width() < 0:
                remove_pipes.append(pipe)

            pipe.move()

        # once the bird has passed the pipe, add to score and set up next set of pipes
        if add_pipe:
            score += 1
            #if the bird makes it through the pipe, add to fitness to encourage it to want to go through the pipe
            for genome in genomes_list:
                genome.fitness += 5
            pipes.append(Pipe(600))

        # remove the pipes in the remove list from the pipes list
        for pipe in remove_pipes:
            pipes.remove(pipe)

        # if the bird hits the floor
        for bird_index, bird in enumerate(birds):
            if bird.y_pos + bird.img.get_height() >= 730 or bird.y_pos < 0:
                birds.pop(bird_index)
                networks.pop(bird_index)
                genomes_list.pop(bird_index)

        # once bird gets good enough, break out of loop
        if score > 50:
            break

        base.move()
        draw_window(win, birds, pipes, base, score, GEN)
Esempio n. 22
0
 def __init__(self):
     self.bird = Bird()
     self.pipes = []
     self.distance = 0
     self.score = 0
Esempio n. 23
0
def main():
    print("main called")
    path = os.path.dirname(__file__)
    bird = Bird(10)
    bird.flyForward()
Esempio n. 24
0
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Check twitter easily')
    parser.add_argument('--user', '-u',
            help='Get user infos')
    parser.add_argument('--tweets', '-t',
            help='Download tweets of an user')
    parser.add_argument('--tweet', '-T',
            help='Download tweet with the given id')
    parser.add_argument('--save', '-s',
            help='save all infos about an user and their tweets')
    parser.add_argument('--file', '-f',
            help='File containing usernames, display user infos in CSV format')

    args = parser.parse_args()

    bird = Bird()

    if args.user:
        a = bird.get_profile_information(args.user)
        print json.dumps(a._json, sort_keys=True, indent=4, separators=(',', ': '))
    elif args.tweets:
        a = bird.get_user_tweets(args.tweets, limit=1000)
        for page in a:
            # FIXME : improve this
            print json.dumps(page, sort_keys=True, indent=4, separators=(',', ': '))
    elif args.tweet:
        a = bird.get_tweet(args.tweet)
        print json.dumps(a._json, sort_keys=True, indent=4, separators=(',', ': '))
    elif args.save:
        data = {}
        a = bird.get_profile_information(args.save)
Esempio n. 25
0
class Board(QFrame):

    BoardWidth = 1200
    BoardHeight = 850

    def __init__(self, parent):
        super().__init__(parent)

        self.initBoard()

    def initBoard(self):
        '''initiates board'''

        self.q = Queue()
        self.qB = Queue()

        # setting timer for players
        self.timer = QBasicTimer()
        self.timer.start(20, self)

        # setting timer for birds
        self.timerBirds = QBasicTimer()
        self.timerBirds.start(BIRD_SPEED, self)
        self.timerBirdsID = self.timerBirds.timerId()

        # setting timer for birds bullets
        self.timerBird_bullet = QBasicTimer()
        self.timerBird_bullet.start(BIRD_BULLET_SPEED, self)
        self.timerBird_bulletID = self.timerBird_bullet.timerId()

        self.timerCounter = 0
        self.timerCounterBullets = 0

        # counter for levels
        self.lvl = 1
        self.nextLvl = False

        # setting label for showing number of levels
        self.lvlLabel = QLabel(self)
        pic = QPixmap('level.png')
        pic = pic.scaled(125, 65)
        self.lvlLabel.setPixmap(pic)
        self.lvlLabel.move(450, 20)

        self.lvlNumberLabel = QLabel(self)
        self.changeLvlNumber()
        self.lvlNumberLabel.move(600, 22)

        self.lvlNumberLabel2 = QLabel(self)
        pic = QPixmap('blue-watercolor-number-1B.png')
        pic = pic.scaled(25, 60)
        self.lvlNumberLabel2.setPixmap(pic)
        self.lvlNumberLabel2.move(630, 22)
        self.lvlNumberLabel2.hide()

        # setting label for showing who's winner
        self.winnerLabel = QLabel(self)
        pic = QPixmap('winner.png')
        pic = pic.scaled(700, 60)
        self.winnerLabel.setPixmap(pic)
        self.winnerLabel.move(190, 530)
        self.winnerLabel.hide()

        self.winnerNumLabel = QLabel(self)
        pic = QPixmap('blue-watercolor-number-0B.png')
        pic = pic.scaled(25, 60)
        self.winnerNumLabel.setPixmap(pic)
        self.winnerNumLabel.move(925, 530)
        self.winnerNumLabel.hide()

        self.noWinnerLabel = QLabel(self)
        pic = QPixmap('nowinner.png')
        pic = pic.scaled(500, 60)
        self.noWinnerLabel.setPixmap(pic)
        self.noWinnerLabel.move(340, 530)
        self.noWinnerLabel.hide()

        # setting curent value for birds speed and bullets speed
        self.curBirdSpeed = 30
        self.curBirdBulletSpeed = 10

        self.bigBird = Bird(self, -55, 80, 70, 70)
        self.bigBirdUp = True
        self.bigBirdHit = False
        #self.bigBirdStarted = False
        self.bigBirdFlying = False

        self.bigBird.setGeometry(10, 100, 70, 70)
        self.bigBird.hide()

        # initializing 3x10 birds, their directions, counter for number of hitted ones, bullets they have and number of ones they fired
        self.birds = [Bird(self, 0, 0, 50, 50) for i in range(NUM_BIRDS)]
        self.BirdsGoingLeft = True
        self.BirdsGoingRight = False
        self.wingsUp = [True for i in range(NUM_BIRDS)]
        self.bird_hit = [False for i in range(NUM_BIRDS)]
        self.dead_count = 0

        self.bird_bullets = [
            Bullet(self, 0, 0, 'Poop-512.png') for i in range(NUM_BIRDS)
        ]
        self.bird_bullets_fired = [False for i in range(NUM_BIRDS)]

        self.ColumnDown = [False for i in range(10)]

        self.leftBirdsWall = 9
        self.rightBirdsWall = 0
        self.rowDown = 2
        self.rowGone = False

        self.setUpGame()

        # initializing 2 players, their bullets, flags for firing bullets, hitting birds, touching another label, being dead and checking which key is pressed
        self.player1 = Player(self, 1100, 750, 1110, 'planeW.gif')
        self.player2 = Player(self, 50, 750, 0, 'planeG.gif')
        self.bullet1 = Bullet(self, 1120, 740, 'bullet.png')
        self.bullet1.hide()
        self.bullet2 = Bullet(self, 70, 740, 'bullet.png')
        self.bullet2.hide()

        self.isFired1 = False
        self.isFired2 = False
        self.labelsTouching1 = False
        self.labelsTouching2 = False
        self.hitBird1 = False
        self.hitBird2 = False

        self.noWinner = False

        self.isDead = 0
        self.isDead1 = False
        self.isDead2 = False

        self.gameOver = False

        self.keys_pressed = set()

        self.startProcess()

        self.setFocusPolicy(Qt.StrongFocus)

    def closeProcess(self):
        print("close T")
        self.q.put("CLOSE")

    def startProcess(self):
        self.p = Process(target=calculateBigBird, args=[self.q])
        # self.pBirds = Process(target=calculateBirds, args=[self.q])
        self.p.start()
    # self.pBirds.start()

    # method for setting up game -> place birds on board in formation

    def setUpGame(self):
        j = 0
        i = 0
        for z in range(NUM_BIRDS):
            self.birds[z].setX(1100 - i * 65)
            self.birds[z].setY(150 + j * 55)
            self.birds[z].setGeo()

            self.bird_bullets[z].set_bullets(1125 - i * 80, 205 + j * 80)
            self.bird_bullets[z].hide()

            i += 1
            if (i != 0 and i % 10 == 0):
                j += 1
                i = 0

    # method for updating game
    def game_update(self):
        self.checkNeighbors()

        self.timerCounter += 1
        self.timerCounterBullets += 1

        if (self.timerCounter % 14
                == 0) and self.bigBirdFlying and self.bigBirdHit is False:
            self.timerCounter = 0
            self.flyBigBird()

        if (self.timerCounterBullets % 75 == 0):
            self.update_bullets()
            self.timerCounterBullets = 0

        # -> checks which player has fired bullet and calls responding method
        if self.isFired1:
            self.isFired1 = self.fireBullet(self.bullet1,
                                            self.bullet1.y - BULLET_SPEED,
                                            True)
        else:
            self.bullet1.hide()
            self.hitBird1 = False

        if self.isFired2:
            self.isFired2 = self.fireBullet(self.bullet2,
                                            self.bullet2.y - BULLET_SPEED,
                                            True)
        else:
            self.bullet2.hide()
            self.hitBird2 = False

        # -> checks if bird has been hitted and sets her at responding position
        if self.hitBird1:
            self.bullet1.y = 0
            self.bullet1.x = 0
            self.bullet1.hide()

        if self.hitBird2:
            self.bullet2.y = 0
            self.bullet2.x = 0
            self.bullet2.hide()

        # -> checks flags to know if it needs to stop game and display winner
        if self.isDead1 is True and self.isDead2 is True:
            self.gameOver = True

            if (self.player1.num_lifes > 0 and self.player2.num_lifes > 0):
                self.noWinner = True
            self.endGame()

        # -> checks which key is being pressed and calls responding method to move player in wanted direction
        if Qt.Key_Left in self.keys_pressed:
            self.MovePlayer(self.player1, self.player1.x - 20,
                            'planeWLeft.gif')
        if Qt.Key_Right in self.keys_pressed:
            self.MovePlayer(self.player1, self.player1.x + 20,
                            'planeWRight.gif')
        if Qt.Key_A in self.keys_pressed:
            self.MovePlayer(self.player2, self.player2.x - 20,
                            'planeGLeft.gif')
        if Qt.Key_D in self.keys_pressed:
            self.MovePlayer(self.player2, self.player2.x + 20,
                            'planeGRight.gif')

        # -> checks if player is alive and sets position for bullet to be fired
        if Qt.Key_Up in self.keys_pressed and self.isFired1 is False and self.isDead1 is False:
            self.bullet1.y = self.player1.y - 15
            self.bullet1.x = self.player1.x + 20
            self.bullet1.move(self.bullet1.x, self.bullet1.y)
            self.bullet1.show()
            self.isFired1 = True
        if Qt.Key_W in self.keys_pressed and self.isFired2 is False and self.isDead2 is False:
            self.bullet2.y = self.player2.y - 15
            self.bullet2.x = self.player2.x + 20
            self.bullet2.move(self.bullet2.x, self.bullet2.y)
            self.bullet2.show()
            self.isFired2 = True

        # -> checks if there's need to update game to new level, if bird's bullet has hit the player, which player has hit the bird
        for i in range(NUM_BIRDS):
            if (self.dead_count == 30
                    and (self.isDead1 is False or self.isDead2 is False)):
                self.nextLvl = True
                self.lvl += 1
                self.curBirdSpeed += 2
                if (self.lvl % 3 == 0):
                    self.curBirdBulletSpeed += 2

                self.bigBird.move(-55, 80)
                self.bigBird.hide()

                # self.bigBirdStarted = False
                self.bigBirdFlying = False

                self.changeLvlNumber()

                if self.isDead1 is False:
                    self.player1.num_lifes = 3
                    for i in range(self.player1.num_lifes):
                        self.player1.lifes[i].show()

                if self.isDead2 is False:
                    self.player2.num_lifes = 3
                    for i in range(self.player2.num_lifes):
                        self.player2.lifes[i].show()

                self.setUpGame()

                self.BirdsGoingLeft = True
                self.BirdsGoingRight = False
                self.wingsUp = [True for i in range(NUM_BIRDS)]
                self.bird_hit = [False for i in range(NUM_BIRDS)]
                self.dead_count = 0

                self.bird_bullets_fired = [False for i in range(NUM_BIRDS)]

                self.ColumnDown = [False for i in range(10)]
                self.leftBirdsWall = 9
                self.rightBirdsWall = 0

                if self.isDead1 is False:
                    self.player1.x = 1100
                    self.player1.y = 750
                    self.player1.move(self.player1.x, self.player1.y)

                if self.isDead2 is False:
                    self.player2.x = 50
                    self.player2.y = 750
                    self.player2.move(self.player2.x, self.player2.y)

            if self.bird_bullets_fired[i] and self.bird_hit[i] is False:
                if self.areLabelsTouching(
                        self.bird_bullets[i],
                        self.player1) is False and self.areLabelsTouching(
                            self.bird_bullets[i], self.player2) is False:
                    self.bird_bullets_fired[i] = self.fireBullet(
                        self.bird_bullets[i],
                        self.bird_bullets[i].y + self.curBirdBulletSpeed,
                        False)
                elif self.areLabelsTouching(self.bird_bullets[i],
                                            self.player2):
                    self.player2.move(50, 750)
                    self.player2.x = 50
                    self.player2.num_lifes -= 1
                    self.player2.lifes[self.player2.num_lifes].hide()
                    self.bird_bullets_fired[i] = False
                    self.bird_bullets[i].hide()
                    if self.player2.num_lifes == 0:
                        self.isDead2 = True
                        self.isDead = 2
                        self.player2.setParent(None)
                elif self.areLabelsTouching(self.bird_bullets[i],
                                            self.player1):
                    self.player1.move(1100, 750)
                    self.player1.x = 1100
                    self.player1.num_lifes -= 1
                    self.player1.lifes[self.player1.num_lifes].hide()
                    self.bird_bullets_fired[i] = False
                    self.bird_bullets[i].hide()
                    if self.player1.num_lifes == 0:
                        self.isDead1 = True
                        self.isDead = 1
                        self.player1.setParent(None)

            if self.gameOver:
                self.birds[i].hide()
                self.bird_bullets[i].hide()

            if (self.bird_hit[i]):
                self.birds[i].hide()
                self.bird_bullets[i].hide()

            else:
                value = self.detectCollision(self.birds[i], self.bullet1,
                                             self.bullet2)
                if (value == 1):
                    self.dead_count += 1
                    print(self.dead_count)
                    self.hitBird1 = True
                    self.bird_hit[i] = True
                if (value == 2):
                    self.dead_count += 1
                    print(self.dead_count)
                    self.hitBird2 = True
                    self.bird_hit[i] = True

                if self.bigBirdFlying:
                    value = self.detectCollision(self.bigBird, self.bullet1,
                                                 self.bullet2)
                    if (value == 1 and self.player1.num_lifes < 3):
                        self.bigBirdHit = True
                        self.bigBird.hide()
                        if self.player1.num_lifes < 3:
                            self.player1.num_lifes += 1
                            self.player1.lifes[self.player1.num_lifes -
                                               1].show()
                    if (value == 2 and self.player2.num_lifes < 3):
                        self.bigBirdHit = True
                        self.bigBird.hide()
                        if self.player2.num_lifes < 3:
                            self.player2.num_lifes += 1
                            self.player2.lifes[self.player2.num_lifes].show()

    # method for checking if there's been collision between two labels
    def areLabelsTouching(self, label1, label2):
        self.label1 = label1
        self.label2 = label2
        if self.label2.x <= self.label1.x <= self.label2.x + self.label2.dimX and self.label1.y + self.label1.dimY >= \
                self.label2.y:
            return True
        elif self.label2.x <= self.label1.x + self.label1.dimX <= self.label2.x + self.label2.dimX and self.label1.y + \
                self.label1.dimY >= self.label2.y:
            return True
        else:
            return False

    def startBigBird(self):
        chance = random.randint(1, 100)
        #chance = 10
        if (chance < 10):
            #self.bigBirdStarted = True
            self.bigBird.move(-55, 80)
            self.bigBirdFlying = True  #!!!!!!!!!

    def flyBigBird(self):
        if self.bigBird.x < 1200:
            self.q.put(self.bigBird.x)
            pos = self.q.get()
            self.bigBird.move(pos, self.bigBird.y)
            #self.bigBird.move(self.bigBird.x + BIGBIRD_SPEED, self.bigBird.y)
            if self.bigBirdHit is False:
                self.FlightPicture(self.bigBird, self.bigBirdUp, False)
            else:
                self.bigBird.hide()

            if self.bigBirdUp:
                self.bigBirdUp = False
            else:
                self.bigBirdUp = True
        else:
            self.bigBirdFlying = False
            self.bigBird.hide()

    def checkNeighbors(self):
        for i in range(self.rightBirdsWall, self.leftBirdsWall):
            if (self.bird_hit[i] is False or self.bird_hit[i + 10] is False
                    or self.bird_hit[i + 20] is False):
                break
            else:
                self.rightBirdsWall = i + 1

        for j in range(self.leftBirdsWall, self.rightBirdsWall, -1):
            if (self.bird_hit[j] is False or self.bird_hit[j + 10] is False
                    or self.bird_hit[j + 20] is False):
                break
            else:
                self.leftBirdsWall = j - 1

    # method for birds movement formation
    def update_birds(self):
        if (self.bigBirdFlying is False):
            self.startBigBird()

        #if self.rowGone:
        #    self.rowDown -= 1
        #    self.rowGone = False

        if (self.BirdsGoingLeft):

            newX1 = self.birds[self.leftBirdsWall].x - 30
            newX2 = self.birds[self.leftBirdsWall + 10].x - 30
            newX3 = self.birds[self.leftBirdsWall + 20].x - 30
            newY = self.birds[self.leftBirdsWall].y - 30
            #idx = 10 * self.rowDown
            #bottomY = self.birds[self.leftBirdsWall].y + 30

            #if(self.birds[bottomY] > 720):

            #   self.isDead1 = True
            #   self.isDead2 = True

            if self.gameOver is False:
                if (newX1 > 0 and newX2 > 0 and newX3 > 0):
                    for i in range(NUM_BIRDS):
                        if self.bird_hit[i] is False:
                            #self.qB.put(self.birds[i].x)
                            #self.qB.put("SPEED")
                            #self.qB.put(self.curBirdSpeed)
                            #move = self.qB.get()
                            #self.birds[i].move(move, self.birds[i].y)
                            self.birds[i].move(
                                self.birds[i].x - self.curBirdSpeed,
                                self.birds[i].y)
                            self.FlightPicture(self.birds[i], self.wingsUp[i],
                                               True)

                            if (self.wingsUp[i]):
                                self.wingsUp[i] = False
                            else:
                                self.wingsUp[i] = True
                        else:
                            self.birds[i].hide()

                else:
                    for i in range(NUM_BIRDS):
                        if self.bird_hit[i] is False:
                            self.birds[i].move(
                                self.birds[i].x,
                                self.birds[i].y + self.curBirdSpeed)
                            self.FlightPicture(self.birds[i], self.wingsUp[i],
                                               False)
                            if (self.wingsUp[i]):
                                self.wingsUp[i] = False
                            else:
                                self.wingsUp[i] = True
                            self.BirdsGoingLeft = False
                            self.BirdsGoingRight = True
                        else:
                            self.birds[i].hide()

            else:
                for i in range(NUM_BIRDS):
                    self.birds[i].hide()

        elif (self.BirdsGoingRight):

            newX1 = self.birds[self.rightBirdsWall].x + 30
            newX2 = self.birds[self.rightBirdsWall + 10].x + 30
            newX3 = self.birds[self.rightBirdsWall + 20].x + 30

            newY = self.birds[0].y + 30
            idx = 10 * self.rowDown
            #bottomY = self.birds[idx].y + 30

            #if(self.birds[bottomY] > 720):
            #    self.isDead1 = True
            #    self.isDead2 = True

            if self.gameOver is False:

                if (newX1 < 1100 and newX2 < 1100 and newX3 < 1100):
                    for i in range(NUM_BIRDS):
                        if self.bird_hit[i] is False:
                            self.birds[i].move(
                                self.birds[i].x + self.curBirdSpeed,
                                self.birds[i].y)
                            self.FlightPicture(self.birds[i], self.wingsUp[i],
                                               False)
                            if (self.wingsUp[i]):
                                self.wingsUp[i] = False
                            else:
                                self.wingsUp[i] = True
                        else:
                            self.birds[i].hide()

                else:
                    for i in range(NUM_BIRDS):
                        if self.bird_hit[i] is False:
                            self.birds[i].move(
                                self.birds[i].x,
                                self.birds[i].y + self.curBirdSpeed)
                            self.FlightPicture(self.birds[i], self.wingsUp[i],
                                               True)
                            if (self.wingsUp[i]):
                                self.wingsUp[i] = False
                            else:
                                self.wingsUp[i] = True
                            self.BirdsGoingLeft = True
                            self.BirdsGoingRight = False
                        else:
                            self.birds[i].hide()

            else:
                for i in range(NUM_BIRDS):
                    self.birds[i].hide()

    # method for changing picture of a bird to mimic winds movement
    def FlightPicture(self, bird, wUp, left):
        if (wUp):
            picture = QPixmap("13g.gif")
        else:
            picture = QPixmap("18g.gif")

        if (left):
            picture = picture.transformed(QTransform().scale(-1, 1))

        picture = picture.scaled(50, 50)
        bird.setPixmap(picture)

    # method for birds randomly firing bullets
    def update_bullets(self):
        for i in range(NUM_BIRDS):
            choice = False
            number = random.randint(1, 200)
            if (number < 10):
                choice = True
            if (choice and self.bird_bullets_fired[i] is False):
                self.bird_bullets[i].x = self.birds[i].x + 50
                self.bird_bullets[i].y = self.birds[i].y + 55

                self.bird_bullets[i].move(self.bird_bullets[i].x,
                                          self.bird_bullets[i].y)
                self.bird_bullets[i].show()
                self.bird_bullets_fired[i] = True

    # method for detecting key being pressed and adding that event to array of pressed keys
    def keyPressEvent(self, event):
        self.keys_pressed.add(event.key())

    # method for detecting released pressed key and removing that event from array of pressed keys
    def keyReleaseEvent(self, event):
        self.keys_pressed.remove(event.key())

        key = event.key()

        if key == Qt.Key_Left:
            self.changePicture(self.player1, 'planeW.gif')
        if key == Qt.Key_Right:
            self.changePicture(self.player1, 'planeW.gif')
        if key == Qt.Key_A:
            self.changePicture(self.player2, 'planeG.gif')
        if key == Qt.Key_D:
            self.changePicture(self.player2, 'planeG.gif')

    # method for moving players within the range of board when keys are pressed
    def MovePlayer(self, player, newX, newPicture):

        if newX < Board.BoardWidth - 60 and newX > 10:
            self.player = player
            self.changePicture(self.player, newPicture)
            self.player.x = newX
            self.player.move(newX, self.player.y)
            self.show()

    # method for changing picture of a player to mimic movement in requested direction
    def changePicture(self, label, newPicture):
        picture = QPixmap(newPicture)
        picture = picture.scaled(40, 60)
        label.setPixmap(picture)

    # method for ending game and showing result
    def endGame(self):
        self.end = EndGame(self)

        if (self.noWinner is False):
            if self.isDead == 2:
                pic = QPixmap('blue-watercolor-number-2B.png')
            else:
                pic = QPixmap('blue-watercolor-number-1B.png')
            pic = pic.scaled(25, 60)
            self.winnerNumLabel.setPixmap(pic)

            self.winnerLabel.show()
            self.winnerNumLabel.show()
        else:
            self.noWinnerLabel.show()

        self.end.show()
        self.lvlLabel.hide()
        self.lvlNumberLabel.hide()
        self.lvlNumberLabel2.hide()
        self.player1.hide()
        self.player2.hide()

        for i in range(self.player1.num_lifes):
            self.player1.lifes[i].hide()

        for i in range(self.player2.num_lifes):
            self.player2.lifes[i].hide()

    # method for changing number of level
    def changeLvlNumber(self):
        if (self.lvl > 9 and self.lvl < 100):
            strLvl = str(self.lvl)
            pic1 = QPixmap('blue-watercolor-number-' + strLvl[0] + 'B.png')
            pic2 = QPixmap('blue-watercolor-number-' + strLvl[1] + 'B.png')

            pic1 = pic1.scaled(25, 60)
            pic2 = pic2.scaled(25, 60)

            self.lvlNumberLabel.setPixmap(pic1)
            self.lvlNumberLabel2.setPixmap(pic2)
            self.lvlNumberLabel.show()
            self.lvlNumberLabel2.show()
        else:
            pic = QPixmap('blue-watercolor-number-' + str(self.lvl) + 'B.png')
            pic = pic.scaled(25, 60)
            self.lvlNumberLabel.setPixmap(pic)
            self.lvlNumberLabel.show()

    # method for player firing bullets
    def fireBullet(self, bullet, newY, player):
        self.bullet = bullet

        if (player):
            if newY < 10:
                self.bullet.hide()
                return False
            else:
                self.bullet.move(self.bullet.x, newY)
                self.bullet.y = newY
                self.bullet.show()
                return True
        elif (newY > 840):
            self.bullet.hide()
            return False
        else:
            self.bullet.move(self.bullet.x, newY)
            self.bullet.y = newY
            self.bullet.show()
            return True

    # method for detecting which player has hit the bird
    def detectCollision(self, label1, label2, label3):
        self.label1 = label1
        self.label2 = label2

        detX1_start = self.label1.x
        detX1_stop = self.label1.x + self.label1.dimX

        detY1_start = self.label1.y
        detY1_stop = self.label1.y + self.label1.dimY

        detX2_start = self.label2.x
        detX2_stop = self.label2.x + self.label2.dimX

        detY2_start = self.label2.y
        detY2_stop = self.label2.y + self.label2.dimY

        if (detX2_start > detX1_start and detX2_start < detX1_stop):
            if (detY2_start > detY1_start and detY2_start < detY1_stop):
                return 1
            elif (detY2_stop > detY1_start and detY2_stop < detY1_stop):
                return 1
        elif (detX2_stop > detX1_start and detX2_stop < detX1_stop):
            if (detY2_start > detY1_start and detY2_start < detY1_stop):
                return 1
            elif (detY2_stop > detY1_start and detY2_stop < detY1_stop):
                return 1

        self.label2 = label3

        detX1_start = self.label1.x
        detX1_stop = self.label1.x + self.label1.dimX

        detY1_start = self.label1.y
        detY1_stop = self.label1.y + self.label1.dimY

        detX2_start = self.label2.x
        detX2_stop = self.label2.x + self.label2.dimX

        detY2_start = self.label2.y
        detY2_stop = self.label2.y + self.label2.dimY

        if (detX2_start > detX1_start and detX2_start < detX1_stop):
            if (detY2_start > detY1_start and detY2_start < detY1_stop):
                return 2
            elif (detY2_stop > detY1_start and detY2_stop < detY1_stop):
                return 2
        elif (detX2_stop > detX1_start and detX2_stop < detX1_stop):
            if (detY2_start > detY1_start and detY2_start < detY1_stop):
                return 2
            elif (detY2_stop > detY1_start and detY2_stop < detY1_stop):
                return 2

        return -1

    # method for initiazing game update according to timer event
    def timerEvent(self, event):
        if self.gameOver is False:
            self.game_update()

            if (self.timerBirdsID == event.timerId()):
                self.update_birds()

            #if(self.timerBird_bulletID == event.timerId()):
            #    self.update_bullets()

            self.update()
Esempio n. 26
0
    def initBoard(self):
        '''initiates board'''

        self.q = Queue()
        self.qB = Queue()

        # setting timer for players
        self.timer = QBasicTimer()
        self.timer.start(20, self)

        # setting timer for birds
        self.timerBirds = QBasicTimer()
        self.timerBirds.start(BIRD_SPEED, self)
        self.timerBirdsID = self.timerBirds.timerId()

        # setting timer for birds bullets
        self.timerBird_bullet = QBasicTimer()
        self.timerBird_bullet.start(BIRD_BULLET_SPEED, self)
        self.timerBird_bulletID = self.timerBird_bullet.timerId()

        self.timerCounter = 0
        self.timerCounterBullets = 0

        # counter for levels
        self.lvl = 1
        self.nextLvl = False

        # setting label for showing number of levels
        self.lvlLabel = QLabel(self)
        pic = QPixmap('level.png')
        pic = pic.scaled(125, 65)
        self.lvlLabel.setPixmap(pic)
        self.lvlLabel.move(450, 20)

        self.lvlNumberLabel = QLabel(self)
        self.changeLvlNumber()
        self.lvlNumberLabel.move(600, 22)

        self.lvlNumberLabel2 = QLabel(self)
        pic = QPixmap('blue-watercolor-number-1B.png')
        pic = pic.scaled(25, 60)
        self.lvlNumberLabel2.setPixmap(pic)
        self.lvlNumberLabel2.move(630, 22)
        self.lvlNumberLabel2.hide()

        # setting label for showing who's winner
        self.winnerLabel = QLabel(self)
        pic = QPixmap('winner.png')
        pic = pic.scaled(700, 60)
        self.winnerLabel.setPixmap(pic)
        self.winnerLabel.move(190, 530)
        self.winnerLabel.hide()

        self.winnerNumLabel = QLabel(self)
        pic = QPixmap('blue-watercolor-number-0B.png')
        pic = pic.scaled(25, 60)
        self.winnerNumLabel.setPixmap(pic)
        self.winnerNumLabel.move(925, 530)
        self.winnerNumLabel.hide()

        self.noWinnerLabel = QLabel(self)
        pic = QPixmap('nowinner.png')
        pic = pic.scaled(500, 60)
        self.noWinnerLabel.setPixmap(pic)
        self.noWinnerLabel.move(340, 530)
        self.noWinnerLabel.hide()

        # setting curent value for birds speed and bullets speed
        self.curBirdSpeed = 30
        self.curBirdBulletSpeed = 10

        self.bigBird = Bird(self, -55, 80, 70, 70)
        self.bigBirdUp = True
        self.bigBirdHit = False
        #self.bigBirdStarted = False
        self.bigBirdFlying = False

        self.bigBird.setGeometry(10, 100, 70, 70)
        self.bigBird.hide()

        # initializing 3x10 birds, their directions, counter for number of hitted ones, bullets they have and number of ones they fired
        self.birds = [Bird(self, 0, 0, 50, 50) for i in range(NUM_BIRDS)]
        self.BirdsGoingLeft = True
        self.BirdsGoingRight = False
        self.wingsUp = [True for i in range(NUM_BIRDS)]
        self.bird_hit = [False for i in range(NUM_BIRDS)]
        self.dead_count = 0

        self.bird_bullets = [
            Bullet(self, 0, 0, 'Poop-512.png') for i in range(NUM_BIRDS)
        ]
        self.bird_bullets_fired = [False for i in range(NUM_BIRDS)]

        self.ColumnDown = [False for i in range(10)]

        self.leftBirdsWall = 9
        self.rightBirdsWall = 0
        self.rowDown = 2
        self.rowGone = False

        self.setUpGame()

        # initializing 2 players, their bullets, flags for firing bullets, hitting birds, touching another label, being dead and checking which key is pressed
        self.player1 = Player(self, 1100, 750, 1110, 'planeW.gif')
        self.player2 = Player(self, 50, 750, 0, 'planeG.gif')
        self.bullet1 = Bullet(self, 1120, 740, 'bullet.png')
        self.bullet1.hide()
        self.bullet2 = Bullet(self, 70, 740, 'bullet.png')
        self.bullet2.hide()

        self.isFired1 = False
        self.isFired2 = False
        self.labelsTouching1 = False
        self.labelsTouching2 = False
        self.hitBird1 = False
        self.hitBird2 = False

        self.noWinner = False

        self.isDead = 0
        self.isDead1 = False
        self.isDead2 = False

        self.gameOver = False

        self.keys_pressed = set()

        self.startProcess()

        self.setFocusPolicy(Qt.StrongFocus)
Esempio n. 27
0
    parser.add_argument('--user', '-u', help='Get user infos')
    parser.add_argument('--tweets', '-t', help='Download tweets of an user')
    parser.add_argument('--tweet',
                        '-T',
                        help='Download tweet with the given id')
    parser.add_argument('--save',
                        '-s',
                        help='save all infos about an user and their tweets')
    parser.add_argument(
        '--file',
        '-f',
        help='File containing usernames, display user infos in CSV format')

    args = parser.parse_args()

    bird = Bird()

    if args.user:
        a = bird.get_profile_information(args.user)
        print json.dumps(a._json,
                         sort_keys=True,
                         indent=4,
                         separators=(',', ': '))
    elif args.tweets:
        a = bird.get_user_tweets(args.tweets)
        for page in a:
            # FIXME : improve this
            print json.dumps(page._json,
                             sort_keys=True,
                             indent=4,
                             separators=(',', ': '))