class MarketWindow(Container):
    """Market Window class
    """
    def __init__(self, width, height, imgloader, player, gamemanager):
        self.gamemanager = gamemanager
        self.player = player
        self.imgloader = imgloader
        Container.__init__(self, width, height, (200, 50))
        # set window alpha
        self.alphavalue = 250 * 0.95
        # items offset for gui buttons
        self.itemsoffset = [32, 20]
        # selected item
        self.selecteditem = None

        self.showborder = False

        # Selection count
        self.count = 1

        # Tooltip to draw
        self.tooltip = [None, None]

        # Create gui
        self.create_gui()

        # hide market at load
        self.hide()

    def create_gui(self):
        """Add images for seeds in market

        :return:
        """
        print('generate Marketwindow')
        posx, posy = [0, 0]
        columns = int(self.width / 64) - 1
        # rows = (self.height / 32) - 1
        # Background
        bgimage = self.imgloader["marketbg"]
        bgimage = Image(bgimage, (0, 0))
        self.addwidget(bgimage)

        # close button
        closebutton = Button("X", (380, 3), labelsize=15,
                             color=(255, 255, 255))
        closebutton.connect("clicked", lambda x: self.hide())
        closebutton.connect("onshow", self.on_market_show)
        self.addwidget(closebutton)

        # refill watercan
        waterbuybutton = Button("Refill water (${0!s})".
                                format(WATERREFILLCOST),
                                (10, 30), color=(128, 128, 255))
        waterbuybutton.connect("clicked", self.on_water_buy)
        self.addwidget(waterbuybutton)

        # Buy farm
        farmcost = self.gamemanager.getnextfarmcost()
        self.buyfarm = Button("Buy new farm (${0!s})".format(farmcost),
                              (150, 30), color=(255, 0, 0))
        self.buyfarm.connect("clicked", self.on_farm_buy)
        self.addwidget(self.buyfarm)

        # Add items
        gridimg = self.imgloader['grid2']
        for seeddef in objects:
            if seeddef["id"] in OBJECTSNOTINMARKET:
                continue
            itemid = seeddef['id']
            # add seed image widget
            img = self.imgloader['object' + str(itemid)]
            px = 64 * posx + self.itemsoffset[0]
            py = 32 * posy + self.itemsoffset[1] + 30
            # add grid
            grid = Image(gridimg, (px, py))
            self.addwidget(grid)
            # Add image button
            imagebutton = Button("", (px, py), bgimage=img)
            self.addwidget(imagebutton)
            imagebutton.connect("clicked", self.on_item_select,
                                itemid=itemid)
            imagebutton.connect("onenter", self.on_mouse_item_enter,
                                itemid=itemid)
            imagebutton.connect("onleave", self.on_mouse_item_leave,
                                itemid=itemid)
            # limit
            posx += 1
            if posx >= columns:
                posx = 0
                posy += 1

        # Costlabel
        costlabel = Label("Cost:", (80, 340), size=12,
                          color=(255, 255, 255), align="center")
        self.addwidget(costlabel)
        # Cost value
        self.costvalue = Label("", (110, 340), size=12,
                               color=(200, 200, 50), align="center")
        self.addwidget(self.costvalue)

        # Selllabel
        selllabel = Label("Sell value:", (280, 340), size=12,
                          color=(255, 255, 255), align="center")
        self.addwidget(selllabel)
        # Sell value
        self.sellvalue = Label("", (330, 340), size=12,
                               color=(200, 200, 50), align="center")
        self.addwidget(self.sellvalue)

        # Message
        self.message = Label("", (10, 360), size=12,
                             color=(250, 0, 250), align="left")
        self.addwidget(self.message)
        # Selected item icon
        self.selectedicon = Image(None, (160, 332))
        self.addwidget(self.selectedicon)

        # add buttons
        self.buybutton = Button("BUY", (60, 375), color=(0, 255, 0),
                                labelsize=13)
        self.sellbutton = Button("SELL", (300, 375), color=(0, 255, 0),
                                 labelsize=13)
        self.addwidget(self.buybutton)
        self.addwidget(self.sellbutton)
        self.buybutton.connect("clicked", self.on_buy_clicked)
        self.sellbutton.connect("clicked", self.on_sell_clicked)

    def draw(self, surface):
        """draw

        :param surface:
        :return:
        """
        Container.draw(self, surface)
        if self.tooltip[0]:
            self.tooltip[0].draw(surface)

    def on_market_show(self, widget):
        """Reset market on show"""
        self.buybutton.settext("BUY")
        self.sellbutton.settext("SELL")
        self.message.settext("")
        self.selecteditem = None
        self.selectedicon.image = None
        self.sellvalue.settext("")
        self.costvalue.settext("")
        farmcost = self.gamemanager.getnextfarmcost()
        self.buyfarm.settext("Buy new farm (${0!s})".format(farmcost))

    def get_item_cost(self, itemid):
        """get item cost

        :param itemid:
        :return:
        """
        cost = int(objects[itemid]["price"])
        return cost * self.count

    def get_item_sell_value(self, itemid):
        """get item sell value

        :param itemid:
        :return:
        """
        sellcost = int(self.get_item_cost(itemid) / 8)
        return sellcost

    def update_buy_sell_button(self, itemid):
        """update buy sell button

        :param itemid:
        :return:
        """
        have = 0
        if self.player.item_in_inventory(itemid):
            have = self.player.itemscounter[str(itemid)]
        self.buybutton.settext("BUY x{0!s} (you have {1!s})".
                               format(str(self.count), have))
        self.sellbutton.settext("SELL x{0!s} ".format(str(self.count)))

    def on_item_select(self, widget, itemid):
        """selected item
        increase count if the same item selected

        :param widget:
        :param itemid:
        :return:
        """
        if itemid == self.selecteditem:
            self.count += 1
        else:
            self.count = 1

        self.selecteditem = itemid
        img = self.imgloader["object" + str(self.selecteditem)]
        # set image
        self.selectedicon.setimage(img)
        # update values
        cost = self.get_item_cost(itemid)
        self.costvalue.settext(cost)
        self.sellvalue.settext(self.get_item_sell_value(itemid))
        self.update_buy_sell_button(itemid)

    def on_buy_clicked(self, widget, **data):
        """buy clicked

        :param widget:
        :param data:
        :return:
        """
        if self.selecteditem is None:
            return
        itemid = self.selecteditem
        cost = self.get_item_cost(itemid)
        if self.player.money >= cost:
            self.player.money -= cost
            self.give_item(self.selecteditem, self.count)
            self.message.settext("You bought item")
            self.update_buy_sell_button(itemid)
        else:
            self.message.settext("You dont have enought money")

    def on_sell_clicked(self, widget, **data):
        """on sel clicked

        :param widget:
        :param data:
        :return:
        """
        if self.selecteditem is None:
            return
        itemid = self.selecteditem

        # remove item if player have it
        if self.player.item_in_inventory(itemid) \
                and self.player.itemscounter[str(itemid)] >= self.count:
            done = True
        else:
            done = False

        if done:
            # Remove items
            for x in xrange(self.count):
                self.player.remove_item(itemid)
            # Add money
            self.player.money += self.get_item_sell_value(itemid)
            self.message.settext("You sold item")
            self.update_buy_sell_button(itemid)
        else:
            self.message.settext("You don\'t have this item (or not enought)")

    def on_water_buy(self, widget, **data):
        """ water buy

        :param widget:
        :param data:
        :return:
        """
        if self.player.watercanuses == 100:
            self.message.settext("You no need refill")
            return
        if self.player.money >= WATERREFILLCOST:
            self.player.money -= WATERREFILLCOST
            self.player.watercanuses = 100
            self.message.settext("You filled watercan")
        else:
            self.message.settext("You dont have money to refill watercan")

    def give_item(self, itemid, count):
        """give item

        :param itemid:
        :param count:
        :return:
        """
        for x in xrange(count):
            self.player.add_item(self.selecteditem)

    # TOOLTIP
    def on_mouse_item_enter(self, widget, itemid):
        """on mouse item enter

        :param widget:
        :param itemid:
        :return:
        """
        seed = objects[itemid]
        otype = objects.get("type", "object")

        # Item is seed
        if otype == "seed":
            data = [
                    ["Name", seed["name"]],
                    ["Description", seed["description"]],
                    ["Quantity", str(seed["growquantity"])],
                    ["Grow in", str(seed["growtime"] / 60) + " minutes"],
                    ["Required level", str(seed.get("requiredlevel", 1))],
                    ]
        # Item is object
        else:
            data = [
                ["Name", seed["name"]],
                ["Description", seed["description"]],
                ["Required level", str(seed.get("requiredlevel", 1))],
            ]
        mx, my = pygame.mouse.get_pos()
        self.tooltip = [Tooltip((mx + 5, my + 5), data), widget]

    def on_mouse_item_leave(self, widget, itemid):
        """on mouse item leave

        :param widget:
        :param itemid:
        :return:
        """
        if self.tooltip[1] == widget:
            self.tooltip = [None, None]

    def on_farm_buy(self, widget):
        """on farm buy

        :param widget:
        :return:
        """
        farmcost = self.gamemanager.getnextfarmcost()
        if self.player.money < farmcost:
            self.message.settext("You dont have money to buy new farm")
        else:
            self.player.money -= farmcost
            self.gamemanager.addfarm()
            self.message.settext("You bought a new farm")
            self.on_market_show(None)
class GameWindow(Window):

    def __init__(self):
        Window.__init__(self, (800, 600), (0, 0))

        self.lazyscreen = None

        # Create gamemanager
        self.gamemanager = GameManager()
        # timers
        self.eventstimer = Timer()
        self.updatetimer = Timer()

        self.images = ImageLoader(imagesdata)
        self.notifyfont = pygame.font.Font("dejavusansmono.ttf", 12)
        self.font2 = pygame.font.Font("dejavusansmono.ttf", 18)

        # Install plugins
        self.coreplugin = PluginSystem.installPlugin(CorePlugin)
        self.coreplugin.gamewindow = self

        # background image
        bgimg = Image(self.images['background'], (0, 0))
        self.addwidget(bgimg)

        # Create inventory window
        player = self.gamemanager.getplayer()
        self.inventorywindow = InventoryWindow(self.images, player)
        self.inventorywindow.hide()

        # create market window
        self.sellwindow = MarketWindow((400, 400), self.images, player,
                                       self.gamemanager)
        self.sellwindow.gamewindow = self

        # Market button
        marketbutton = Button("", (800 - 42, 10),
                              bgimage=self.images['marketbutton'])
        marketbutton.connect("clicked", self.toggle_market)
        self.addwidget(marketbutton)

        # Inventory button
        inventorybutton = Button("", (800 - 42, 52),
                                 bgimage=self.images['inventorybutton'])
        inventorybutton.connect("clicked", self.toggle_inventory)
        self.addwidget(inventorybutton)

        # Create help window
        self.helpwindow = HelpWindow((500, 300))

        # Create expbar
        self.expbar = ExpBar(player)
        self.addwidget(self.expbar)

        # labels
        self.moneylabel = Label("", (400, 5), align="center")
        self.addwidget(self.moneylabel)

        # Label for version
        versionlabel = Label("v. " + __VERSION__ + " (H for help)",
                             (5, 580))
        self.addwidget(versionlabel)

        # Is game running?
        self.running = False

        # Farm position offset (to center map)
        self.farmoffset = (212, 50)

        # Temp image for farmfield redraw if not modified
        self.tempfarmimage = None

    def update(self):
        """Update farm"""
        Window.update(self)
        self.eventstimer.tick()
        self.updatetimer.tick()

        # update inventory
        self.inventorywindow.update()

        # Update game 20 times per second
        if self.updatetimer.tickpassed(20):
            self.gamemanager.update()

            # update inventory when changed
            self.update_current_money()
            if self.inventorywindow.ismodified():
                self.recreate_inventory()

    def update_current_money(self):
        player = self.gamemanager.getplayer()
        # Render current money
        text = "Money: $%s " % player.money
        self.moneylabel.settext(text)

    def recreate_inventory(self):
        self.inventorywindow.create_gui()

    def handle_farmfield_events(self, event):
        # Mouse motion
        mx, my = pygame.mouse.get_pos()

        player = self.gamemanager.getplayer()

        # left mouse button
        if pygame.mouse.get_pressed()[0] == 1:

            pos = self.get_farmtile_pos_under_mouse()

            if pos:
                # Emit toolused event
                PluginSystem.emit_event("toolused", position=pos,
                                        gamemanager=self.gamemanager)

        # events for tools
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # events for tools
            for tool in TOOLS:
                index = TOOLS.index(tool)
                rect = (10 + 50 * index, 10, 48, 48)
                if pygame.Rect(rect).collidepoint((mx, my)):
                    farmlib.clicksound.play()
                    player.selectedtool = tool

    def toggle_market(self, widget):
        self.inventorywindow.hide()
        self.sellwindow.togglevisible()

    def toggle_inventory(self, widget):
        self.sellwindow.hide()
        self.inventorywindow.togglevisible()

    def active_game_events(self, event):
        player = self.gamemanager.getplayer()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                player.selectedtool = "harvest"
            if event.key == pygame.K_2:
                player.selectedtool = "plant"
            if event.key == pygame.K_3:
                player.selectedtool = "watering"
            if event.key == pygame.K_4:
                player.selectedtool = "shovel"
            if event.key == pygame.K_5:
                player.selectedtool = "pickaxe"
            if event.key == pygame.K_6:
                player.selectedtool = "axe"

    def events(self):
        """Events handler"""

        for event in pygame.event.get():
            # poll events to market window
            self.sellwindow.poll_event(event)
            # poll events to inventory window
            self.inventorywindow.poll_event(event)
            # gamewindow events
            self.poll_event(event)

            if event.type == pygame.QUIT:
                self.running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # ESC close market window or exit from game
                    if self.sellwindow.visible:
                        self.sellwindow.hide()
                    elif self.inventorywindow.visible:
                        self.inventorywindow.hide()
                    else:
                        self.go_to_main_menu()

                # Events only for active game
                if not self.sellwindow.visible and \
                        not self.inventorywindow.visible:

                    self.active_game_events(event)

                # Windows toggle buttons
                if event.key == pygame.K_s:
                    self.toggle_market(None)
                if event.key == pygame.K_i:
                    self.toggle_inventory(None)
                    self.recreate_inventory()
                if event.key == pygame.K_m:
                    if farmlib.clicksound.get_volume() == 0.0:
                        farmlib.clicksound.set_volume(1.0)
                    else:
                        farmlib.clicksound.set_volume(0.0)
                # help window key
                if event.key == pygame.K_h:
                    self.sellwindow.hide()
                    self.inventorywindow.hide()
                    self.helpwindow.togglevisible()
                # previous farm key
                if event.key == pygame.K_z:
                    farmcount = self.gamemanager.getfarmcount()
                    currfarmid = self.gamemanager.getcurrentfarmid()
                    if currfarmid > 0:
                        self.gamemanager.setcurrentfarm(currfarmid - 1)
                        farm = self.gamemanager.getfarm()
                        farm.markmodified()
                # next farm key
                if event.key == pygame.K_x:
                    farmcount = self.gamemanager.getfarmcount()
                    currfarmid = self.gamemanager.getcurrentfarmid()
                    if currfarmid < farmcount - 1:
                        self.gamemanager.setcurrentfarm(currfarmid + 1)
                        farm = self.gamemanager.getfarm()
                        farm.markmodified()
            # others events
            if not self.sellwindow.visible and \
                    not self.inventorywindow.visible:

                self.handle_farmfield_events(event)

    def redraw(self, screen):
        """Redraw screen"""
        Window.draw(self, screen)

        # Draw gamewindow
        self.draw(screen)

        farm = self.gamemanager.getfarm()
        player = self.gamemanager.getplayer()

        # avoid temp farm image to be None
        if not self.tempfarmimage or farm.ismodified():
            # Draw farmfield
            self.tempfarmimage = render_field(screen, self.images,
                                              farm, self.farmoffset)
        # Blit farmfield
        screen.blit(self.tempfarmimage, (0, 0))

        # draw rain
        if farm.raining and self.updatetimer.tickpassed(2):
            render_rain(screen)
            x = random.randint(0, 12)
            y = random.randint(0, 12)
            farm.water(x, y)

        drawnearcursor = not self.sellwindow.visible
        # Draw tools and selected tool rectangle
        draw_tools(screen,
                   player.selectedtool,
                   player.selecteditem,
                   self.images,
                   drawnearcursor=drawnearcursor)

        # draw watercanuses
        uses = Label("", (110 + 2, 10 + 2), color=(255, 240, 240))
        uses.settext(str(player.watercanuses))
        uses.repaint()
        uses.draw(screen)

        if not self.sellwindow.visible and \
                not self.inventorywindow.visible:

            mx, my = pygame.mouse.get_pos()

            # Draw help window
            self.helpwindow.draw(screen)

            # draw notify window if mouse under seed
            pos = self.get_farmtile_pos_under_mouse()
            if pos:
                farmtile = farm.get_farmtile(pos[0], pos[1])
                farmobject = farmtile['object']
                render_seed_notify(screen, self.notifyfont,
                                   mx + 5, my + 5,
                                   farmobject, farmtile, self.images
                                   )
        # draw selected seed
        if player.selecteditem != None:
            draw_selected_seed(screen, player.selecteditem, self.images)

        # draw inventory
        self.inventorywindow.draw(screen)
        # redraw sell window
        self.sellwindow.draw(screen)

    def get_farmtile_pos_under_mouse(self):
        """Get FarmTile position under mouse"""

        mx, my = pygame.mouse.get_pos()
        mx -= 150 + 32 + self.farmoffset[0]
        my -= self.farmoffset[1]
        xx, yy = self.screen2iso(mx, my)

        if xx < 0 or yy < 0 or xx > 11 or yy > 11:
            return None
        else:
            xx = min(12 - 1, xx)
            yy = min(12 - 1, yy)
            return (xx, yy)

    def get_farmobject_under_cursor(self):
        """Get Seed under mouse cursor"""

        pos = self.get_farmtile_pos_under_mouse()
        if pos:
            return self.farm.get_farmobject(pos[0], pos[1])

        return None

    def iso2screen(self, x, y):
        xx = (x - y) * (64 / 2)
        yy = (x + y) * (32 / 2)
        return xx, yy

    def screen2iso(self, x, y):
        x = x / 2
        xx = (y + x) / (32)
        yy = (y - x) / (32)
        return xx, yy

    def go_to_main_menu(self):
        self.deinit()
        from farmlib.menuwindow import MenuWindow
        self.parent.set_active_screen(MenuWindow())
        self.parent.inmenu = True
        self.parent.ingame = False

    def init(self):
        self.running = True
        # Load game
        result = self.gamemanager.loadgame()
        if not result:
            self.gamemanager.start_new_game()
            print("No save game found. Starting new one")
        # Forward time to match gametime
        self.gamemanager.timeforward()

    def deinit(self):
        # stop game
        self.running = False
        self.gamemanager.savegame()
    def redraw(self, screen):
        """Redraw screen"""
        Window.draw(self, screen)

        # Draw gamewindow
        self.draw(screen)

        farm = self.gamemanager.getfarm()
        player = self.gamemanager.getplayer()

        # avoid temp farm image to be None
        if not self.tempfarmimage or farm.ismodified():
            # Draw farmfield
            self.tempfarmimage = render_field(screen, self.images,
                                              farm, self.farmoffset)
        # Blit farmfield
        screen.blit(self.tempfarmimage, (0, 0))

        # draw rain
        if farm.raining and self.updatetimer.tickpassed(2):
            render_rain(screen)
            x = random.randint(0, 12)
            y = random.randint(0, 12)
            farm.water(x, y)

        drawnearcursor = not self.sellwindow.visible
        # Draw tools and selected tool rectangle
        draw_tools(screen,
                   player.selectedtool,
                   player.selecteditem,
                   self.images,
                   drawnearcursor=drawnearcursor)

        # draw watercanuses
        uses = Label("", (110 + 2, 10 + 2), color=(255, 240, 240))
        uses.settext(str(player.watercanuses))
        uses.repaint()
        uses.draw(screen)

        if not self.sellwindow.visible and \
                not self.inventorywindow.visible:

            mx, my = pygame.mouse.get_pos()

            # Draw help window
            self.helpwindow.draw(screen)

            # draw notify window if mouse under seed
            pos = self.get_farmtile_pos_under_mouse()
            if pos:
                farmtile = farm.get_farmtile(pos[0], pos[1])
                farmobject = farmtile['object']
                render_seed_notify(screen, self.notifyfont,
                                   mx + 5, my + 5,
                                   farmobject, farmtile, self.images
                                   )
        # draw selected seed
        if player.selecteditem != None:
            draw_selected_seed(screen, player.selecteditem, self.images)

        # draw inventory
        self.inventorywindow.draw(screen)
        # redraw sell window
        self.sellwindow.draw(screen)
Exemple #4
0
class MarketWindow(Container):
    def __init__(self, size, imgloader, player, gamemanager):
        self.gamemanager = gamemanager
        self.player = player
        self.imgloader = imgloader
        Container.__init__(self, size, (200, 50))
        # set window alpha
        self.alphavalue = 250 * 0.95
        # items offset for gui buttons
        self.itemsoffset = [32, 20]
        # selected item
        self.selecteditem = None

        self.showborder = False

        # Selection count
        self.count = 1

        # Tooltip to draw
        self.tooltip = [None, None]

        # Create gui
        self.create_gui()

        # hide market at load
        self.hide()

    def create_gui(self):
        # Add images for seeds in market
        posx, posy = [0, 0]
        columns = (self.width / 64) - 1
        #rows = (self.height / 32) - 1
        # Background
        bgimage = self.imgloader["marketbg"]
        bgimage = Image(bgimage, (0, 0))
        self.addwidget(bgimage)

        # close button
        closebutton = Button("X", (380, 3),
                             labelsize=15,
                             color=(255, 255, 255))
        closebutton.connect("clicked", lambda x: self.hide())
        closebutton.connect("onshow", self.on_market_show)
        self.addwidget(closebutton)

        # refill watercan
        waterbuybutton = Button("Refill water ($%s)" % WATERREFILLCOST,
                                (10, 30),
                                color=(128, 128, 255))
        waterbuybutton.connect("clicked", self.on_water_buy)
        self.addwidget(waterbuybutton)

        # Buy farm
        farmcost = self.gamemanager.getnextfarmcost()
        self.buyfarm = Button("Buy new farm ($%s)" % farmcost, (150, 30),
                              color=(255, 0, 0))
        self.buyfarm.connect("clicked", self.on_farm_buy)
        self.addwidget(self.buyfarm)

        # Add items
        gridimg = self.imgloader['grid2']
        for seeddef in objects:
            if seeddef["id"] in OBJECTSNOTINMARKET:
                continue
            itemid = seeddef['id']
            # add seed image widget
            img = self.imgloader['object' + str(itemid)]
            px = 64 * posx + self.itemsoffset[0]
            py = 32 * posy + self.itemsoffset[1] + 30
            # add grid
            grid = Image(gridimg, (px, py))
            self.addwidget(grid)
            # Add image button
            imagebutton = Button("", (px, py), bgimage=img)
            self.addwidget(imagebutton)
            imagebutton.connect("clicked", self.on_item_select, itemid=itemid)
            imagebutton.connect("onenter",
                                self.on_mouse_item_enter,
                                itemid=itemid)
            imagebutton.connect("onleave",
                                self.on_mouse_item_leave,
                                itemid=itemid)
            # limit
            posx += 1
            if posx >= columns:
                posx = 0
                posy += 1

        # Costlabel
        costlabel = Label("Cost:", (80, 340),
                          size=12,
                          color=(255, 255, 255),
                          align="center")
        self.addwidget(costlabel)
        # Cost value
        self.costvalue = Label("", (110, 340),
                               size=12,
                               color=(200, 200, 50),
                               align="center")
        self.addwidget(self.costvalue)

        # Selllabel
        selllabel = Label("Sell value:", (280, 340),
                          size=12,
                          color=(255, 255, 255),
                          align="center")
        self.addwidget(selllabel)
        # Sell value
        self.sellvalue = Label("", (330, 340),
                               size=12,
                               color=(200, 200, 50),
                               align="center")
        self.addwidget(self.sellvalue)

        # Message
        self.message = Label("", (10, 360),
                             size=12,
                             color=(250, 0, 250),
                             align="left")
        self.addwidget(self.message)
        # Selected item icon
        self.selectedicon = Image(None, (160, 332))
        self.addwidget(self.selectedicon)

        # add buttons
        self.buybutton = Button("BUY", (60, 375),
                                color=(0, 255, 0),
                                labelsize=13)
        self.sellbutton = Button("SELL", (300, 375),
                                 color=(0, 255, 0),
                                 labelsize=13)
        self.addwidget(self.buybutton)
        self.addwidget(self.sellbutton)
        self.buybutton.connect("clicked", self.on_buy_clicked)
        self.sellbutton.connect("clicked", self.on_sell_clicked)

    def draw(self, surface):
        Container.draw(self, surface)
        if self.tooltip[0]:
            self.tooltip[0].draw(surface)

    def on_market_show(self, widget):
        """Reset market on show"""
        self.buybutton.settext("BUY")
        self.sellbutton.settext("SELL")
        self.message.settext("")
        self.selecteditem = None
        self.selectedicon.image = None
        self.sellvalue.settext("")
        self.costvalue.settext("")
        farmcost = self.gamemanager.getnextfarmcost()
        self.buyfarm.settext("Buy new farm ($%s)" % farmcost)

    def get_item_cost(self, itemid):
        cost = int(objects[itemid]["price"])
        return cost * self.count

    def get_item_sell_value(self, itemid):
        sellcost = int(self.get_item_cost(itemid) / 8)
        return sellcost

    def update_buy_sell_button(self, itemid):
        have = 0
        if self.player.item_in_inventory(itemid):
            have = self.player.itemscounter[str(itemid)]
        self.buybutton.settext("BUY x%s (you have %s)" %
                               (str(self.count), have))
        self.sellbutton.settext("SELL x%s " % str(self.count))

    def on_item_select(self, widget, itemid):
        # increase count if the same item selected
        if itemid == self.selecteditem:
            self.count += 1
        else:
            self.count = 1

        self.selecteditem = itemid
        img = self.imgloader["object" + str(self.selecteditem)]
        # set image
        self.selectedicon.setimage(img)
        # update values
        cost = self.get_item_cost(itemid)
        self.costvalue.settext(cost)
        self.sellvalue.settext(self.get_item_sell_value(itemid))
        self.update_buy_sell_button(itemid)

    def on_buy_clicked(self, widget, **data):
        if self.selecteditem is None:
            return
        itemid = self.selecteditem
        cost = self.get_item_cost(itemid)
        if self.player.money >= cost:
            self.player.money -= cost
            self.give_item(self.selecteditem, self.count)
            self.message.settext("You bought item")
            self.update_buy_sell_button(itemid)
        else:
            self.message.settext("You dont have enought money")

    def on_sell_clicked(self, widget, **data):
        if self.selecteditem is None:
            return
        itemid = self.selecteditem

        # remove item if player have it
        if self.player.item_in_inventory(itemid) \
                and self.player.itemscounter[str(itemid)] >= self.count:
            done = True
        else:
            done = False

        if done:
            # Remove items
            for x in xrange(self.count):
                self.player.remove_item(itemid)
            # Add money
            self.player.money += self.get_item_sell_value(itemid)
            self.message.settext("You sold item")
            self.update_buy_sell_button(itemid)
        else:
            self.message.settext("You don\'t have this item (or not enought)")

    def on_water_buy(self, widget, **data):
        if self.player.watercanuses == 100:
            self.message.settext("You no need refill")
            return
        if self.player.money >= WATERREFILLCOST:
            self.player.money -= WATERREFILLCOST
            self.player.watercanuses = 100
            self.message.settext("You filled watercan")
        else:
            self.message.settext("You dont have money to refill watercan")

    def give_item(self, itemid, count):
        for x in xrange(count):
            self.player.add_item(self.selecteditem)

    # TOOLTIP
    def on_mouse_item_enter(self, widget, itemid):
        seed = objects[itemid]
        otype = objects.get("type", "object")

        #Item is seed
        if otype == "seed":
            data = [
                ["Name", seed["name"]],
                ["Description", seed["description"]],
                ["Quantity", str(seed["growquantity"])],
                ["Grow in", str(seed["growtime"] / 60) + " minutes"],
                ["Required level",
                 str(seed.get("requiredlevel", 1))],
            ]
        #Item is object
        else:
            data = [
                ["Name", seed["name"]],
                ["Description", seed["description"]],
                ["Required level",
                 str(seed.get("requiredlevel", 1))],
            ]
        mx, my = pygame.mouse.get_pos()
        self.tooltip = [Tooltip((mx + 5, my + 5), data), widget]

    def on_mouse_item_leave(self, widget, itemid):
        if self.tooltip[1] == widget:
            self.tooltip = [None, None]

    def on_farm_buy(self, widget):
        farmcost = self.gamemanager.getnextfarmcost()
        if self.player.money < farmcost:
            self.message.settext("You dont have money to buy new farm")
        else:
            self.player.money -= farmcost
            self.gamemanager.addfarm()
            self.message.settext("You bought a new farm")
            self.on_market_show(None)
Exemple #5
0
class GameWindow(Window):
    def __init__(self):
        Window.__init__(self, (800, 600), (0, 0))

        self.lazyscreen = None

        # Create gamemanager
        self.gamemanager = GameManager()
        # timers
        self.eventstimer = Timer()
        self.updatetimer = Timer()

        self.images = ImageLoader(imagesdata)
        self.notifyfont = pygame.font.Font("dejavusansmono.ttf", 12)
        self.font2 = pygame.font.Font("dejavusansmono.ttf", 18)

        # Install plugins
        self.coreplugin = PluginSystem.installPlugin(CorePlugin)
        self.coreplugin.gamewindow = self

        # background image
        bgimg = Image(self.images['background'], (0, 0))
        self.addwidget(bgimg)

        # Create inventory window
        player = self.gamemanager.getplayer()
        self.inventorywindow = InventoryWindow(self.images, player)
        self.inventorywindow.hide()

        # create market window
        self.sellwindow = MarketWindow((400, 400), self.images, player,
                                       self.gamemanager)
        self.sellwindow.gamewindow = self

        # Market button
        marketbutton = Button("", (800 - 42, 10),
                              bgimage=self.images['marketbutton'])
        marketbutton.connect("clicked", self.toggle_market)
        self.addwidget(marketbutton)

        # Inventory button
        inventorybutton = Button("", (800 - 42, 52),
                                 bgimage=self.images['inventorybutton'])
        inventorybutton.connect("clicked", self.toggle_inventory)
        self.addwidget(inventorybutton)

        # Create help window
        self.helpwindow = HelpWindow((500, 300))

        # Create expbar
        self.expbar = ExpBar(player)
        self.addwidget(self.expbar)

        # labels
        self.moneylabel = Label("", (400, 5), align="center")
        self.addwidget(self.moneylabel)

        # Label for version
        versionlabel = Label("v. " + __VERSION__ + " (H for help)", (5, 580))
        self.addwidget(versionlabel)

        # Is game running?
        self.running = False

        # Farm position offset (to center map)
        self.farmoffset = (212, 50)

        # Temp image for farmfield redraw if not modified
        self.tempfarmimage = None

    def update(self):
        """Update farm"""
        Window.update(self)
        self.eventstimer.tick()
        self.updatetimer.tick()

        # update inventory
        self.inventorywindow.update()

        # Update game 20 times per second
        if self.updatetimer.tickpassed(20):
            self.gamemanager.update()

            # update inventory when changed
            self.update_current_money()
            if self.inventorywindow.ismodified():
                self.recreate_inventory()

    def update_current_money(self):
        player = self.gamemanager.getplayer()
        # Render current money
        text = "Money: $%s " % player.money
        self.moneylabel.settext(text)

    def recreate_inventory(self):
        self.inventorywindow.create_gui()

    def handle_farmfield_events(self, event):
        # Mouse motion
        mx, my = pygame.mouse.get_pos()

        player = self.gamemanager.getplayer()

        # left mouse button
        if pygame.mouse.get_pressed()[0] == 1:

            pos = self.get_farmtile_pos_under_mouse()

            if pos:
                # Emit toolused event
                PluginSystem.emit_event("toolused",
                                        position=pos,
                                        gamemanager=self.gamemanager)

        # events for tools
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # events for tools
            for tool in TOOLS:
                index = TOOLS.index(tool)
                rect = (10 + 50 * index, 10, 48, 48)
                if pygame.Rect(rect).collidepoint((mx, my)):
                    farmlib.clicksound.play()
                    player.selectedtool = tool

    def toggle_market(self, widget):
        self.inventorywindow.hide()
        self.sellwindow.togglevisible()

    def toggle_inventory(self, widget):
        self.sellwindow.hide()
        self.inventorywindow.togglevisible()

    def active_game_events(self, event):
        player = self.gamemanager.getplayer()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                player.selectedtool = "harvest"
            if event.key == pygame.K_2:
                player.selectedtool = "plant"
            if event.key == pygame.K_3:
                player.selectedtool = "watering"
            if event.key == pygame.K_4:
                player.selectedtool = "shovel"
            if event.key == pygame.K_5:
                player.selectedtool = "pickaxe"
            if event.key == pygame.K_6:
                player.selectedtool = "axe"

    def events(self):
        """Events handler"""

        for event in pygame.event.get():
            # poll events to market window
            self.sellwindow.poll_event(event)
            # poll events to inventory window
            self.inventorywindow.poll_event(event)
            # gamewindow events
            self.poll_event(event)

            if event.type == pygame.QUIT:
                self.running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # ESC close market window or exit from game
                    if self.sellwindow.visible:
                        self.sellwindow.hide()
                    elif self.inventorywindow.visible:
                        self.inventorywindow.hide()
                    else:
                        self.go_to_main_menu()

                # Events only for active game
                if not self.sellwindow.visible and \
                        not self.inventorywindow.visible:

                    self.active_game_events(event)

                # Windows toggle buttons
                if event.key == pygame.K_s:
                    self.toggle_market(None)
                if event.key == pygame.K_i:
                    self.toggle_inventory(None)
                    self.recreate_inventory()
                if event.key == pygame.K_m:
                    if farmlib.clicksound.get_volume() == 0.0:
                        farmlib.clicksound.set_volume(1.0)
                    else:
                        farmlib.clicksound.set_volume(0.0)
                # help window key
                if event.key == pygame.K_h:
                    self.sellwindow.hide()
                    self.inventorywindow.hide()
                    self.helpwindow.togglevisible()
                # previous farm key
                if event.key == pygame.K_z:
                    farmcount = self.gamemanager.getfarmcount()
                    currfarmid = self.gamemanager.getcurrentfarmid()
                    if currfarmid > 0:
                        self.gamemanager.setcurrentfarm(currfarmid - 1)
                        farm = self.gamemanager.getfarm()
                        farm.markmodified()
                # next farm key
                if event.key == pygame.K_x:
                    farmcount = self.gamemanager.getfarmcount()
                    currfarmid = self.gamemanager.getcurrentfarmid()
                    if currfarmid < farmcount - 1:
                        self.gamemanager.setcurrentfarm(currfarmid + 1)
                        farm = self.gamemanager.getfarm()
                        farm.markmodified()
            # others events
            if not self.sellwindow.visible and \
                    not self.inventorywindow.visible:

                self.handle_farmfield_events(event)

    def redraw(self, screen):
        """Redraw screen"""
        Window.draw(self, screen)

        # Draw gamewindow
        self.draw(screen)

        farm = self.gamemanager.getfarm()
        player = self.gamemanager.getplayer()

        # avoid temp farm image to be None
        if not self.tempfarmimage or farm.ismodified():
            # Draw farmfield
            self.tempfarmimage = render_field(screen, self.images, farm,
                                              self.farmoffset)
        # Blit farmfield
        screen.blit(self.tempfarmimage, (0, 0))

        # draw rain
        if farm.raining and self.updatetimer.tickpassed(2):
            render_rain(screen)
            x = random.randint(0, 12)
            y = random.randint(0, 12)
            farm.water(x, y)

        drawnearcursor = not self.sellwindow.visible
        # Draw tools and selected tool rectangle
        draw_tools(screen,
                   player.selectedtool,
                   player.selecteditem,
                   self.images,
                   drawnearcursor=drawnearcursor)

        # draw watercanuses
        uses = Label("", (110 + 2, 10 + 2), color=(255, 240, 240))
        uses.settext(str(player.watercanuses))
        uses.repaint()
        uses.draw(screen)

        if not self.sellwindow.visible and \
                not self.inventorywindow.visible:

            mx, my = pygame.mouse.get_pos()

            # Draw help window
            self.helpwindow.draw(screen)

            # draw notify window if mouse under seed
            pos = self.get_farmtile_pos_under_mouse()
            if pos:
                farmtile = farm.get_farmtile(pos[0], pos[1])
                farmobject = farmtile['object']
                render_seed_notify(screen, self.notifyfont, mx + 5, my + 5,
                                   farmobject, farmtile, self.images)
        # draw selected seed
        if player.selecteditem != None:
            draw_selected_seed(screen, player.selecteditem, self.images)

        # draw inventory
        self.inventorywindow.draw(screen)
        # redraw sell window
        self.sellwindow.draw(screen)

    def get_farmtile_pos_under_mouse(self):
        """Get FarmTile position under mouse"""

        mx, my = pygame.mouse.get_pos()
        mx -= 150 + 32 + self.farmoffset[0]
        my -= self.farmoffset[1]
        xx, yy = self.screen2iso(mx, my)

        if xx < 0 or yy < 0 or xx > 11 or yy > 11:
            return None
        else:
            xx = min(12 - 1, xx)
            yy = min(12 - 1, yy)
            return (xx, yy)

    def get_farmobject_under_cursor(self):
        """Get Seed under mouse cursor"""

        pos = self.get_farmtile_pos_under_mouse()
        if pos:
            return self.farm.get_farmobject(pos[0], pos[1])

        return None

    def iso2screen(self, x, y):
        xx = (x - y) * (64 / 2)
        yy = (x + y) * (32 / 2)
        return xx, yy

    def screen2iso(self, x, y):
        x = x / 2
        xx = (y + x) / (32)
        yy = (y - x) / (32)
        return xx, yy

    def go_to_main_menu(self):
        self.deinit()
        from farmlib.menuwindow import MenuWindow
        self.parent.set_active_screen(MenuWindow())
        self.parent.inmenu = True
        self.parent.ingame = False

    def init(self):
        self.running = True
        # Load game
        result = self.gamemanager.loadgame()
        if not result:
            self.gamemanager.start_new_game()
            print("No save game found. Starting new one")
        # Forward time to match gametime
        self.gamemanager.timeforward()

    def deinit(self):
        # stop game
        self.running = False
        self.gamemanager.savegame()
Exemple #6
0
    def redraw(self, screen):
        """Redraw screen"""
        Window.draw(self, screen)

        # Draw gamewindow
        self.draw(screen)

        farm = self.gamemanager.getfarm()
        player = self.gamemanager.getplayer()

        # avoid temp farm image to be None
        if not self.tempfarmimage or farm.ismodified():
            # Draw farmfield
            self.tempfarmimage = render_field(screen, self.images, farm,
                                              self.farmoffset)
        # Blit farmfield
        screen.blit(self.tempfarmimage, (0, 0))

        # draw rain
        if farm.raining and self.updatetimer.tickpassed(2):
            render_rain(screen)
            x = random.randint(0, 12)
            y = random.randint(0, 12)
            farm.water(x, y)

        drawnearcursor = not self.sellwindow.visible
        # Draw tools and selected tool rectangle
        draw_tools(screen,
                   player.selectedtool,
                   player.selecteditem,
                   self.images,
                   drawnearcursor=drawnearcursor)

        # draw watercanuses
        uses = Label("", (110 + 2, 10 + 2), color=(255, 240, 240))
        uses.settext(str(player.watercanuses))
        uses.repaint()
        uses.draw(screen)

        if not self.sellwindow.visible and \
                not self.inventorywindow.visible:

            mx, my = pygame.mouse.get_pos()

            # Draw help window
            self.helpwindow.draw(screen)

            # draw notify window if mouse under seed
            pos = self.get_farmtile_pos_under_mouse()
            if pos:
                farmtile = farm.get_farmtile(pos[0], pos[1])
                farmobject = farmtile['object']
                render_seed_notify(screen, self.notifyfont, mx + 5, my + 5,
                                   farmobject, farmtile, self.images)
        # draw selected seed
        if player.selecteditem != None:
            draw_selected_seed(screen, player.selecteditem, self.images)

        # draw inventory
        self.inventorywindow.draw(screen)
        # redraw sell window
        self.sellwindow.draw(screen)