Exemple #1
0
def main():
    global Time

    if IsLinux:
        _ = os.system("clear")
    else:
        _ = os.system("cls")

    for i in range(len(start_functions)):
        b = bug.Bug(start_properties[i].name, start_properties[i].char,
                    start_properties[i].x, start_properties[i].y,
                    create_bullet, bugs_list)
        bugs_list.append(b)

    for i in range(len(start_functions)):
        start_functions[i] = bug.main_loop_decorator(start_functions[i])
        t = threading.Thread(target=start_functions[i], args=(bugs_list[i], ))
        threads.append(t)
        t.start()

    starter = threading.Thread(target=start_game)
    starter.start()
    for t in threads:
        t.join()
    starter.join()

    draw()
Exemple #2
0
 def spawn_bug(self):
     if len(self.server) > 0:
         chosen = random.choice(self.server)
         (row, col) = chosen
         newbug = bug.Bug()
         newbug.row = row
         newbug.col = col
         newbug.dir = random.randint(0, 3)
         newbug.prev_row = row
         newbug.prev_col = col
         self.bugs.append(newbug)
         self.field[row][col].append(BUG)
Exemple #3
0
async def on_message(msg):
    content = msg.content
    author = msg.author
    print(author, client.user)
    if not author == client.user:
        if author not in users:
            users[author] = {'oof': 0, 'bug': bug.Bug()}

        if author != client.user and not content.count("!oof"):
            num = content.count('oof')
            if num > 0:
                users[msg.author]['oof'] += num

        users[author]['bug'].digest(content)

    await client.process_commands(msg)
DISPLAYSURF = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption('bumper test')
DISPLAYSURF.fill(WHITE)

bumperTop = bug.Bumper('top', screenWidth, 1, 0, 0)
bumperBottom = bug.Bumper('bottom', screenWidth, 1, 0, screenHeight - 1)
bumperRight = bug.Bumper('right', 1, screenHeight, screenWidth - 1, 0)
bumperLeft = bug.Bumper('left', 1, screenHeight, 0, 0)

bumpers = pygame.sprite.Group()
bumpers.add(bumperTop)
bumpers.add(bumperRight)
bumpers.add(bumperBottom)
bumpers.add(bumperLeft)

bug = bug.Bug('bug.png', 50, 50, 5, 8)

while True:
    DISPLAYSURF.fill(BLACK)

    DISPLAYSURF.blit(bug.image, (bug.x, bug.y))
    bug.update()

    for bumper in bumpers:
        DISPLAYSURF.blit(bumper.image, (bumper.x, bumper.y))

    collisionList = pygame.sprite.spritecollide(bug, bumpers, False)
    if collisionList:
        bug.bounce(collisionList)

#for bug in movingBugs:
DISPLAYSURF = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption('shooting test')
DISPLAYSURF.fill(WHITE)

#make bumpers
bumperTop = bug.Bumper('top', screenWidth, 1, 0, 0)
bumperBottom = bug.Bumper('bottom', screenWidth, 1, 0, screenHeight - 1)
bumperRight = bug.Bumper('right', 1, screenHeight, screenWidth - 1, 0)
bumperLeft = bug.Bumper('left', 1, screenHeight, 0, 0)
bumpers = pygame.sprite.Group()
bumpers.add(bumperTop)
bumpers.add(bumperRight)
bumpers.add(bumperBottom)
bumpers.add(bumperLeft)

bug1 = bug.Bug('bug.png', 1, 1, 5, 0)
DISPLAYSURF.blit(bug1.image, (bug1.x, bug1.y))
smartBugs = pygame.sprite.Group()
smartBugs.add(bug1)

#make target bugs
stationaryBugs = pygame.sprite.Group()
x = 0
for i in range(0, 10):
    bugTarget = bug.Bug('bug.png', 0 + x, screenHeight - 50)
    bugTarget.update_rect()
    DISPLAYSURF.blit(bugTarget.image, (bugTarget.x, bugTarget.y))
    stationaryBugs.add(bugTarget)
    x = x + 50

count = 0
Exemple #6
0
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# frames per second setting
FPS = 30
fpsClock = pygame.time.Clock()

pygame.init()
DISPLAYSURF = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption('bug collision test')
DISPLAYSURF.fill(WHITE)

#bug2 moves down to colide with bug3
bug2 = bug.Bug('bug.png', 50, 0, 0, 5)
DISPLAYSURF.blit(bug2.image, (bug2.x, bug2.y))

#bug3 is stationary so that bug2 can hit it
bug3 = bug.Bug('bug.png', 50, 200)
DISPLAYSURF.blit(bug3.image, (bug3.x, bug3.y))

movingBugs = pygame.sprite.Group()
movingBugs.add(bug2)

stationaryBugs = pygame.sprite.Group()
stationaryBugs.add(bug3)

while True:
    DISPLAYSURF.fill(BLACK)
def mainLoop():
    collisionList = None
    levelCount = 1
    bugXVelocity = 3
    bugYVelovity = 1
    bugFiringPeriod = 80
    velocity = 10

    gamePlay = True
    shipAlive = True
    playerHealth = 400

    scoreFont = pygame.font.SysFont("Source Code Pro", 20)
    gameOverFont = pygame.font.SysFont("Source Code Pro", 30)
    score = 0
    scoreLabel = "SCORE: "

    while gamePlay:
        # pygame.time.wait(20)

        window.blit(background, (0, 0))

        healthBar(playerHealth)
        scoreLabel = scoreFont.render("SCORE: ", 1, WHITE)
        scoreDisplay = scoreFont.render(str(score), 1, WHITE)
        window.blit(scoreLabel, (415, 15))
        window.blit(scoreDisplay, (465, 15))

        # check for game exit
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gamePlay = False

        for bug in stationaryBugs:
            bullet = bug.update()
            window.blit(bug.image, (bug.x, bug.y))
            if bullet:
                pygame.mixer.Sound.play(bugBlaster_sound)
                enemyFire.add(bullet)

        for bullet in enemyFire:
            bullet.update()
            window.blit(bullet.image, (bullet.x, bullet.y))

        debris.update()
        debris.draw(window)

        for bug in stationaryBugs:
            collisionList = pygame.sprite.spritecollide(bug, bumpers, False)
            if collisionList:
                bug.bounce(collisionList)

        if playerFire:
            for bullet in playerFire:
                bullet.update()
                bumperCollision = pygame.sprite.spritecollide(bullet, bumpers, False)
                if bumperCollision:
                    playerFire.remove(bullet)
                window.blit(bullet.image, (bullet.x, bullet.y))

        # controls - arrow keys and space bar actions
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and spaceShip.x > 10:
            spaceShip.x -= velocity
            spaceShip.update_rect()

        if keys[pygame.K_RIGHT] and spaceShip.x < 450:
            spaceShip.x += velocity
            spaceShip.update_rect()

        if keys[pygame.K_UP] and spaceShip.y > 50:
            spaceShip.y -= velocity
            spaceShip.update_rect()

        if keys[pygame.K_DOWN] and spaceShip.y < 450:
            spaceShip.y += velocity
            spaceShip.update_rect()

        if keys[pygame.K_SPACE]:
            if shipAlive:
                spaceShip.hasFired = True

        if spaceShip.hasFired == True and spaceShip.count % 4 == 0:
            pygame.mixer.Sound.play(blaster_sound)
            newShot = fire.Fire(spaceShip, "up")
            playerFire.add(newShot)
            spaceShip.hasFired = False

        #   check for collisions with bullets and bugs
        if playerFire:
            for bullet in playerFire:
                collisionList = pygame.sprite.spritecollide(bullet, stationaryBugs, True)
                if collisionList:
                    playerFire.remove(bullet)
                    pygame.mixer.Sound.play(beenHit_sound)
                    newDebris = explosion.create_explosion(bullet)
                    for particle in newDebris:
                        debris.add(particle)
                    score += 1

        if enemyFire and shipAlive:
            # for bullet in enemyFire:
            collisionList = pygame.sprite.spritecollide(spaceShip, enemyFire, True)
            if collisionList:
                pygame.mixer.Sound.play(explosion_sound)
                newDebris = explosion.create_explosion(spaceShip)
                for particle in newDebris:
                    debris.add(particle)
                score += 1

                playerHealth = playerHealth - 25

                if playerHealth <= 0:
                    shipAlive = False

        if shipAlive:
            shipOnBugCollisionList = pygame.sprite.spritecollide(spaceShip, stationaryBugs, True)
            if shipOnBugCollisionList:
                newDebris=explosion.create_explosion(spaceShip)
                for p in newDebris:
                    debris.add(p)
                pygame.mixer.Sound.play(explosion_sound)
                playerHealth = playerHealth - 25
            if playerHealth <= 0:
                shipAlive = False

        for particle in debris:
            if particle.velocityX == 0 and particle.velocityY == 0:
                debris.remove(particle)

        if len(stationaryBugs) <= 3:
            levelCount += 1
            # make target bugs
            bugXVelocity += 1 * -1
            bugYVelovity += 1
            bugFiringPeriod -= 4
            x = 0

            for i in range(0, 10):
                bugTarget = None
                bugTarget = bg.Bug('aliensprite2.png', 0 + x, 50, bugXVelocity, bugYVelovity, bugFiringPeriod)
                #   bugTarget.update_rect()
                window.blit(bugTarget.image, (bugTarget.x, bugTarget.y))
                stationaryBugs.add(bugTarget)
                x = x + 50

        if shipAlive:
            window.blit(spaceShip.image, (spaceShip.x, spaceShip.y))
            spaceShip.count += 1
        else:
            gameOver = gameOverFont.render("GAME OVER! ", 1, WHITE)
            finalScoreLabel = gameOverFont.render("FINAL SCORE: ", 1, WHITE)
            finalScoreDisplay = gameOverFont.render(str(score), 1, WHITE)
            window.blit(gameOver, (180, 250))
            window.blit(finalScoreLabel, (160, 280))
            window.blit(finalScoreDisplay, (310, 280))

            gameOverMenu()

        pygame.display.update()
        fpsClock.tick(FPS)
Exemple #8
0
def track(video_path, contour_size_thresh, dist_thresh, penalty_thresh,
          output_dir, debug):

    FRAME_HISTORY = 10
    DIST_THRESH = dist_thresh
    PENALTY_THRESH = penalty_thresh
    CONTOUR_THRESH = contour_size_thresh

    # Initialize parameters
    video = cv2.VideoCapture(video_path)
    fgbg = cv2.bgsegm.createBackgroundSubtractorMOG(history=FRAME_HISTORY,
                                                    nmixtures=2,
                                                    backgroundRatio=0.1,
                                                    noiseSigma=0)
    bugs = []
    frame_num = 0
    show_box = 1
    show_trail = 1

    # Find a file name that isn't taken
    i = 1
    while os.path.isfile('%s%s%d%s' % (output_dir, '/result', i, '.mp4')):
        i = i + 1

    # Capture frame-by-frame
    ret, frame = video.read()

    fourcc = cv2.VideoWriter_fourcc(*'DIVX')
    frame_size = (np.shape(frame)[1], np.shape(frame)[0])
    new_video = cv2.VideoWriter(
        '%s%s%d%s' % (output_dir, '/result', i, '.mp4'), fourcc, 20.0,
        frame_size)

    while (True):
        # Capture frame-by-frame
        ret, frame = video.read()
        if ret == False:
            break
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        disp_frame = frame.copy()
        frame_num = frame_num + 1
        # cv2.putText(frame, "#%d" % frame_num, (3, 12), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 127, 0), 1)

        # Apply Background Subtraction
        fgmask = fgbg.apply(frame)

        # Get rid of the first frames in which background isn't properly identified
        if frame_num < FRAME_HISTORY * 2.5:
            continue

        # Perform morphological transformations
        kernel_ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
        dilation = cv2.dilate(fgmask, kernel_ellipse, iterations=1)
        fgmask = cv2.erode(dilation, kernel_ellipse, iterations=1)
        #cv2.imshow('bg', fgmask)

        # Find object contours
        _, contours, hierarchy = cv2.findContours(fgmask.copy(),
                                                  cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)
        contours[:] = [
            item for i, item in enumerate(contours)
            if cv2.contourArea(contours[i]) >= CONTOUR_THRESH
        ]
        #fgmask = cv2.cvtColor(fgmask, cv2.CV_GRAY2RGB)
        #cv2.drawContours(disp_frame, contours, -1, (0, 255, 0), 2)
        #cv2.imshow('frame', cv2.cvtColor(disp_frame, cv2.COLOR_BGR2RGB))
        #cv2.imshow('bg', cv2.cvtColor(fgmask, cv2.COLOR_BGR2RGB))

        centroids_list = []
        for curr_contour in contours:
            # Find contour's centriod
            moment = cv2.moments(curr_contour)
            cx = int(moment['m10'] / moment['m00'])
            cy = int(moment['m01'] / moment['m00'])
            measure = np.array([cx, cy], dtype=np.float32)
            centroids_list.append(measure)
            # for debug -- show centriod
            # TODO: move drawing to final drawing stage
            cv2.circle(disp_frame, (cx, cy), 3, (255, 0, 0), 1)
        centroids = np.array(centroids_list)

        if len(bugs) == 0:
            # Init the bug list
            for cent in centroids:
                buggy = bug.Bug(cent)
                bugs.append(buggy)
        else:
            # Calculate cost matrix for Hungarian Algorithm
            cost_matrix = np.zeros((len(bugs), len(centroids)))
            for i, buggy in enumerate(bugs):
                last_pos = buggy.path[-1]
                cost_matrix[i, :] = np.sqrt((centroids[:, 0] -
                                             last_pos[0])**2 +
                                            (centroids[:, 1] - last_pos[1])**2)

            # Hungarian Algorithm Assignment
            bug_ind, centroid_ind = linear_sum_assignment(cost_matrix)
            #print(bug_ind)
            #print(centroid_ind)

            # Reject assignments that are far from the previous point
            for i in range(len(bug_ind)):
                if np.linalg.norm(
                        centroids[centroid_ind[i]] -
                        bugs[bug_ind[i]].get_position()) > DIST_THRESH:
                    bug_ind[i] = -1
                    centroid_ind[i] = -1

            # Use all the valid assignments
            for i in range(len(bug_ind)):
                if bug_ind[i] != -1:
                    bugs[bug_ind[i]].update_path(centroids[centroid_ind[i]])
                    bugs[bug_ind[i]].plot_on_img(disp_frame, show_box,
                                                 show_trail,
                                                 contours[centroid_ind[i]])

            # See wich bugs and centroids remain unassigned
            bug_ind = np.unique(bug_ind)
            if bug_ind[0] == -1:
                bug_ind = bug_ind[1:]
            centroid_ind = np.unique(centroid_ind)
            if centroid_ind[0] == -1:
                centroid_ind = centroid_ind[1:]

            assigned_centroids = np.zeros(len(centroids))
            assigned_centroids[centroid_ind] = 1
            assigned_bugs = np.zeros(len(bugs))
            assigned_bugs[np.unique(bug_ind)] = 1

            # Create a new bug out of each unassigned centroid
            for i in range(len(assigned_centroids)):
                if assigned_centroids[i] == 0:
                    buggy = bug.Bug(centroids[i])
                    bugs.append(buggy)
                    buggy.plot_on_img(disp_frame, show_box, show_trail,
                                      contours[i])

            bugs_to_delete = []

            for i in range(len(assigned_bugs)):
                if assigned_bugs[i] == 0:
                    bugs[i].penalty = bugs[i].penalty + 1
                    if bugs[i].penalty >= PENALTY_THRESH:
                        bugs_to_delete.append(i)

            # Delete unassigned bugs from the bug list
            bugs = [x for i, x in enumerate(bugs) if i not in bugs_to_delete]

            cv2.putText(disp_frame, "%d Bugs in frame" % len(centroid_ind),
                        (10, 20), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0))

            # Display the resulting frame
            cv2.imshow('frame', cv2.cvtColor(disp_frame, cv2.COLOR_BGR2RGB))
            new_video.write(cv2.cvtColor(disp_frame, cv2.COLOR_BGR2RGB))
            if debug == True:
                key = cv2.waitKey(0) & 0xFF
            else:
                key = cv2.waitKey(60) & 0xFF
            if key == ord('t'):
                show_trail = 1 - show_trail
            elif key == ord('b'):
                show_box = 1 - show_box
            elif key == ord(' '):
                key = '0'
                while key != ord(' ') and key != 27:
                    if key == 27:
                        break
                    elif key == ord('t'):
                        show_trail = 1 - show_trail
                    elif key == ord('b'):
                        show_box = 1 - show_box
                    disp_frame = frame.copy()
                    for i in range(len(centroid_ind)):
                        bugs[bug_ind[i]].plot_on_img(disp_frame, show_box,
                                                     show_trail,
                                                     contours[centroid_ind[i]])
                    cv2.putText(disp_frame,
                                "%d Bugs in frame" % len(centroid_ind),
                                (10, 20), cv2.FONT_HERSHEY_PLAIN, 1.0,
                                (0, 0, 0))
                    cv2.imshow('frame',
                               cv2.cvtColor(disp_frame, cv2.COLOR_BGR2RGB))
                    key = cv2.waitKey(0)
            if key == 27:  #Esc ASCII code
                break
            key = '0'

    # When everything done, release the capture
    bug.Bug.bug_counter = 0
    video.release()
    new_video.release()
    cv2.destroyAllWindows()
GREEN = (  0, 255,   0)
BLUE  = (  0,   0, 255)

# frames per second setting
FPS = 10
fpsClock = pygame.time.Clock()

#initialize some variables
debris=pygame.sprite.Group()

pygame.init()
DISPLAYSURF= pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption('shooting test')
DISPLAYSURF.fill(BLACK)

bug1=bug.Bug('bug.png', screenWidth/2, screenHeight/2, 0, 0)
newDebris=explosion.create_explosion(bug1)
for particle in newDebris:
    debris.add(particle)

while True:
    DISPLAYSURF.fill(BLACK)
    if debris:
        for particle in debris:
            #print('particle', count)
            DISPLAYSURF.blit(particle.image, (particle.x, particle.y))
            particle.update()
            if particle.velocityX == 0 and particle.velocityY == 0:
                debris.remove(particle)
                #print(particle.velocityX, " ", particle.velocityY)
                if len(debris.sprites()) == 0: