コード例 #1
0
ファイル: total.py プロジェクト: bkh4149/aocchi
def main():
    #召喚
    m1 = monster.Monster(4, 1)
    m2 = monster.Monster(4, 5)
    m3 = monster.Monster(7, 5)
    mons = [m1, m2, m3]
    f1 = fish.Fish(9, 2)  #魚召喚
    p1 = player.Player()
    map1 = field.map()  # map召喚

    #ゲーム全体のモードのコントロール
    mode = 0
    opening.main()
    while True:
        if mode == 0:  #野
            mode, id = field.main(p1, mons, f1, map1)  #フィールドでの流れ
        elif mode == 3:  #街ナカ
            mode = town.main(p1)  #街ナカ
        elif mode == 10:  #バトル
            m1 = mons[id]
            print("モンスター出現!!  hp", m1.hp, " 攻撃力", m1.at, "  防御力", m1.df)
            flag = battle.battle(p1, m1)  #戦闘シーン
            if flag == 1:  #モンスターをやっつけた
                mons.pop(id)
                mode = 0  #野
            elif flag == 2:  #プレイヤが死んだらゲームオーバー
                print("game over")
                return
            elif flag == 3:  #プレイヤが逃げ出した
                mode = 0  #野
コード例 #2
0
ファイル: game.py プロジェクト: matthewkayin/summerjam2019
    def game_init(self, room_count):
        self.player = fish.Fish()
        self.room_count = room_count
        self.level_one = room.MapMaker(0, 0, self.room_count)
        self.enemies = []
        num_eels = 0
        for i in range(0, len(self.level_one.rooms)):
            for j in range(0, len(self.level_one.rooms[i].eels)):
                new_eel = eel.Eel()
                self.enemies.append(new_eel)
                self.enemies[num_eels].spawn(
                    self.level_one.rooms[i].eels[j][0],
                    self.level_one.rooms[i].eels[j][1],
                    self.level_one.rooms[i].eels[j][2])
                self.enemies[num_eels].room = i
                num_eels += 1

        self.player_room = [0, 0]
        self.player_safe = [self.player.x, self.player.y]

        self.floor_tiles = []
        far_left = 0
        far_right = 0
        far_top = 0
        far_bot = 0
        for curr_room in self.level_one.rooms:
            if curr_room.x_cord < far_left:
                far_left = curr_room.x_cord
            elif curr_room.x_cord + self.SCREEN_WIDTH > far_right:
                far_right = curr_room.x_cord + self.SCREEN_WIDTH
            if curr_room.y_cord < far_top:
                far_top = curr_room.y_cord
            elif curr_room.y_cord + self.SCREEN_HEIGHT > far_bot:
                far_bot = curr_room.y_cord + self.SCREEN_HEIGHT
        no_x_tiles = int(abs(far_left - far_right) / 640) + 2
        no_y_tiles = int(math.ceil(abs(far_top - far_bot) / 640)) + 2
        far_left -= 640
        far_top -= 640
        for x in range(0, no_x_tiles):
            for y in range(0, no_y_tiles):
                self.floor_tiles.append(
                    [far_left + (640 * x), far_top + (640 * y)])

        self.minnow_tick = 0
        self.minnow_MAX = 10
        self.minnow_frame = 0
        self.minnow_MFRAME = 17

        self.eel_sfreq = 120
        self.eel_SMAX = 60 * 7

        self.time_left = self.room_count * 45
        self.time_left_text = self.medfont.render(
            "Reach the pearl before time runs out! Time left: " +
            str(self.time_left), False, self.YELLOW)
コード例 #3
0
def sp_helper_fun():
    """
    Reuse the beautifully constructed core functionality in a helper
    function for the other sp500 functions to allow an output to a
    ``.csv`` or to a :class:`pandas.Series`
    """
    ############################
    # Show the progress fish to user
    fish.Fish()

    url = 'http://en.wikipedia.org/wiki/List_of_S&P_500_companies'
    soup = bs4.BeautifulSoup(urllib2.urlopen(url))

    #currently, all the data is stored in <table class="wikitable sortable">
    table = soup.find('table', {'class': 'wikitable sortable'})
    rows = []
    for row in table.find_all('tr'):
        rows.append([val.text.encode('utf8') for val in row.find_all('td')])

    dataTable = pandas.DataFrame(rows)
    tickers = dataTable[0]
    return tickers
コード例 #4
0
ファイル: fishing.py プロジェクト: OllyCat/funny-fishing
    def run(self):
        # попросим поймать начальную букву
        self.games_sounds.play_startchar(self.big_char)

        # обновляем крючок
        self.FishHook.update(pygame.mouse.get_pos())

        # получаем позицию мыши
        self.x, self.y = pygame.mouse.get_pos()

        # основной цикл
        while True:
            # устанавливаем флаг поимки в False
            self.catch = False

            # опрос очереди событий
            self.check_events()

            # прорисовываем море
            self.Sea.update()

            # в цикле обновляем всех рыб
            for j in self.fishes.__reversed__():
                # рыбе передаем позицию курсора и флаг поимки, получаем False, если не поймана, или True, если поймана
                ret = j.update(self.x, self.y)

            # обновляем крючок и леску
            self.FishHook.update((self.x, self.y))

            # обновляем дисплей
            pygame.display.update()

            # обнаруживаем пересечение объектов, если при этом стоит флаг поимки и
            # буква рыбы совпадает с искомой буквой, то рыба поймана, если не
            # совпадает - то не поймана и разворачивается
            fish_index = self.FishHook.rect.collidelist(
                list(map(lambda x: x.rect, self.fishes)))
            if self.catch and fish_index >= 0:
                if self.fishes[fish_index].get_char() == self.catch:
                    self.u_bar.update(self.catch)
                    self.catch = False
                    new_char = self.u_bar.get_curchar()
                    self.fishes[fish_index].show_fish()
                    cached_fish = self.fishes.pop(fish_index)
                    self.games_sounds.play_success(self.big_char)
                    self.catch_success()
                    self.fishes.append(
                        fish.Fish(
                            self.screen, self.SEA_RECT,
                            os.path.join("data",
                                         random.choice(self.fish_pics)),
                            self.big_char, self.u_bar, self.deck))
                    if new_char != self.big_char:
                        self.big_char = new_char
                        self.games_sounds.play_startchar(self.big_char)
                else:
                    self.fishes[fish_index].set_reverse()
                    self.catch_fail(fish_index)

            # вызываем смену трека
            self.games_sounds.play_music()

            # отсчитываем тики для задержки
            self.clock.tick(50)
        return
コード例 #5
0
ファイル: fishing.py プロジェクト: OllyCat/funny-fishing
    def __init__(self):
        # базовые размеры экрана, бара и "моря"
        self.SCREEN_RECT = pygame.Rect((0, 0), (1024, 768))
        self.BAR_RECT = pygame.Rect((0, 0), (self.SCREEN_RECT.w, 60))
        self.SEA_RECT = pygame.Rect(
            (0, self.BAR_RECT.h),
            (self.SCREEN_RECT.w, self.SCREEN_RECT.h - self.BAR_RECT.h))

        # инициализация pygame
        pygame.init()
        # устанавливаем заголовок
        pygame.display.set_caption("Весёлая рыбалка")
        # создаем окно
        self.screen = pygame.display.set_mode(
            (self.SCREEN_RECT.w, self.SCREEN_RECT.h), HWSURFACE | DOUBLEBUF)

        # массив рыб
        self.fishes = []
        # заполняем список файлов рыб
        data_dir = os.listdir("data")
        # выбираем только файлы рыб
        self.fish_pics = re.findall("fish\d\d.png", ''.join(data_dir))
        if len(self.fish_pics) == 0:
            print("Error! Fish pics not found!")
            sys.exit(255)

        # создаём колоду
        self.deck = deck.Deck()

        # создаем верхний бар
        self.u_bar = ubar.UBar(self.screen, self.BAR_RECT, self.deck)
        self.u_bar.draw()

        # загружаем звуки
        self.games_sounds = sound.Sound()
        # включаем музыку
        self.games_sounds.play_music()

        # буква за которой охотимся
        self.big_char = self.u_bar.get_curchar()

        # создаем море
        self.Sea = sea.Sea(self.screen, self.SEA_RECT)

        # создаем крючок и леску
        self.FishHook = hook.FishHook(self.screen, self.SEA_RECT)

        # таймер
        self.clock = pygame.time.Clock()

        # инициализируем джойстик, если есть
        if pygame.joystick.get_count() > 0:
            joy = pygame.joystick.Joystick(0)
            joy.init()

        # заполняем массив рыбами передавая путь до файлов
        for i in range(3):
            self.fishes.append(
                fish.Fish(self.screen, self.SEA_RECT,
                          os.path.join("data", random.choice(self.fish_pics)),
                          self.big_char, self.u_bar, self.deck))
コード例 #6
0
def main():
    try:
        with open('pets.csv', 'r') as f:
            reader = csv.reader(f)
            your_list = list(reader)
            for i in range(0, len(your_list)):
                if your_list[i][0] == 'Dog':
                    d = dog.Dog(your_list[i][1], your_list[i][2], your_list[i][3],your_list[i][4])
                    name_list.append(d.name)
                elif your_list[i][0] == 'Cat':
                    c = cat.Cat(your_list[i][1], your_list[i][2], your_list[i][3], your_list[i][4])
                    name_list.append(c.name)
                elif your_list[i][0] == 'Fish':
                    f = fish.Fish(your_list[i][1], your_list[i][2], your_list[i][3], your_list[i][4])
                    name_list.append(f.name)
                elif your_list[i][0] == 'Bird':
                    b = bird.Bird(your_list[i][1], your_list[i][2], your_list[i][3], your_list[i][4])
                    name_list.append(b.name)


        # Show only pets of a certain type # Based on the user input, show only the pets that are dogs/cats/fish/birds.
        def animal_type(enter):
            for i in range(0, len(your_list)):
                if your_list[i][0] == enter.title():
                    print('-', your_list[i][3])
            return ''


        # Search for a Pet -
        # you will call your own binary search function to search for the first pet name that matches the user entered string.
        # If a pet is found in the list, then print all the details for that pet and the index in the list where it was found.
        # If the pet is not in the list, then print a message informing the user that the pet is not in the list.
        def search(enter):
            low = 0
            high = len(your_list)-1
            insertion_sort_name(your_list)
            while low <= high:
                mid = int((low + high) / 2)
                if ' ' + enter.title() == your_list[mid][1]:
                    print("The index is " + str(mid) + " in the list.")
                    return your_list[mid]
                elif ' ' + enter.title() < str(your_list[mid][1]):
                    high = mid - 1
                else:  # enter > your_list[mid]
                    low = mid + 1
            return 'The pet is not in the list.'


        # Sort list based on pet name -
        # For all the sort options you can implement either selection sort or insertion sort on the list of pet objects.
        # After sorting the list, display the sorted list.
        def insertion_sort_name(list):
            keyIndex = 1
            while keyIndex < len(list):
                insert_nameorder(list, keyIndex)
                keyIndex += 1

        def insert_nameorder(list, keyIndex):
            key = list[keyIndex][1]
            j = keyIndex -1
            while (list[j][1] >= key) and (j >= 0):
                list[j + 1][1] = list[j][1]
                j -= 1
                list[j + 1][1] = key


        # Sort list based on pet color - After sorting the list, display the sorted list.
        def insertion_sort_color(list):
            keyIndex = 1
            while keyIndex < len(list):
                insert_colororder(list, keyIndex)
                keyIndex += 1

        def insert_colororder(list, keyIndex):
            key = list[keyIndex][4]
            j = keyIndex - 1
            while (list[j][4] >= key) and (j >= 0):
                list[j + 1][4] = list[j][4]
                j -= 1
                list[j + 1][4] = key

        print('Your Pet Finder menu: ')
        print('===========================')
        enter1 = 0
        while enter1 != 6:
            print('1. Display the names of all the pets.')
            print('2. Certain types of pets.')
            print('3. Search for a Pet.')
            print('4. Sort list based on pet name.')
            print('5. Sort list based on pet color.')
            print('6. Exit the program.')

            enter1 = float(input('Enter your choice: '))
            if enter1 == 1:
                # Print only the names of all the pets
                print('Here are the names of pets:')
                print(name_list)
                print('')
            elif enter1 == 2:
                enter2 = input('What kind of pet would you like to see (dog/cat/fish/bird): ')
                print(animal_type(enter2))
            elif enter1 == 3:
                enter3 = input('Search pet name: ')
                print(search(enter3))
                print('')
            elif enter1 == 4:
                insertion_sort_name(your_list)
                print('Sorted list: ', your_list)
                print('')
            elif enter1 == 5:
                insertion_sort_color(your_list)
                print('Sorted list: ', your_list)
                print('')
            elif enter1 == 6:
                exit()
            else:
                print('Invalid value.')
    except IOError:
        print('An error occurred trying to read')
        print('Non-numeric data is allowed.')
        print('Your Pet Finder menu: ')
        print('===========================')
        print('1. Display the names of all the pets.')
        print('2. Certain types of pets.')
        print('3. Search for a Pet.')
        print('4. Sort list based on pet name.')
        print('5. Sort list based on pet color.')
        print('6. Exit the program.')
        enter1 = float(input('Enter your choice: '))
    except ValueError:
        print('Non-numeric data is allowed.')
        print('Your Pet Finder menu: ')
        print('===========================')
        print('1. Display the names of all the pets.')
        print('2. Certain types of pets.')
        print('3. Search for a Pet.')
        print('4. Sort list based on pet name.')
        print('5. Sort list based on pet color.')
        print('6. Exit the program.')
        enter1 = float(input('Enter your choice: '))
    except Exception as err:
        print(err)
        print('Non-numeric data is allowed.')
        print('Your Pet Finder menu: ')
        print('===========================')
        print('1. Display the names of all the pets.')
        print('2. Certain types of pets.')
        print('3. Search for a Pet.')
        print('4. Sort list based on pet name.')
        print('5. Sort list based on pet color.')
        print('6. Exit the program.')
        enter1 = float(input('Enter your choice: '))
コード例 #7
0
ファイル: zoo.py プロジェクト: yuliiahrabar/Python_Lista11
def create_Fish(name, age, height, weight, type_of_fins, type_of_water):
    """Tworzy obiekt klasy Fish"""
    return fish.Fish(name, age, height, weight, type_of_fins, type_of_water)
コード例 #8
0
def adj_close(interface_filename='get_stocks_for_tsr.xlsx',
              assumptions_first_row=4,
              ticker_first_row=8,
              assumptions_columns='B:C',
              ticker_columns='C'):
    """
    Given a Vaulation Date, Lookback Period and a list of tickers, this function will output a matrix of adjusted daily close stock 
    price data for each ticker provided, as well as the annualised volatility of the log returns of each ticker. 
    
    All user inputs are entered via the interface file
        
        default interface_filename:  get_stock_data.xlsx
        sheet name: Assumptions
        
            |   A   |           B               |       C           |
        --------------------------------------------------------------------------
        1   |       |                           |                   |
        2   |       |                           |                   |
        3   |       |                           |                   |
        4   |       |   Valuation Date          |   MM/DD/YYYY  |
        5   |       |   Lookback Period (years) |   3               |
        6   |       |                           |                   |
        7   |       |                           |   Tickers         |
                                                    ----------------
        8   |       |                       1   |   A               |
        9   |       |                       2   |   AA              |
        10  |       |                       3   |   AAPL            |       
        :                                   :       :
    
    :ARGS:
    
        interface_filename: :meth:`str` The name of the excel interface file. The default name is <get_stock_data.xlsx>
    
        assumptions_first_row :meth: `int` The first row in the excel interface of input data. Do not change from the default 
        value unless the interface file has been modified
        
        ticker_first_row  :meth: `int` The first row in the excel interface of ticker data. Do not change from the default 
        value unless the interface file has been modified
        
         assumptions_columns :meth:`str` A string showing the columns within the excel interface file holding the general
         assumptions. Do not change from the default value unless the interface file has been modified
         
         ticker_columns  :meth:`str` A string showing the column within the excel interface file holding the tickers. Do not
         change from the default value unless the interface file has been modified
    
    :RETURNS:
    
    The function will add 3 new sheets to the existing interface file
    
    1.  Adj Close data:     Adjusted close daily stock price data over the 
                        specified period for all tickers
    2.  Volatility:     The volatility of every ticker
    3.  No Data:        A list of tickers that do not have any stock price 
                        history over specified period 
    
    .. warning:: Requires Internet Connectivity
    
    Because the function calls the `Yahoo! API <http://www.finance.yahoo.com>`_
    internet connectivity is required for the function to work
    """

    ############################
    # Show the progress fish to user
    fish.Fish()

    ############################
    #read general assumptions from the interfacefile
    assumptions = pandas.read_excel(interface_filename,
                                    'Assumptions',
                                    skiprows=assumptions_first_row - 2,
                                    index_col=0,
                                    parse_cols=assumption_columns)

    val_date = assumptions.ix['Valuation Date', 0]
    val_date = pandas.Timestamp(val_date)  #cast date to Pandas timestamp

    lookback_period = assumptions.ix['Lookback Period (years)', 0]
    lookback_date = val_date - datetime.timedelta(days=365.25 *
                                                  lookback_period)
    lookback_date = pandas.Timestamp(
        lookback_date)  #cast date to Pandas timestamp for consistency

    ############################
    #get list of tickers from the interface file
    ticker_data = pandas.read_excel(filename,
                                    'Assumptions',
                                    skiprows=ticker_first_row - 2,
                                    parse_cols=ticker_columns)
    ticker_data = ticker_data[ticker_data.Tickers.notnull(
    )]  # remove rows that do not contain tickers

    ############################
    # Download adjusted stock price data directly from Yahoo! API
    stock_dict = {}
    no_data = []
    for ticker in ticker_data.Tickers:
        # make sure the selected ticker has stock data over the specified period, if not display a message and exclude the ticker
        try:
            stock_dict[ticker] = pandas.io.data.DataReader(
                ticker, "yahoo", lookback_date, val_date)['Adj Close']
        except IOError:
            print "Ticker %s has no data between %s and %s" % (
                ticker, lookback_date, val_date)
            no_data.append(ticker)

    stock_data = pandas.DataFrame(stock_dict)
    no_data = pandas.DataFrame({'Ticker': no_data})

    ############################
    # Get volatilities
    log_returns = stock_data.apply(numpy.log).diff(
    )  #calculate log returns of daily adjustced close prices
    sigma = log_returns.apply(numpy.std) * numpy.sqrt(252)
    sigma = pandas.DataFrame({'Volatility': sigma})

    ##############
    # Export to excel
    book = openpyxl.load_workbook(interface_filename)  # open excel workbook

    needed_worksheets = []  # Remove old data from previous runs
    for sheets in book.worksheets:
        if sheets.title != 'Adj Close data' and sheets.title != 'Volatility' and sheets.title != 'No Data':
            needed_worksheets.append(sheets)
    book.worksheets = needed_worksheets

    writer = pandas.ExcelWriter(interface_filename)
    writer.book = book  # Give ExcelWriter needed worksheets

    stock_data.to_excel(
        writer, 'Adj Close data')  # add new worksheets with current data
    sigma.to_excel(writer, 'Volatility')
    no_data.to_excel(writer, 'No Data')
    writer.save()
コード例 #9
0
import fish

fish_sample = fish.Fish('silver', 'silver fish', 'Pacific', 70)

fish_sample.data_output()
コード例 #10
0
def main():

    list = []

    with open('pets.csv', 'r', newline='') as mycsvfile:

        thedatareader = csv.reader(mycsvfile, delimiter=',', quotechar=',')

        for row in thedatareader:

            if 'Dog' == row[0]:
                writedog = dog.Dog(row[0], row[1], row[2], row[3], row[4])
                list.append(writedog)
            if 'Cat' == row[0]:
                writecat = cat.Cat(row[0], row[1], row[2], row[3], row[4])
                list.append(writecat)
            if 'Fish' == row[0]:
                writefish = fish.Fish(row[0], row[1], row[2], row[3], row[4])
                list.append(writefish)
            if 'Bird' == row[0]:
                writebird = bird.Bird(row[0], row[1], row[2], row[3], row[4])
                list.append(writebird)

    option = 0

    #this displays the menu until the user chooses to exit
    while option != 6:

        print("1. Print only the names of all the pets")
        print("2. Show only pets of a certain type")
        print("3. Search for a pet")
        print("4. Sort the list based on the pet name")
        print("5. Sort list based on pet color")
        print("6. Exit the program")

        option = float(input("Pick your option from 1-6: "))

        while option < 1 or option > 6:

            option = float(
                input(
                    "That was an incorrect option. Pick a valid option from 1-6: "
                ))

        if option == 1:
            print(printnames(list))

        elif option == 2:
            petlist = []
            showpets(list, petlist)

            for item in petlist:
                print(item)

        elif option == 3:
            print(searchpets(list))

        elif option == 4:
            newlist = list
            sortname(list, newlist)

            for item in newlist:
                print(item)

        elif option == 5:
            newlist = list
            sortcolor(list, newlist)

            for item in newlist:
                print(item)
    else:
        exit(0)
コード例 #11
0
ファイル: test_fish.py プロジェクト: seun-beta/Unit-Testing
 def setUp(self):
     print('setUp')
     self.fish_1 = fish.Fish('Jake')
     self.fish_2 = fish.Fish('Vanessa')