Beispiel #1
0
def tzst_create_file_only(tmpdir):
    """
    create a note with just a file (filename required).

    Creating a note with just a file and no title or text fails on the note
    being empty. After creating the note as here, there's no evidence of the
    file in the note.

    Aha! I was overwriting the file content with the file name. Let's try it
    again...

    Well, when I pass both file and filename, with the file content base64
    encoded, what I get is 'File not in a valid base64 form'. It's not clear
    what the problem is. Guess I'll need to reach out to bear again.
    """
    pytest.dbgfunc()
    cub = Bear()
    testfile = tmpdir.join("bear-test-data")
    # data = "".join(["This is a file for testing bear\n",
    #                 "It contains a couple of lines\n",
    #                 "and is going to be inserted into a bear note\n"])
    data = "A"
    testfile.write(data)
    frob = base64.b64encode(data.encode())
    note = cub.create(title=beartest_title(),
                      file=frob,
                      filename=testfile.strpath)
    if not note:
        pytest.fail("create returned empty result")
    cub.trash(id=note['identifier'])
Beispiel #2
0
    def __init__(self, level=1):
        cv2.namedWindow('PlayGame', cv2.WINDOW_AUTOSIZE)
        self.level = level
        if self.level == 1:
            pathBackGround = 'imgsrc/resizedforrest.png'
            pathHoney = 'imgsrc/TransparentHoney.png'
            pathHero = 'imgsrc/Transparentpooh.png'
            pathEnemy = 'imgsrc/bee.png'
        elif self.level == 2:
            pathBackGround = 'imgsrc/resizedforrest.png'
            pathHoney = 'imgsrc/TransparentHoney.png'
            pathHero = 'imgsrc/Transparentpooh.png'
            pathEnemy = 'imgsrc/bee.png'
        elif self.level == 3:
            pathBackGround = 'imgsrc/resizedmap.png'
            pathHoney = 'imgsrc/comic1.png'
            pathHero = 'imgsrc/Transparentbear.png'
            pathEnemy = 'imgsrc/resizedpolice.png'
            self.value = [0, 260, 280, 280, 620, 270, 380, 590]

        self.backGround = cv2.imread(pathBackGround)
        self.honey = cv2.imread(pathHoney, -1)
        self.hero = cv2.imread(pathHero, -1)
        self.enemy = cv2.imread(pathEnemy, -1)

        self.windowSize = self.backGround.shape[:2]
        self.copy = self.backGround.copy()
        cv2.rectangle(self.copy, (695, 0), (self.windowSize[1], 35), (255, 255, 255), -1)
        self.collisionWatcher = CollisionWatcher(self.windowSize)
        self.bear = Bear(900, 400, self.hero)
        self.bee = Enemy(100, 100, self.enemy)
        self.cards = []
        self.collisionWatcher.setBear(self.bear)
        self.collisionWatcher.setEnemy(self.bee)
        self.collisionWatcher.setCards(self.cards)
Beispiel #3
0
def test_open_tag_fail():
    """
    Test for bear.open_tag(). Use fixture tnt.
    """
    pytest.dbgfunc()
    cub = Bear()
    with pytest.raises(Bearror) as err:
        cub.open_tag(name="no such tag")
    assert "Tag 'no such tag' was not found" in str(err.value)
Beispiel #4
0
class PluginManagerTestCase(unittest.TestCase):
    def setUp(self):
        self.tmp_config_path = mkstemp()[1]

        self.bear = Bear(settings_path=self.tmp_config_path)
        self.bear.config['settings']['db_path'] = ':memory:'
        self.bear.initialize_db()

    def tearDown(self):
        self.bear.db.close()
        os.remove(self.tmp_config_path)
Beispiel #5
0
class River:

    def __init__(self, hours, first_fish_size):
        # Generate the correct number of salmon
        self._salmons = [Salmon() for i in range(hours)]
        self._bear = Bear(first_fish_size)

    def eat(self):
        for index, salmon in enumerate(self._salmons):
            self._bear.eat(salmon.kgs, index)

    @property
    def total_bear_kgs(self):
        return self._bear.total_kgs
    def __init__(self, forest_size):

        self.forest_size = forest_size

        self.forest = []
        self.trees = []
        self.lumberjacks = []
        self.bears = []

        self.month_counter = 0

        for row in range(forest_size):
            for col in range(forest_size):

                # Roll for tree
                if random.randint(1, 100) < 50:
                    self.trees.append(Tree(row, col, self.forest_size, 12))

                # Roll for lumberjack
                if random.randint(1, 100) < 10:
                    self.lumberjacks.append(Lumberjack(row, col, self.forest_size))

                # Roll for bears
                if random.randint(1, 100) < 2:
                    self.bears.append(Bear(row, col, self.forest_size))

        print("In a {0}x{1} forest:".format(self.forest_size, self.forest_size))
        print("Starting with {0} trees.".format(len(self.trees)))
        print("Starting with {0} lumberjacks.".format(len(self.lumberjacks)))
        print("Starting with {0} bears.".format(len(self.bears)))

        thread.start_new_thread(self.start_display, ())
Beispiel #7
0
def test_instantiate():
    """
    Make sure pytest is working
    """
    pytest.dbgfunc()
    cub = Bear()
    assert 'open_note' in dir(cub)
Beispiel #8
0
    def __generate_random_river__(self, qty):
        for i in range(0, qty):
            random_num = random.randint(0, 2)

            if random_num == 0:
                self.__river__.append(None)
            elif random_num == 1:
                self.__river__.append(Fish(0, random.randint(1, 2)))
            elif random_num == 2:
                self.__river__.append(Bear(0, random.randint(1, 2), 0))
Beispiel #9
0
def test_create_tttp(title, text, tags, ts):
    """
    Test the create function with different possible arg combinations
    """
    pytest.dbgfunc()
    cub = Bear()
    kw = {}
    if title:
        kw['title'] = title
    if text:
        kw['text'] = text
    if tags:
        kw['tags'] = tags
    if ts:
        kw['timestamp'] = ts
    note = cub.create(**kw)
    if not note:
        pytest.fail("create returned empty result")
    cub.trash(id=note['identifier'])
Beispiel #10
0
 def prepare_values(item):
     if item == '---':
         return None
     elif item[0] == 'B':
         gender = 1 if item[1] == 'F' else 2
         age = int(item[2])
         return Bear(age, gender, 0)
     elif item[0] == 'F':
         gender = 1 if item[1] == 'F' else 2
         age = int(item[2])
         return Fish(age, gender)
Beispiel #11
0
def tnt():
    """
    Create a note with defined content, yield to the test, then trash the note
    """
    tid = uuid.uuid4()
    data = {
        'title':
        "pytest tmpnote {}".format(str(tid)),
        'text':
        "Original text",
        'addtext': ("Added text ='>< # // \"foobar\"\n"
                    "* bullet line\n"
                    "- todo line\n"
                    "+ plus +\n"
                    ". period .\n"
                    ", comma ,\n"
                    "! bang !\n"
                    "? question mark ?\n"
                    "| pipe |\n"
                    "\\ backslash \\\n"
                    "tab\t\t\tline\n"
                    "` grave `\n"
                    "$ dollar line\n"
                    "@ at sign @\n"
                    "^ caret ^\n"
                    "& ampersand &\n"
                    ": colon line\n"
                    "% percent line %\n"
                    "~ tilde ~\n"
                    "{ curly brace }\n"
                    "( parenthesis line )\n"
                    "[ square bracket line ]"),
        'addtags': ["newtag1", "newtag2"],
        'cub':
        Bear(),
        'unique_tag':
        tid.hex,
        'tags':
        "pytest,tmpnote,testing," + tid.hex
    }

    result = data["cub"].create(title=data['title'],
                                text=data['text'],
                                tags=data['tags'])
    note = data["cub"].open_note(id=result['identifier'], show_window="no")
    data['id'] = result['identifier']
    data['pre'] = note['note']
    (data['hdr'], data['body']) = note['note'].split("\n", 1)
    yield data
    data["cub"].trash(id=data['id'])
Beispiel #12
0
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        # Set the window size and title bar text
        # Windowed
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        # Full screen
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Play Ball!")

        # Create an instance to store game statistics.
        self.stats = GameStats(self)

        self.bear = Bear(self)
        self.balls = pygame.sprite.Group()
        self.dog = Dog(self)

        # Make the Play button.
        self.play_button = Button(self, "Play")
    def pass_year(self):

        print("Year {0} Report:".format(self.month_counter/12))

        print("Forest has {0} trees, {1} lumberjacks, and {2} bears."
              .format(len(self.trees), len(self.lumberjacks), len(self.bears)))

        # Check lumber and reset to 0 for every lumberjack
        total_lumber = sum([lumberjack.lumber for lumberjack in self.lumberjacks])
        print("Lumber gathered: {0}".format(total_lumber))
        for lumberjack in self.lumberjacks:
            lumberjack.lumber = 0

        # Hire new lumberjacks based on the amount of lumber gathered. Too little lumber? Fire a jack at random.
        if total_lumber >= len(self.lumberjacks):
            for new_lumberjacks in range(0, floor(total_lumber / len(self.lumberjacks))):
                x_pos = random.choice(range(self.forest_size))
                y_pos = random.choice(range(self.forest_size))
                self.lumberjacks.append(Lumberjack(x_pos, y_pos, self.forest_size))
        elif len(self.lumberjacks) > 1:  # Can't go below 1
            random.shuffle(self.lumberjacks)
            self.lumberjacks.pop()

        # Check mawings and reset to 0 for every bear
        total_mawings = sum([bear.maws for bear in self.bears])
        print("Bear mawings: {0}".format(total_mawings))
        for bear in self.bears:
            bear.maws = 0

        # If there are no mawings for a year, add a bear, otherwise, remove one at random
        if total_mawings == 0:
            x_pos = random.choice(range(self.forest_size))
            y_pos = random.choice(range(self.forest_size))
            self.bears.append(Bear(x_pos, y_pos, self.forest_size))
        else:
            random.shuffle(self.bears)
            self.bears.pop()
 def generate_bears(self, num):
     bears=[]
     for i in range(num):
         bear = Bear()
         bears.append(bear)
     return bears
Beispiel #15
0
# Testing the inherited classes - get_name exists only in the base class Animal

from lizard import Lizard
from gorilla import Gorilla
from bear import Bear
from snake import Snake

lizard1 = Lizard("Sweetiepie")
gorilla1 = Gorilla("Howard")
bear1 = Bear("Dolly")
snake1 = Snake("Hzzzz")

print(lizard1.get_name())
print(gorilla1.get_name())
print(bear1.get_name())
print(snake1.get_name())

# print(help(bear1))
help(bear1)
Beispiel #16
0
    def setUp(self):
        self.tmp_config_path = mkstemp()[1]

        self.bear = Bear(settings_path=self.tmp_config_path)
        self.bear.config['settings']['db_path'] = ':memory:'
        self.bear.initialize_db()
Beispiel #17
0
class BearTestCase(unittest.TestCase):
    def setUp(self):
        self.tmp_config_path = mkstemp()[1]

        self.bear = Bear(settings_path=self.tmp_config_path)
        self.bear.config['settings']['db_path'] = ':memory:'
        self.bear.initialize_db()

    def tearDown(self):
        self.bear.db.close()
        os.remove(self.tmp_config_path)

    def test_add_feed(self):
        self.bear.add_feed('http://socketubs.org/atom.xml')
        self.assertEqual(self.bear.get_feeds().count(), 1)

    def test_get_feeds(self):
        feed_url = 'http://socketubs.org/atom.xml'
        self.bear.add_feed(feed_url)
        self.assertEqual(self.bear.get_feeds()[0].url, feed_url)
        self.assertEqual(self.bear.get_feeds()[0].id, 1)

    def test_get_feed_by_id(self):
        feed_url = 'http://socketubs.org/atom.xml'
        feed_id = self.bear.add_feed(feed_url)
        feed = self.bear.get_feed(feed_id=feed_id)
        self.assertEqual(feed.id, feed_id)

    def test_get_feed_by_url(self):
        feed_url = 'http://socketubs.org/atom.xml'
        self.bear.add_feed(feed_url)
        feed = self.bear.get_feed(url=feed_url)
        self.assertEqual(feed.url, feed_url)
Beispiel #18
0
class Game():
    def __init__(self, level=1):
        cv2.namedWindow('PlayGame', cv2.WINDOW_AUTOSIZE)
        self.level = level
        if self.level == 1:
            pathBackGround = 'imgsrc/resizedforrest.png'
            pathHoney = 'imgsrc/TransparentHoney.png'
            pathHero = 'imgsrc/Transparentpooh.png'
            pathEnemy = 'imgsrc/bee.png'
        elif self.level == 2:
            pathBackGround = 'imgsrc/resizedforrest.png'
            pathHoney = 'imgsrc/TransparentHoney.png'
            pathHero = 'imgsrc/Transparentpooh.png'
            pathEnemy = 'imgsrc/bee.png'
        elif self.level == 3:
            pathBackGround = 'imgsrc/resizedmap.png'
            pathHoney = 'imgsrc/comic1.png'
            pathHero = 'imgsrc/Transparentbear.png'
            pathEnemy = 'imgsrc/resizedpolice.png'
            self.value = [0, 260, 280, 280, 620, 270, 380, 590]

        self.backGround = cv2.imread(pathBackGround)
        self.honey = cv2.imread(pathHoney, -1)
        self.hero = cv2.imread(pathHero, -1)
        self.enemy = cv2.imread(pathEnemy, -1)

        self.windowSize = self.backGround.shape[:2]
        self.copy = self.backGround.copy()
        cv2.rectangle(self.copy, (695, 0), (self.windowSize[1], 35), (255, 255, 255), -1)
        self.collisionWatcher = CollisionWatcher(self.windowSize)
        self.bear = Bear(900, 400, self.hero)
        self.bee = Enemy(100, 100, self.enemy)
        self.cards = []
        self.collisionWatcher.setBear(self.bear)
        self.collisionWatcher.setEnemy(self.bee)
        self.collisionWatcher.setCards(self.cards)

    def drawItem(self, frame, Item):
        posX, posY = Item.getPosition()[:2]
        img = Item.getImg()
        height, width = img.shape[:2]
        height //= 2
        width //= 2
        if Item.getMask() is not None:
            mask = Item.getMask()
            frame[posY-height:posY+height, posX-width:posX+width] *= 1 - mask
            frame[posY-height:posY+height, posX-width:posX+width] += img * mask
        else:
            frame[posY-height:posY+height, posX-width:posX+width] = img
        if self.level == 1 and isinstance(Item, Bear):
            frame = self.mosaic_area(frame, posX-width, posY-height, width*2, height*2)


    def generateHoney(self):
        if self.level == 3:
            num = random.randint(1, 7)
            path = 'imgsrc/comic/comic' + str(num) + '.png'
            self.honey = cv2.imread(path)
            heightHoney, widthHoney = self.honey.shape[:2]
            heiH = heightHoney // 2
            widH = widthHoney // 2
            posX = random.randint(widH, self.windowSize[1]-widH)
            posY = random.randint(heiH, self.windowSize[0]-heiH)
            self.cards.append(Card(posX, posY, self.honey, self.level, point=self.value[num]))
        else :
            heightHoney, widthHoney = self.honey.shape[:2]
            heiH = heightHoney // 2
            widH = widthHoney // 2
            posX = random.randint(widH, self.windowSize[1]-widH)
            posY = random.randint(heiH, self.windowSize[0]-heiH)
            self.cards.append(Card(posX, posY, self.honey, self.level))



    def gameOver(self, frame):
        i = 0
        while i < 35:
            bg = frame.copy()
            Irot = ndimage.rotate(self.bear.getImg(), i, reshape=False)
            Mrot = ndimage.rotate(self.bear.getMask(), i, reshape=False)
            self.bear.setImg(Irot)
            self.bear.setMask(Mrot)
            self.drawItem(bg, self.bear)
            cv2.imshow('PlayGame', bg)
            cv2.waitKey(1)
            i += 1

        if self.level != 3:
            x, y = self.windowSize[:2]
            x //= 2
            y //= 2
            cv2.rectangle(self.backGround, (0, 0), (960, 544), (255, 119, 103), -1)
            overImg = cv2.imread('imgsrc/TransparentpoohGameOver.png')
            width, height = overImg.shape[:2]
            self.backGround[80:80+width, 50:50+height] = overImg
            cv2.putText(self.backGround, 'Game Over', (x-100, y-200),
                            cv2.FONT_HERSHEY_COMPLEX, 3, (0,0,0), thickness=4)
            cv2.putText(self.backGround, 'Points: ' + str(self.bear.getHavingPoint()), (x, y),
                            cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), thickness=3)
            while True:
                cv2.imshow('PlayGame', self.backGround)
                if cv2.waitKey(1) & 0xff == ord('q'):
                    return 'end'
                elif cv2.waitKey(1) & 0xff == ord('r'):
                    return ''
        else:
            x, y = self.windowSize[:2]
            x //= 2
            y //= 2
            cv2.rectangle(self.backGround, (0, 0), (960, 544), (255, 119, 103), -1)
            cv2.putText(self.backGround, 'Game Over', (x-100, y-200),
                            cv2.FONT_HERSHEY_COMPLEX, 3, (0,0,0), thickness=4)
            cv2.putText(self.backGround, 'Points: ' + str(self.bear.getHavingPoint()), (x, y),
                            cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), thickness=3)
            while True:
                cv2.imshow('PlayGame', self.backGround)
                if cv2.waitKey(1) & 0xff == ord('q'):
                    return 'end'
                elif cv2.waitKey(1) & 0xff == ord('r'):
                    return ''

    def mosaic(self, src, ratio=0.1):
        small = cv2.resize(src, None, fx=ratio, fy=ratio, interpolation=cv2.INTER_NEAREST)
        return cv2.resize(small, src.shape[:2][::-1], interpolation=cv2.INTER_NEAREST)

    def mosaic_area(self, src, x, y, width, height, ratio=0.1):
        dst = src
        dst[y:y + height, x:x + width] = self.mosaic(dst[y:y + height, x:x + width], ratio)
        return dst

    def operate(self):
        cap = cv2.VideoCapture(0)
        # cv2.namedWindow('hand', cv2.WINDOW_NORMAL)
        message = ''
        low = np.array([0, 30, 60])
        high = np.array([20, 150, 255])
        kernel = np.ones((5,5), np.uint8)
        while True:
            frame = self.copy.copy()
            if len(self.cards) < 30 and random.randint(0, 100) > 98:
                self.generateHoney()
            if cap.isOpened():
                ret, img = cap.read()
                img = cv2.flip(img, 1)
                hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
                skin = cv2.inRange(hsv, low, high)
                advance = cv2.dilate(skin,kernel)
                advance = cv2.erode(advance,kernel)
                _, contours, hierarchy = cv2.findContours(advance, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
                if len(contours) > 0:
                    index = 0
                    max = 0
                    for i in range(0, len(contours)):
                        area = cv2.contourArea(contours[i])
                        if area > max:
                            index = i
                            max = area
                    # cv2.drawContours(img, contours, index, (0, 0, 255), 2, 8, hierarchy, 0)
                    lrtb = []
                    cnt = contours[index]
                    lrtb.append(tuple(cnt[cnt[:,:,0].argmin()][0]))
                    lrtb.append(tuple(cnt[cnt[:,:,0].argmax()][0]))
                    lrtb.append(tuple(cnt[cnt[:,:,1].argmin()][0]))
                    lrtb.append(tuple(cnt[cnt[:,:,1].argmax()][0]))
                    M = cv2.moments(cnt)
                    cx = int(M['m10']/M['m00'])
                    cy = int(M['m01']/M['m00'])
                    cg = np.array([cx, cy])
                    max = 0
                    index = 0
                    for i, point in enumerate(lrtb):
                        b = np.array(point)
                        norm = np.linalg.norm(b - cg)
                        if norm > max:
                            max = norm
                            index = i
                    # cv2.circle(img, (cx ,cy), 20, (0,255,0), -1)
                    # cv2.circle(img, lrtb[index], 20, (255,0,0), -1)
                    # cv2.imshow('hand', img)
                    x = lrtb[index][0] - cx
                    y = lrtb[index][1] - cy
                    if x >= 0 and y >= 0:
                        if x < y:
                            ope =  'bottom'
                        else:
                            ope =  'right'
                    elif x >= 0 and y < 0:
                        if x < abs(y):
                            ope =  'top'
                        else:
                            ope = 'right'
                    elif x < 0 and y >= 0:
                        if abs(x) < y:
                            ope = 'bottom'
                        else:
                            ope = 'left'
                    else:
                        if abs(x) < abs(y):
                            ope = 'top'
                        else:
                            ope = 'left'
                    self.bear.opePosition(ope)
            self.bee.calPosition()
            self.collisionWatcher.watch()
            if self.collisionWatcher.collideEnemy():
                for card in self.cards:
                    self.drawItem(frame, card)
                self.drawItem(frame, self.bee)
                message = self.gameOver(frame)
                break
            else:
                for card in self.cards:
                    self.drawItem(frame, card)
                self.drawItem(frame, self.bee)
                self.drawItem(frame, self.bear)
                if self.level == 3:
                    cv2.putText(frame, 'Money: '+ str(self.bear.getHavingPoint()), (700, 30),
                                    cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), thickness=3)
                else :
                    cv2.putText(frame, 'Points: ' + str(self.bear.getHavingPoint()), (700, 30),
                                    cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), thickness=3)
                cv2.imshow('PlayGame', frame)
                if cv2.waitKey(1) & 0xff == ord('q'):
                    break
        return message

    def run(self):
        message = ''
        while True:
            frame = self.copy.copy()
            if len(self.cards) < 30 and random.randint(0, 100) > 98:
                self.generateHoney()

            self.bear.calPosition()
            self.bee.calPosition()
            self.collisionWatcher.watch()
            if self.collisionWatcher.collideEnemy():
                message = self.gameOver()
                break
            else:
                for card in self.cards:
                    self.drawItem(frame, card)

                self.drawItem(frame, self.bee)
                self.drawItem(frame, self.bear)

                if self.level == 3:
                    cv2.putText(frame, '¥ '+ str(self.bear.getHavingPoint()), (700, 30),
                                    cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), thickness=3)
                else :
                    cv2.putText(frame, 'Points: ' + str(self.bear.getHavingPoint()), (700, 30),
                                    cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), thickness=3)
                cv2.imshow('PlayGame', frame)
                if cv2.waitKey(5) & 0xff == ord('q'):
                    break
        return message
Beispiel #19
0
class PlayBall:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        # Set the window size and title bar text
        # Windowed
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        # Full screen
        # self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        # self.settings.screen_width = self.screen.get_rect().width
        # self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Play Ball!")

        # Create an instance to store game statistics.
        self.stats = GameStats(self)

        self.bear = Bear(self)
        self.balls = pygame.sprite.Group()
        self.dog = Dog(self)

        # Make the Play button.
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.bear.update()
                self._update_balls()
                self._update_dog()

            self._update_screen()

    def _update_dog(self):
        """Respond appropriately if the dog has reached an edge."""
        dog_direction = self.settings.dog_direction
        if self.dog.check_edges():
            dog_direction *= -1
        self.dog.update(dog_direction)

    def _update_balls(self):
        # Update ball positions.
        self.balls.update()

        # Get rid of balls that have disappeared.
        for ball in self.balls.copy():
            if ball.rect.left >= self.settings.screen_width:
                self.balls.remove(ball)
                self._ball_missed()

        self._check_ball_dog_collisions()

    def _check_ball_dog_collisions(self):
        """Respond to ball-dog collisions."""
        # When the ball reaches the dog, remove ball and dog and celebrate.
        if pygame.sprite.spritecollideany(self.dog, self.balls):
            self.balls.remove(ball)

        # Celebrate

    def _ball_missed(self):
        """Respond to ball misses."""
        if self.stats.balls_left > 0:
            #Decrement balls_left.
            self.stats.balls_left -= 1
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_events(self):
        """Respond to key presses and mouse events."""
        # Gracefully exit when 'X' or alt+F4 close the window
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                # sys.exit() - in text, but does not close gracefully
                # respond to other key presses
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            self._start_game()

    def _start_game(self):
        """Start a new game."""
        # Reset the game statistics.
        self.stats.reset_stats()
        self.stats.game_active = True

        # Get rid of remaining balls.
        self.balls.empty()

        # Create a new dog and center the bear.
        self.dog.center_dog()
        self.bear.center_bear()

        # Hide the mouse pointer.
        pygame.mouse.set_visible(False)

    def _check_keydown_events(self, event):
        """Respond to key presses."""
        if event.key == pygame.K_DOWN:
            self.bear.moving_down = True
        elif event.key == pygame.K_UP:
            self.bear.moving_up = True
        elif event.key == pygame.K_q:
            pygame.quit()
        elif event.key == pygame.K_ESCAPE:
            pygame.quit()
        elif event.key == pygame.K_p:
            self._start_game()
        elif event.key == pygame.K_SPACE:
            self._throw_ball()

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_DOWN:
            self.bear.moving_down = False
        elif event.key == pygame.K_UP:
            self.bear.moving_up = False

    def _throw_ball(self):
        """Create a new ball and toss it to the dog."""
        if len(self.balls) < self.settings.balls_allowed:
            new_ball = Ball(self)
            self.balls.add(new_ball)

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        self.screen.fill(self.settings.bg_color)
        self.bear.blitme()
        self.dog.blitme()
        for ball in self.balls.sprites():
            ball.draw_ball()

        # Draw the Play button if the game is inactive.
        if not self.stats.game_active:
            self.play_button.draw_button()

        # Make the most recently drawn screen visible.
        pygame.display.flip()
Beispiel #20
0
 def __init__(self, hours, first_fish_size):
     # Generate the correct number of salmon
     self._salmons = [Salmon() for i in range(hours)]
     self._bear = Bear(first_fish_size)
Beispiel #21
0
 def generate_bear(self, bear_type):
     return Bear(
         bear_type=bear_type,
         bear_name=self.generate_random_str(),
         bear_age=round(random.uniform(1, 50), 1),
     )