Пример #1
0
 def handle_mouse_events(self, mouse):
     for tower in self.world.towers:
         if tower.pressed(mouse) and self.world.current_tower_type == tower.type and not self.world.put_mine:
             if self.is_enough_money(self.world.upgrade_cost, self.gamer) and tower.can_be_upgraded():
                 self.gamer.money -= self.world.upgrade_cost
                 tower.upgrade()
             else:
                 pass
                 #printCostMessage()
     for cell in self.world.tower_places:
         if cell.pressed(mouse) and not self.world.put_mine:
             if self.is_enough_money(self.world.buy_cost, self.gamer):
                 self.gamer.money -= self.world.buy_cost
                 self.world.tower_places.remove(cell)
                 self.world.towers.append(Tower(cell.x, cell.y, self.world.current_tower_type))
             else:
                 pass
                 #printCostMessage()
     if self.world.put_mine:
         inter = False
         mine = Mine((mouse[0] // 32) * 32, (mouse[1] // 32) * 32)
         for tower in self.world.towers:
             if mine.intersects(tower):
                 inter = True
         for creep in self.world.creeps:
             if mine.intersects(creep):
                 inter = True
         for tow_pl in self.world.tower_places:
             if mine.intersects(tow_pl):
                 inter = True
         if not inter:
             if self.is_enough_money(20, self.gamer):
                 self.world.mines.append(mine)
                 self.gamer.money -= 20
             self.world.put_mine = False
 def __init__(self, window, width, height, mine_count):
     self.window = window
     self.width = width
     self.height = height
     self.mine_count = mine_count
     mine = Mine(self.width, self.height, self.mine_count)
     self.mine_list = mine.create_mine_list()
     self.mine_count_nearby_button_double_list = mine.create_mine_count_nearby_button_double_list(
         self.mine_list)
Пример #3
0
    def __init__(self, game_map, task=TASKS.MINE):
        self.user_interface = UserInterface()
        self.backpack = Backpack()
        self.mine = Mine(self, game_map)
        self.smelt = Smelt(self, game_map)
        self.forge = Forge(self, game_map)

        # Set the default initial task
        self.task = task
        self.action_count = 0
Пример #4
0
def spawn_mines(mines, screen):
    y = randint(100, 700)
    new_y = y
    x = 1500
    new_mine = Mine(screen, x, y)
    mines.add(new_mine)

    for numbers in range(0, 4):
        new_y += 50
        new_mine = Mine(screen, x, new_y)
        mines.add(new_mine)
        if new_y > 1400 or new_y < 0:
            new_y = y
            x += 100
Пример #5
0
    def spawn_enemies(self):
        spawns = self.level.get_spawns()
        if spawns[Level.SHARKS]:
            # Make a new shark
            self.sharks.append(Shark())
            self.shark_sprites.add(self.sharks[-1])

        if spawns[Level.PIRATES]:
            # Make a new pirate ship
            self.pirates.append(Pirateboat())
            self.pirate_sprites.add(self.pirates[-1])

        if spawns[Level.MINES]:
            self.mines.append(Mine())
            self.mine_sprites.add(self.mines[-1])

        if spawns[Level.SEAGULLS]:
            self.seagulls.append(Seagull())
            self.seagull_sprites.add(self.seagulls[-1])

        if spawns[Level.TITANIC]:
            self.titanic = Titanic()
            self.titanic_sprite.add(self.titanic)

        if spawns[Level.POWERUPS]:
            self.powerups.append(Powerup())
            self.powerup_sprites.add(self.powerups[-1])
Пример #6
0
    def board_select(self, *args):
        self.horizontal, self.vertical = map(int, args)
        mine = Mine(self.horizontal, self.vertical, self.level)
        self.board = map(int, mine.board.reshape(1, self.horizontal * self.vertical)[0])
        self.bomb_count = len(filter(lambda x: x == -1, self.board))
        self.switch_screen(screen='board_screen')

        self.current_screen.board.clear_widgets()
        self.prepare_board()
Пример #7
0
 def open(self, directory):
     '''Opens new map'''
     self.bullets.empty()
     self.enemies.empty()
     #self.ship.position = self.position
     with open(directory) as location:
         for line in location.readlines():
             data = line.split()
             if data[0] == 'mine':
                 self.enemies.add(Mine(self.screen,
                     Vector(int(data[1]), int(data[2])), self.ship))
Пример #8
0
 def test_creeps_after_mines(self):
     with patch('application.Application') as perm_mock:
         perm_mock.game_engine = None
     cells = Unity.identifier(self.labyrinth)[0]
     way = deque(cells)
     pos = way[3]
     game_state = GameState(perm_mock)
     creep = Creep(pos[0], pos[1], way, 1)
     mine = Mine(pos[0], pos[1])
     game_state.world.mines.append(mine)
     game_state.world.creeps.append(creep)
     game_state.blast_and_kill(creep, game_state.world, game_state.gamer)
     self.assertEqual(len(game_state.world.creeps), 1)
Пример #9
0
 def init__window(self):
     lb.create_table()  #creates the leaderboard for the first time only
     self.master.title("Minesweeper")
     self.pack(fill=BOTH, expand=1)
     count = 0  #counts the mines
     self.scoreBoard = Label(self,
                             text='Your Score: ' +
                             str(self.openBoxes))  # creates the scoreboard
     self.scoreBoard.grid(row=0, column=int(1),
                          columnspan=2)  # places the score
     self.highScore = Label(
         self, text='Highest Score: ' +
         str(lb.get_high_score()))  # displays the highest score
     self.highScore.grid(row=0, column=int(4),
                         columnspan=2)  # places the score
     #assigns the bombs to the randomly selected mines and places the mines on the map
     for x in range(1, len(self.mineField)):
         for y in range(len(self.mineField[x])):
             if self.mineField[x][y] == "X":
                 mine = Mine(self,
                             text="",
                             font=20,
                             width=4,
                             command=lambda bomb=True, order=count, result=
                             str(self.mineField[x][y]): self.find_bomb(
                                 bomb, order, result))  #create mine
                 mine.xpos = x
                 mine.ypos = y
                 self.mines.append(mine)
             else:
                 mine = Mine(self,
                             text="",
                             font=20,
                             width=4,
                             command=lambda bomb=False, order=count, result=
                             str(self.mineField[x][y]): self.find_bomb(
                                 bomb, order, result))  #create mine
                 mine.xpos = x
                 mine.ypos = y
                 self.mines.append(mine)
             self.mines[count].grid(row=x, column=y)
             count = count + 1
     self.board = Button(self, text="Leader Board", command=self.show_board)
     self.board.grid(row=x + 1, column=3, columnspan=2)
Пример #10
0
def run_game():
    # Initialize pygame and screen
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption("2Dverse")

    # Create ship and groups for bullets, enemies and obstacles
    ship = Ship(screen)
    bullets = Group()
    enemies = Group()
    obstacles = Group()
    mine = Mine(screen, Vector(40, 40), ship)

    # Main game loop
    while True:

        gf.check_events(settings, screen, ship, bullets)
        gf.update_objects(ship, bullets, screen, mine)
        gf.draw_screen(settings, screen, ship, bullets, mine)
Пример #11
0
def play(current_level, message=""):
    levers = []
    doors = []
    multi_levers = []
    multi_doors = []
    monsters = []
    mines = []
    data_holder = MapDataHolder(levers, doors, multi_levers, multi_doors,
                                monsters, mines)

    if message == "":
        message = "Level " + str(current_level) + "/" + str(level_number)
    else:
        message += "\nLevel " + str(current_level) + "/" + str(level_number)

    if current_level == 1:
        message += " ('h' for help)"

    with open("Maps/" + str(current_level) + ".map") as file:
        mapList = [[tileForChar(char) for char in list(line.rstrip())]
                   for line in file]  # Reference [y, x]

    height = len(mapList)
    width = len(mapList[0])

    # Read data
    player = Player(Point2D(0, 0))
    with open("Maps/" + str(current_level) + ".dat") as file:
        lines = [line.rstrip('\n') for line in file]
        for line in lines:
            # Player
            if line.startswith("player"):
                numbers = line.split('=')[1]
                split = numbers.split(',')
                first = split[0]
                second = split[1]
                player.location = Point2D(int(first), int(second))
            elif line.startswith(
                    "monster"):  # monster.1-2;1:ground=5,3 # id, mf, speed
                numbers = line.split('=')[1]
                split = numbers.split(',')
                x = int(split[0])
                y = int(split[1])
                id = int(line.split('-')[0].split('.')[1])
                moveFrequency = int(line.split(';')[0].split('-')[1])
                speed = int(line.split(':')[0].split(';')[1])
                isFlying = 0
                isFlyingString = line.split('=')[0].split(':')[1]
                if isFlyingString == "fly":
                    isFlying = True
                elif isFlyingString == "ground":
                    isFlying = False
                data_holder.monsters.append(
                    Monster(Point2D(x, y), speed, moveFrequency, isFlying, id,
                            MONSTER_CHAR))
            elif line.startswith("mine"):
                numbers = line.split('=')[1]
                split = numbers.split(',')
                first = int(split[0])
                second = int(split[1])
                data_holder.mines.append(
                    Mine(Point2D(first, second), MINE_CHAR))
            elif line.startswith("lever"):  #lever-1=5,5
                values = line.split('=')
                leverNumber = int(values[0].split('-')[1])
                x = int(values[1].split(',')[0])
                y = int(values[1].split(',')[1])
                data_holder.levers.append(
                    Lever(
                        Point2D(x, y), LEVER_CHAR, False,
                        leverNumber))  # The items must be in order in the file
            elif line.startswith("door"):  #door-1=6,4
                values = line.split('=')
                doorNumber = int(values[0].split('-')[1])
                x = int(values[1].split(',')[0])
                y = int(values[1].split(',')[1])
                data_holder.doors.append(
                    Door(Point2D(x, y), doorNumber, isOpen=False))
            elif line.startswith("multi_lever"):
                id = int(line.split('-')[0].split('.')[1])
                number = int(line.split('-')[1].split('=')[0])
                x = int(line.split('=')[1].split(',')[0])
                y = int(line.split('=')[1].split(',')[1])
                data_holder.multi_levers.append(
                    MultiLever(Point2D(x, y), LEVER_CHAR, False, id,
                               number))  # temporary
            elif line.startswith("multi_door"):  # multi_door.1-1+2+3=4,2
                id = int(line.split('-')[0].split('.')[1])
                x = int(line.split('=')[1].split(',')[0])
                y = int(line.split('=')[1].split(',')[1])
                levers_needed = []
                lever_numbers = line.split('-')[1].split('=')[0]
                temp = 0
                for c in lever_numbers:
                    if c == '+':
                        levers_needed.append(temp)
                        temp = 0
                    else:
                        temp += int(c)
                levers_needed.append(temp)
                data_holder.multi_doors.append(
                    MultiDoor(Point2D(x, y), id, levers_needed, isOpen=False))

    # Game loop
    gameRunning = True
    while (gameRunning):
        os.system("clear")
        print(message)
        drawMap(player, mapList, data_holder)
        print("> ")
        ch = getch()
        if ch == 'q':
            gameRunning = False
            quit()
        elif ch == 'k':
            new_level = current_level - 1
            if new_level < 1:
                continue
            else:
                play(current_level - 1)
        elif ch == 'l':  # Skip level
            new_level = current_level + 1
            if new_level > level_number:
                continue
            else:
                play(current_level + 1)
        elif ch == 'h':  # help
            help()
        elif ch == 's':
            playerMovement(0, 1, data_holder, player, mapList, current_level)
        elif ch == 'w':
            playerMovement(0, -1, data_holder, player, mapList, current_level)
        elif ch == 'a':
            playerMovement(-1, 0, data_holder, player, mapList, current_level)
        elif ch == 'd':
            playerMovement(1, 0, data_holder, player, mapList, current_level)

        if isLevelCompleted(mapList, player):
            if current_level == level_number:
                end(player, mapList, data_holder)
            else:
                play(current_level + 1)
Пример #12
0
 def defuse(self, drone):
     """ Defuse the Mine """
     Mine.scan(self, drone)
Пример #13
0
    print(t.get_percentages())

    sleep(1)
    print("\nYOUR TURN (3 rounds)")
    
    # Mining operations
    # NOTE: the video demo mentioned 3 options for your turn
    # For simplicity, we've kept it 1 mining option.
    for i in range(1,4):
        sleep(1)
        print(list(t.get_percentages().keys()))
        r = input("Select one of the above resources to mine ")
        while r not in t.get_percentages().keys():
            r = input("Please choose a valid resource to mine ")
        p = Player(myCountry)
        m = Mine(p, r)
        m.execute(state)
        print("Mine operation successful")
    
    t = Thresholds(state, myCountry)

    sleep(1)
    print("\nYour resource levels:")
    print(t.get_resources())

    sleep(1)
    print("\nYour resource percentages:")
    print(t.get_percentages())

    
    sleep(1)
Пример #14
0
 def defuseCarefully(self, drone):
     """ Defuse the Mine carefully """
     Mine.defuse(self, drone)
Пример #15
0
 def defuseCarefully(self, drone):
     """ Defuse the Mine carefully """
     Mine.defuse(self, drone)
Пример #16
0
    def generateActions(self, world, market):
        actions = []
        untradeable_resources = [
            'R1', 'R4', 'R7', 'R19', 'R21', 'R22', "R1'", "R5'", "R6'", "R18'",
            "R19'", "R20'", "R21'", "R22'", "cash"
        ]
        myResources = world[self.name]
        lowOnCash = myResources["cash"] <= 2000
        # if the agent is low on cash, try to sell a type of resource for
        # cash gain and at the same time mine for the loss
        if lowOnCash:
            bestResourceToMine = ""
            bestPrice = float("-inf")
            # find the resource with the highest selling price
            for ticker in myResources.keys():
                if ticker not in untradeable_resources:
                    sellPrice = market.quotePrice(ticker)["sellingPrice"]
                    if sellPrice > bestPrice:
                        bestResourceToMine = ticker
                        bestPrice = sellPrice
            # if it exists, sell and mine
            if bestResourceToMine:
                quantity = market.getBuyOrders(
                    bestResourceToMine)[0]["quantity"]
                if myResources[bestResourceToMine] < quantity:
                    quantity = myResources[bestResourceToMine] / 2
                transaction = Transaction(
                    self.name, "sell", {
                        bestResourceToMine: [{
                            "quantity": quantity,
                            "strike": bestPrice,
                            "expiration": 2
                        }]
                    }, market)
                actions.append(transaction)
                mine = Mine(self, bestResourceToMine, 2)
                actions.append(mine)
        # generate actions according to the supply and demand
        else:
            cashAmount = myResources["cash"]
            for ticker in myResources.keys():
                if ticker not in untradeable_resources:
                    book = market.getOrders(ticker)
                    buyAmount = 0
                    sellAmount = 0
                    for order in book["bids"]:
                        buyAmount = buyAmount + order["quantity"]
                    for order in book["asks"]:
                        sellAmount = sellAmount + order["quantity"]
                    # if buyers are more than sellers, try to outbid the buyers
                    # in anticipation for the price to go up
                    if buyAmount > sellAmount:
                        bestBid = book["bids"][0]
                        bidPrice = bestBid["strike"]
                        askPrice = float("inf")
                        askQuantity = float("inf")
                        if sellAmount != 0:
                            bestAsk = book["asks"][0]
                            askPrice = bestAsk["strike"]
                            askQuantity = bestAsk["quantity"]
                        myBidPrice = bidPrice + 5
                        if myBidPrice > askPrice:
                            myBidPrice = askPrice

                        quantity = askQuantity
                        if myBidPrice * quantity > cashAmount:
                            quantity = int(cashAmount / 4 / myBidPrice)

                        if quantity != 0:
                            transaction = Transaction(
                                self.name, "buy", {
                                    ticker: [{
                                        "quantity": quantity,
                                        "strike": myBidPrice,
                                        "expiration": 2
                                    }]
                                }, market)
                            cashAmount = cashAmount - myBidPrice * quantity
                            actions.append(transaction)
                    # if buyers are less than sellers, try to undercut the sellers
                    # in anticipation for the price to go down
                    if buyAmount < sellAmount:
                        bestAsk = book["asks"][0]
                        askPrice = bestAsk["strike"]
                        bidPrice = float("-inf")
                        bidQuantity = 0
                        if buyAmount != 0:
                            bestBid = book["bids"][0]
                            bidPrice = bestBid["strike"]
                            bidQuantity = bestBid["quantity"]
                        myAskPrice = askPrice - 5
                        if myAskPrice < bidPrice:
                            myAskPrice = bidPrice
                        if bidQuantity == 0:
                            quantity = int(myResources[ticker] / 20)
                            if quantity != 0:
                                transaction = Transaction(
                                    self.name, "sell", {
                                        ticker: [{
                                            "quantity": quantity,
                                            "strike": myAskPrice,
                                            "expiration": 2
                                        }]
                                    }, market)
                                actions.append(transaction)
                        else:
                            quantity = bidQuantity
                            if myResources[ticker] < quantity:
                                quantity = int(myResources[ticker] / 2)
                            if quantity != 0:
                                transaction = Transaction(
                                    self.name, "sell", {
                                        ticker: [{
                                            "quantity": quantity,
                                            "strike": myAskPrice,
                                            "expiration": 2
                                        }]
                                    }, market)
                                actions.append(transaction)
        return actions
Пример #17
0
 def generateActions(self, world, market):
     finish = False
     actions = []
     untradeable_resources = [
         'R1', 'R4', 'R7', 'R19', 'R21', 'R22', "R1'", "R5'", "R6'", "R18'",
         "R19'", "R20'", "R21'", "R22'", "cash"
     ]
     while not finish:
         print("Awaiting command: ")
         string = str(input())
         tokens = string.split()
         command = tokens[0].lower()
         if command == "buy":
             if len(tokens) < 3:
                 print("Missing parameters")
             else:
                 ticker = tokens[1].upper()
                 if ticker in untradeable_resources:
                     print("Cannot buy " + ticker)
                 else:
                     orders = []
                     for i in range(2, len(tokens)):
                         order = tokens[i].split(",")
                         content = {}
                         strike = float(order[0])
                         content["strike"] = strike
                         quantity = int(order[1])
                         content["quantity"] = quantity
                         if len(order) >= 3:
                             expiration = int(order[2])
                             content["expiration"] = expiration
                         orders.append(content)
                     transaction = Transaction(self.name, "buy",
                                               {ticker: orders}, market)
                     actions.append(transaction)
                     print("Submitted:")
                     print(transaction.toString())
         elif command == "sell":
             if len(tokens) < 3:
                 print("Missing parameters")
             else:
                 ticker = tokens[1].upper()
                 if ticker in untradeable_resources:
                     print("Cannot sell " + ticker)
                 else:
                     orders = []
                     for i in range(2, len(tokens)):
                         order = tokens[i].split(",")
                         content = {}
                         strike = float(order[0])
                         content["strike"] = strike
                         quantity = int(order[1])
                         content["quantity"] = quantity
                         if len(order) >= 3:
                             expiration = int(order[2])
                             content["expiration"] = expiration
                         orders.append(content)
                     transaction = Transaction(self.name, "sell",
                                               {ticker: orders}, market)
                     actions.append(transaction)
                     print("Submitted:")
                     print(transaction.toString())
         elif command == "show":
             if len(tokens) > 1:
                 flag = tokens[1].lower()
                 if flag == "-w":
                     print("World State:", world)
                 elif flag == "-m":
                     market.printOrderBook()
                 elif flag == "-t":
                     if len(tokens) < 3:
                         print("Missing parameters")
                     else:
                         tickers = tokens[2].split(",")
                         for i in range(0, len(tickers)):
                             ticker = tickers[i].upper()
                             print(ticker, market.quotePrice(ticker))
                 elif flag == "-tm":
                     print("housing:", housing)
                     print("alloys:", alloys)
                     print("electronics:", electronics)
                     print("farms:", farms)
                     print("factories:", factories)
                     print("metallic_elements:", metallic_elements)
                     print("timber:", timber)
                     print("plant:", plant)
                 else:
                     print("Illgeal flag")
             else:
                 print("My State:", world[self.name])
         elif command == "mine":
             if len(tokens) < 3:
                 print("missing parameters")
             else:
                 resource = tokens[1].upper()
                 difficulty = int(tokens[2])
                 mine = Mine(self, resource, difficulty)
                 print("Submitted: ", mine.toString())
                 actions.append(mine)
         elif command == "transform":
             if len(tokens) < 3:
                 print("missing parameters")
             else:
                 t = tokens[1].lower()
                 multiplier = int(tokens[2])
                 template = ""
                 if t == "housing":
                     template = housing
                 if t == "alloys":
                     template = alloys
                 if t == "electronics":
                     template = electronics
                 if t == "farms":
                     template = farms
                 if t == "factories":
                     template = factories
                 if t == "metallic_elements":
                     template = metallic_elements
                 if t == "timber":
                     template = timber
                 if t == "plant":
                     template = plant
                 if template:
                     transformation = Transformation(
                         self.name, template, multiplier)
                     print("Submitted: ", transformation.toString())
                     actions.append(transformation)
                 else:
                     print("Illegal template")
         # Congratulations! You have found the easter egg!
         elif command == "greedisgood":
             money = 5000
             if len(tokens) >= 2:
                 money = float(tokens[1])
             world[self.name]["cash"] = world[self.name]["cash"] + money
             print("You gave yourself " + str(money) + " cash. Go crazy!")
         elif command == "end":
             finish = True
         elif command == "help":
             print("Here's a list of the commands: ")
             print("1. show [-w] [-m] [-t (t1,t2,t3...)] [-tm]")
             print(
                 "2. buy (ticker) (strike1,quantity1,[expiration1]) (strike2,quantity2,[expiration2]) ..."
             )
             print(
                 "3. sell (ticker) (strike1,quantity1,[expiration1]) (strike2,quantity2,[expiration2]) ..."
             )
             print("4. mine (resource) (difficulty)")
             print("5. transform (template) (multiplier)")
             print("6. end")
         else:
             print("Illegal command")
         print()
     return actions
Пример #18
0
 def generateActions(self, world, market):
     resources_filename = "resources.xlsx"
     depth_bound = 5
     frontier_max_size = 5
     multiplier = 0.3
     transform_templates = [
         housing, alloys, electronics, farms, factories, metallic_elements,
         timber, plant
     ]
     worldWrapper = WorldWrapper(world, self.name, transform_templates,
                                 resources_filename)
     scheduler = Scheduler(worldWrapper)
     res = scheduler.search(depth_bound, frontier_max_size, multiplier)
     bestSchedule = heapq.heappop(res).getSchedule()
     # below is the wrapper
     table = str.maketrans(dict.fromkeys("()"))
     bestAction = bestSchedule[0][0].translate(table)
     tokens = bestAction.split()
     actions = []
     if tokens[0] == "TRANSFER":
         fromName = tokens[2]
         ticker = tokens[5]
         quantity = int(tokens[6])
         # convert a transfer that brings resource out to a market sell order
         if fromName == self.name:
             price = market.quotePrice(ticker)["sellingPrice"]
             # arbitrarily set the price so that we gain 25% of what we have in cash right now
             if price == float("-inf"):
                 price = world[self.name]["cash"] / 4 / quantity
             transaction = Transaction(
                 self.name, "sell", {
                     ticker: [{
                         "quantity": quantity,
                         "strike": price,
                         "expiration": 2
                     }]
                 }, market)
             actions.append(transaction)
         # convert a transfer that brings resource in to a market buy order
         else:
             price = market.quotePrice(ticker)["buyingPrice"]
             # arbitrarily use 25% of the money to bid for it
             if price == float("inf"):
                 price = world[self.name]["cash"] / 4 / quantity
             # buy as much as possible
             else:
                 quantity = int(world[self.name]["cash"] / price)
             if quantity != 0:
                 transaction = Transaction(
                     self.name, "buy", {
                         ticker: [{
                             "quantity": quantity,
                             "strike": price,
                             "expiration": 2
                         }]
                     }, market)
                 actions.append(transaction)
             # if the country cannot afford to buy it, convert it to a mine action
             else:
                 mine = Mine(self, ticker, 2)
                 actions.append(mine)
     # convert a transform to a transformation
     if tokens[0] == "TRANSFORM":
         tokens = bestAction.split("||")
         inputs = tokens[1].split()
         outputs = tokens[2].split()
         multiplier = int(tokens[3].split())
         template = {}
         template["in"] = {}
         template["out"] = {}
         for i in range(0, len(inputs) / 2):
             template["in"][inputs[i]] = int(inputs[i + 1])
         for i in range(0, len(outputs) / 2):
             template["out"][outputs[i]] = int(outputs[i + 1])
         transformation = Transformation(self.name, template, multiplier)
         actions.append(transformation)
     return actions
Пример #19
0
    def build_mine(self, screen, pad):

        m = Mine(screen, pad, self.width, self.height)

        tribe_population = self.args.miners or random.randint(1, 30)

        tribe_width = int(m.width / (self.args.tribes * 2 - 1))
        for t in range(self.args.tribes):
            new_tribe = random.choice(TRIBE_CLASSES)(t)

            new_tribe.min_x = tribe_width * new_tribe.id * 2
            new_tribe.max_x = tribe_width * (new_tribe.id * 2 + 1) - 1
            new_tribe.color = COLORS[t]
            new_tribe.leader_color = KING_COLORS[t]
            new_tribe.name = (NAMES[t] + ' ' + new_tribe.name).strip()
            m.tribes.append(new_tribe)

            creatures = new_tribe.populate(tribe_population)
            for c in creatures:
                m.add_creature(c)

        #for i in range(miner_count):
        #    tribe = random.choice(m.tribes)
        #    x = random.randint(tribe.min_x, tribe.max_x)

        #    creature = tribe.create_creature(x=x, y=0, tribe=tribe)
        #    m.add_creature(creature)

        for i in range(random.randint(4, 10)):
            hole_size = random.randint(4, 8)
            m.create_cave(random.randint(0, m.width - 1),
                          random.randint(0, m.height - 1), hole_size)

        outcast_tribe = Tribe(-1)
        outcast_tribe.name = 'Outcast'
        saboteur_count = self.args.saboteurs or random.randint(1, 3)
        for i in range(saboteur_count):
            saboteur = Saboteur(random.randint(0, m.width - 1),
                                int(m.height / 2),
                                tribe=outcast_tribe)
            m.add_creature(saboteur)

        wizard_count = self.args.wizards or random.randint(1, 5)
        for i in range(wizard_count):
            wizard = Wizard(
                random.randint(0, m.width - 1),
                random.randint(math.ceil(m.height / 3), m.height - 1))
            m.add_creature(wizard)

    #   def make_explore_action():
    #       return ExploreAction()

    #snake_count = self.args.snakes or random.randint(1, 5)
    #for i in range(snake_count):
    #    tribe = random.choice([t for t in m.tribes if Snake in t.creatures])
    #    x = random.randint(tribe.min_x, tribe.max_x)
    #    snake = Snake(x, 0, tribe=tribe)

    #    snake.default_action = make_explore_action
    #    snake.push_action(ExploreAction())
    #    if snake.has_trait(Contagious):
    #        snake.color = KING_COLORS[tribe.id]
    #    else:
    #        snake.color = tribe.color

#     #     snake = Snake(random.randint(0, m.width - 1), random.randint(math.ceil(m.height / 5), m.height - 1))
#    m.add_creature(snake)

        treasure_count = self.args.treasures or random.randint(1, 10)
        for i in range(treasure_count):
            treasure = Treasure(random.randint(0, m.width - 1),
                                random.randint(10, m.height - 1))
            m.add_item(treasure)
            map_item = Map(random.randint(0, m.width - 1),
                           random.randint(5, m.height - 1), treasure)
            m.add_item(map_item)

    #  for t in m.tribes:
    #      king_count = int(self.args.kings) if self.args.kings is not None else 1
    #      for i in range(king_count):
    #          x = random.randint(t.min_x, t.max_x)
#
#          king = DwarfKing(x, 0, t)
#          king.color = KING_COLORS[t.id]
#          m.add_creature(king)
#
        return m
Пример #20
0
    if index == x:
        print "^^^^^^^^^^^^^^^^^^^^ Cue ", countcue
        countcue -= 1
        index = 0


ryg = CaliforniaQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
cyg = YukonQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
lyg = BrazilQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
qyg = ScotlandQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
eyg = SouthAfricaQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
cuyg = VictoriaQuadraticYieldGenerator(depth=10, max=maxgold, min=0)

logger.event_logger.info("Yield Generators created")

mryg = Mine(ryg, 0.8)
mcyg = Mine(cyg, 0.8)
mlyg = Mine(lyg, 0.8)
mqyg = Mine(qyg, 0.8)
meyg = Mine(eyg, 0.8)
mcuyg = Mine(cuyg, 0.8)

print '\n' + "### Cali ###" + '\n'
mryg.show_mine()

print '\n' + "### Yukon ###" + '\n'
mcyg.show_mine()

print '\n' + "### Brazil ###" + '\n'
mlyg.show_mine()
Пример #21
0
    index += 1
    if index == x:
        print "^^^^^^^^^^^^^^^^^^^^ Cue ", countcue
        countcue -= 1
        index = 0

ryg = CaliforniaQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
cyg = YukonQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
lyg = BrazilQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
qyg = ScotlandQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
eyg = SouthAfricaQuadraticYieldGenerator(depth=10, max=maxgold, min=0)
cuyg = VictoriaQuadraticYieldGenerator(depth=10, max=maxgold, min=0)

logger.event_logger.info("Yield Generators created")

mryg = Mine(ryg, 0.8)
mcyg = Mine(cyg, 0.8)
mlyg = Mine(lyg, 0.8)
mqyg = Mine(qyg, 0.8)
meyg = Mine(eyg, 0.8)
mcuyg = Mine(cuyg, 0.8)

print '\n' + "### Cali ###" + '\n'
mryg.show_mine()

print '\n' + "### Yukon ###" + '\n'
mcyg.show_mine()

print '\n' + "### Brazil ###" + '\n'
mlyg.show_mine()
Пример #22
0
class Player():
    """
        This class handles everything relating to the player
        """
    LOW_HEALTH = 150
    TASKS = Enum('Task', 'MINE, SMELT, FORGE')

    def __init__(self, game_map, task=TASKS.MINE):
        self.user_interface = UserInterface()
        self.backpack = Backpack()
        self.mine = Mine(self, game_map)
        self.smelt = Smelt(self, game_map)
        self.forge = Forge(self, game_map)

        # Set the default initial task
        self.task = task
        self.action_count = 0

    def perform_task(self):
        """
            Checks health, organizes backpack and then performs
            one of the following tasks: mine, smelt, or forge
            """
        # Do pre-task checks
        self.action_count += 1

        # Only check health every 25 turns (it is a slow process)
        if self.action_count % 25 == 0:
            self.action_count = 0
            self.check_health()

        # Perform task
        if self.task == self.TASKS.MINE:
            self.task = self.mine.mine()
            delay = 0
        elif self.task == self.TASKS.SMELT:
            self.task = self.smelt.smelt()
            delay = 1.4
        elif self.task == self.TASKS.FORGE:
            self.task = self.forge.forge()
            delay = 2.1

        # Give the task time to complete
        sleep(delay)

        # Organize backpack now that items have been potentially added
        self.organize_backpack()

    def check_health(self):
        """
            Checks player's HP and uses a potion if it is low.
            If no potions are found, game will quit
            """
        # Check if HP is low
        if self.user_interface.get_health() < self.LOW_HEALTH:
            # Attempt to use a potion
            utils.log("INFO", F"Health dropped below {self.LOW_HEALTH}")
            used_potion = self.backpack.use_item('potion', offset=(4, 9))

            # No potions were found
            if not used_potion:
                # Potions may be obscurred by items, try selling
                self.forge.sell_items()
                # Try using a potion again
                used_potion = self.backpack.use_item('potion', offset=(4, 9))

                # Still can't use potions, likely do not have any
                if not used_potion:
                    utils.log("SEVERE", "No potions found")
                    utils.quit_game()

            # Sleep so that there is no issue using the next item
            utils.log("INFO", F"Used a potion")
            sleep(6)

    def is_weight_below_threshold(self, threshold):
        # Calculate how much more weight the player can carry
        current_weight, max_weight = self.user_interface.get_weight()
        difference = max_weight - current_weight

        # Check if the weight the player can carry is below the threshold
        if difference < threshold:
            utils.log("INFO", F"Weight is {difference} from max, threshold was set to {threshold}")
            return True

        return False

    def organize_backpack(self):
        """
            Move all items to the correct areas of the backpack
            """
        self.backpack.move_item('ore', self.backpack.ORE_LOC, (8, 6))
        self.backpack.move_item('gem', self.backpack.GEM_LOC, (4, 2))
        self.backpack.move_item('jewel', self.backpack.GEM_LOC, (4, 2))
        self.backpack.move_item('galantine', self.backpack.GEM_LOC, (5, 4))
        self.backpack.move_item('pickaxe', self.backpack.PICKAXE_LOC, (9, 4))
        self.backpack.move_item('dagger', self.backpack.DAGGER_LOC, (4, 6))
        self.backpack.move_item('hammer', self.backpack.HAMMER_LOC, (7, 3))
        self.backpack.move_item('gold', self.backpack.GEM_LOC, (6, 5))
        self.backpack.move_item('ingot', self.backpack.INGOT_LOC)
Пример #23
0
from hall_of_fame import HallOfFame

bot = Bot(command_prefix='$')


@bot.listen()
async def on_ready():
    for guild in bot.guilds:
        print(f'Guild: {guild.name}, {guild.id}')


if __name__ == '__main__':
    bot.remove_command('help')
    bot.add_cog(Help(bot))
    bot.add_cog(Hello(bot))
    bot.add_cog(Covid(bot))
    bot.add_cog(X(bot))
    bot.add_cog(Dice(bot))
    bot.add_cog(Landmine(bot))
    bot.add_cog(Sleep(bot))
    bot.add_cog(Tex(bot))
    bot.add_cog(Mine(bot))
    bot.add_cog((MessagePlayback(bot)))
    bot.add_cog(Doctor(bot))
    bot.add_cog(HallOfFame(bot))
    # bot.add_cog(Cropped(bot))

    TOKEN = os.environ['DISCORD_BOT_TOKEN']
    # sleepCommand = sleep.Sleep()
    bot.run(TOKEN)
Пример #24
0
 def generateActions(self, world, market):
     mine = Mine(self, "R1", 3)
     return [mine]
Пример #25
0
 def __init__(self):
     """ Initialize the Anti-Drone Mine """
     self.turrets = []
     Mine.__init__(self)
Пример #26
0
	def lay_mine(self):
		self.map.mine_list.append(Mine(self.rect.x, self.rect.y, self))
Пример #27
0
    def generateActions(self, world, market):
        # a list of the possible random actions
        actions = []

        # Generate possible transforms
        transform_templates = [
            housing, alloys, electronics, farms, factories, metallic_elements,
            timber, plant
        ]
        myResources = world[self.name]
        for template in transform_templates:
            max_multiplier = utils.calculate_transform_max_multiplier(
                myResources, template)
            if max_multiplier:
                transform = Transformation(self.name, template, max_multiplier)
                actions.append(transform)

        # Generate possible buys from the market
        untradeable_resources = [
            'R1', 'R4', 'R7', 'R19', 'R21', 'R22', "R1'", "R5'", "R6'", "R18'",
            "R19'", "R20'", "R21'", "R22'", "cash"
        ]
        resources = myResources.keys()
        for resource in resources:
            if resource not in untradeable_resources:
                sell_orders = market.getSellOrders(resource)
                for order in sell_orders:
                    quantity = order["quantity"]
                    price = order["strike"]
                    seller = order["name"]
                    quantity_to_buy = world[self.name]["cash"] // price

                    # create a buy order of a random quantity of the resource up to the limit
                    quantity_to_buy = random.randint(1, quantity_to_buy)
                    if seller != self.name:
                        transaction = Transaction(
                            self.name, "buy", {
                                resource: [{
                                    "quantity": quantity_to_buy,
                                    "strike": price,
                                    "expiration": 3
                                }]
                            }, market)
                        actions.append(transaction)

        # Generate possible sells for the market
        for resource in resources:
            if resource not in untradeable_resources:
                quantity = myResources[resource]
                if quantity > 0:
                    price = market.quotePrice(resource)["sellingPrice"]
                    if price == float("-inf"):
                        price = 30
                    # Create a sell order for a random amount of the resource that the country has at the market's price for it
                    quantity = random.randint(1, quantity)
                    transaction = Transaction(
                        self.name, "sell", {
                            resource: [{
                                "quantity": quantity,
                                "strike": price,
                                "expiration": 3
                            }]
                        }, market)
                    actions.append(transaction)

        # Generate possible random mine actions
        mineable_resources = ["R2", "R3", "R6"]
        for resource in mineable_resources:
            for difficulty in [1, 2, 3]:
                mine = Mine(self, resource, difficulty)
                actions.append(mine)

        # Return 3-5 random actions of all the possible actions
        random_actions = []
        num_actions = random.randint(3, 5)
        has_mine = False
        for i in range(num_actions):
            while True:
                action = random.choice(actions)
                # If action was selected already
                if action in random_actions:
                    continue
                # If a Mine action was already chosen
                elif isinstance(action, Mine) and has_mine:
                    continue
                else:
                    if isinstance(action, Mine):
                        has_mine = True
                    break

            random_actions.append(action)

        #print(self.name + ": " + action[0].toString())
        return random_actions
Пример #28
0
 def defuse(self, drone):
     """ Defuse the Mine """
     Mine.scan(self, drone)