Example #1
0
    def __init__(self):
        self.parent = None
        Container.__init__(self, 800, 600, (0, 0))
        self.running = True

        self.menupos = 0
        self.maxmenupos = 1

        # background
        imgpath = os.path.join("images", "gui", "mainmenubg.png")
        bgimage = pygame.image.load(imgpath).convert_alpha()
        bg = Image(bgimage, (0, 0))
        self.addwidget(bg)

        # start button
        self.menucursor = Label("-> ", (230, 120),
                                color=(255, 255, 0), size=20)
        self.addwidget(self.menucursor)

        # start button
        self.startbutton = Button("Start game / Continue", (270, 120),
                                  color=(255, 255, 200), labelsize=20)
        self.startbutton.connect("clicked", self.on_startgame)
        self.addwidget(self.startbutton)

        # Quit button
        self.quitbutton = Button("Quit", (270, 160),
                                 color=(255, 0, 0),
                                 labelsize=20)
        self.quitbutton.connect("clicked", self.on_quit)
        self.addwidget(self.quitbutton)

        # Show window
        self.show()
Example #2
0
    def __init__(self):
        self.parent = None
        Container.__init__(self, (800, 600), (0, 0))
        self.running = True

        self.menupos = 0
        self.maxmenupos = 1

        # background
        imgpath = os.path.join("images", "gui", "mainmenubg.png")
        bgimage = pygame.image.load(imgpath).convert_alpha()
        bg = Image(bgimage, (0, 0))
        self.addwidget(bg)

        # start button
        self.menucursor = Label("-> ", (230, 200),
                                color=(255, 255, 0), size=20)
        self.addwidget(self.menucursor)

        # start button
        self.startbutton = Button("Start game / Continue", (270, 200),
                                  color=(255, 255, 200), labelsize=20)
        self.startbutton.connect("clicked", self.on_startgame)
        self.addwidget(self.startbutton)

        # Quit button
        self.quitbutton = Button("Quit", (270, 240),
                                 color=(255, 0, 0),
                                 labelsize=20)
        self.quitbutton.connect("clicked", self.on_quit)
        self.addwidget(self.quitbutton)

        # Show window
        self.show()
Example #3
0
class MainView(View):

    logo = None
    btn_start = None
    btn_exit = None
    context = None

    def __init__(self, context):
        self.btn_start = Button('Start Game', self._on_start)
        self.btn_exit = Button('Exit Game', self._on_exit)
        self.context = context
        self.logo = pygame.image.load('img/logo.png')
        w, h = self.logo.get_size()
        # 调整界面适应 Logo 大小以及显示按钮
        self.context.screen = pygame.display.set_mode(
            (int(w * 1.5), int(h * 2)), 0, 32)
        # 设置界面标题
        pygame.display.set_caption('Python Snake Game v1.0')
        View.__init__(self, context.screen)

    def on_draw(self):
        # 绘制界面
        self._on_draw()
        # 绘制按钮
        self.btn_start.on_draw(self.context.screen)
        self.btn_exit.on_draw(self.context.screen)

    def on_event(self, event):
        # 监控各种事件
        self.btn_start.on_event(event)
        self.btn_exit.on_event(event)

    def _on_exit(self):
        # 控制退出状态
        print('exit game')
        self.context.running = False

    def _on_start(self):
        # 切换界面到游戏界面
        print('start game')
        self.context.view = GameView(self.context)

    def _on_draw(self):
        '''
        计算各个按钮的位置以及Logo的位置
        '''
        s_w, s_h = self.context.screen.get_size()
        l_w, l_h = self.logo.get_size()
        x, y, bs_w, bs_h = self.btn_start.get_box()
        x, y, be_w, be_h = self.btn_exit.get_box()
        y_start = l_h + 50
        '''
        界面元素排版
        '''
        self.btn_start.pos = (s_w / 2 - bs_w / 2, y_start)
        self.btn_exit.pos = (s_w / 2 - be_w / 2, y_start + bs_h + 4)
        self.context.screen.blit(self.logo,
                                 (s_w / 2 - l_w / 2, s_h / 2 - l_h / 2))
Example #4
0
 def __init__(self, context):
     self.btn_start = Button('Start Game', self._on_start)
     self.btn_exit = Button('Exit Game', self._on_exit)
     self.context = context
     self.logo = pygame.image.load('img/logo.png')
     w, h = self.logo.get_size()
     # 调整界面适应 Logo 大小以及显示按钮
     self.context.screen = pygame.display.set_mode(
         (int(w * 1.5), int(h * 2)), 0, 32)
     # 设置界面标题
     pygame.display.set_caption('Python Snake Game v1.0')
     View.__init__(self, context.screen)
    def create_gui(self):
        """create gui

        :return:
        """
        self.remove_all_widgets()
        bg = Image(self.images['inventory'], (0, 0))
        self.addwidget(bg)

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

        # create items
        counterx = 0
        countery = 0
        for item in self.player.inventory:
            px = counterx * 64 + self.inventoryoffset[0] + 25
            py = countery * 32 + self.inventoryoffset[1] + 30
            # make grid
            px += counterx * 30
            py += countery * 15

            # grid image
            gridimage = Image(self.images['grid2'], (px, py))
            self.addwidget(gridimage)

            # item button
            img = self.images['object' + str(item)]
            itembutton = Button("", (px, py), img)
            itembutton.connect("clicked",
                               self.on_item_select, itemid=item)
            itembutton.connect("onenter",
                               self.on_item_enter, itemid=item)
            itembutton.connect("onleave",
                               self.on_item_leave, itemid=item)
            self.addwidget(itembutton)

            # item count
            text = str(self.player.itemscounter[str(item)])
            itemcount = Label(text, (px + 40, py + 16), align="center")
            self.addwidget(itemcount)

            # limit
            counterx += 1
            if counterx == self.inventorysize[0]:
                counterx = 0
                countery += 1
            if countery == self.inventorysize[1]:
                break
Example #6
0
    def create_gui(self):
        """create gui

        :return:
        """
        self.remove_all_widgets()
        bg = Image(self.images['inventory'], (0, 0))
        self.addwidget(bg)

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

        # create items
        counterx = 0
        countery = 0
        for item in self.player.inventory:
            px = counterx * 64 + self.inventoryoffset[0] + 25
            py = countery * 32 + self.inventoryoffset[1] + 30
            # make grid
            px += counterx * 30
            py += countery * 15

            # grid image
            gridimage = Image(self.images['grid2'], (px, py))
            self.addwidget(gridimage)

            # item button
            img = self.images['object' + str(item)]
            itembutton = Button("", (px, py), img)
            itembutton.connect("clicked", self.on_item_select, itemid=item)
            itembutton.connect("onenter", self.on_item_enter, itemid=item)
            itembutton.connect("onleave", self.on_item_leave, itemid=item)
            self.addwidget(itembutton)

            # item count
            text = str(self.player.itemscounter[str(item)])
            itemcount = Label(text, (px + 40, py + 16), align="center")
            self.addwidget(itemcount)

            # limit
            counterx += 1
            if counterx == self.inventorysize[0]:
                counterx = 0
                countery += 1
            if countery == self.inventorysize[1]:
                break
Example #7
0
class GameOverView(View):
    btn_replay = None
    btn_exit = None
    context = None
    game_over = None

    def __init__(self, context):
        self.btn_replay = Button('Replay Game', self._on_start)
        self.btn_exit = Button('Exit Game', self._on_exit)
        font = pygame.font.SysFont('arial', 32)
        self.game_over = font.render('Game Over', True, (0, 0, 0))
        self.context = context

    def on_draw(self):

        s_w, s_h = self.context.screen.get_size()
        l_w, l_h = self.game_over.get_size()
        x, y, bs_w, bs_h = self.btn_replay.get_box()
        x, y, be_w, be_h = self.btn_exit.get_box()

        # 所有元素高度
        y_h = bs_h + be_h + l_h + 4 + 50

        y_start = s_h / 2 - y_h / 2 + 50
        '''
        界面元素排版
        '''
        self.btn_replay.pos = (s_w / 2 - bs_w / 2, y_start)
        self.btn_exit.pos = (s_w / 2 - be_w / 2, y_start + bs_h + 4)
        self.context.screen.blit(self.game_over,
                                 (s_w / 2 - l_w / 2, s_h / 2 - y_h / 2))
        # 绘制按钮
        self.btn_replay.on_draw(self.context.screen)
        self.btn_exit.on_draw(self.context.screen)

    def _on_exit(self):
        # 控制退出状态
        print('exit game')
        self.context.running = False

    def _on_start(self):
        # 切换界面到游戏界面
        print('start game')
        self.context.view = GameView(self.context)

    def on_event(self, event):
        # 监控各种事件
        self.btn_replay.on_event(event)
        self.btn_exit.on_event(event)
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)
Example #9
0
class MenuWindow(Container):
    """MenuWindow

    """
    def __init__(self):
        self.parent = None
        Container.__init__(self, 800, 600, (0, 0))
        self.running = True

        self.menupos = 0
        self.maxmenupos = 1

        # background
        imgpath = os.path.join("images", "gui", "mainmenubg.png")
        bgimage = pygame.image.load(imgpath).convert_alpha()
        bg = Image(bgimage, (0, 0))
        self.addwidget(bg)

        # start button
        self.menucursor = Label("-> ", (230, 120),
                                color=(255, 255, 0), size=20)
        self.addwidget(self.menucursor)

        # start button
        self.startbutton = Button("Start game / Continue", (270, 120),
                                  color=(255, 255, 200), labelsize=20)
        self.startbutton.connect("clicked", self.on_startgame)
        self.addwidget(self.startbutton)

        # Quit button
        self.quitbutton = Button("Quit", (270, 160),
                                 color=(255, 0, 0),
                                 labelsize=20)
        self.quitbutton.connect("clicked", self.on_quit)
        self.addwidget(self.quitbutton)

        # Show window
        self.show()

    def on_quit(self, widget, **data):
        """quit

        :param widget:
        :param data:
        :return:
        """
        self.running = False

    def on_startgame(self, widget, **data):
        """start game

        :param widget:
        :param data:
        :return:
        """
        self.startbutton.settext("Loading...")
        self.parent.gamescreen = GameWindow()
        self.parent.set_active_screen(self.parent.gamescreen)
        self.parent.gamescreen.init()
        self.parent.inmenu = False
        self.parent.ingame = True
        self.running = False

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

        :param surface:
        :return:
        """
        Container.draw(self, surface)

    def update_menu_cursor(self):
        """update menu cursor

        :return:
        """
        if self.menupos < 0:
            self.menupos = 0
        if self.menupos > self.maxmenupos:
            self.menupos = self.maxmenupos
        newpos = [230, 120 + 40 * self.menupos]
        self.menucursor.position = newpos
        self.repaint()

    def events(self):
        """events

        :return:
        """
        for event in pygame.event.get():
            # poll event to window
            self.poll_event(event)

            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    self.menupos += 1
                    self.update_menu_cursor()
                if event.key == pygame.K_UP:
                    self.menupos -= 1
                    self.update_menu_cursor()
                if event.key == pygame.K_RETURN:
                    if self.menupos == 0:
                        self.on_startgame(None)
                    if self.menupos == 1:
                        self.running = False
Example #10
0
    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
Example #11
0
 def __init__(self, context):
     self.btn_replay = Button('Replay Game', self._on_start)
     self.btn_exit = Button('Exit Game', self._on_exit)
     font = pygame.font.SysFont('arial', 32)
     self.game_over = font.render('Game Over', True, (0, 0, 0))
     self.context = context
Example #12
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)
Example #13
0
class MenuWindow(Container):
    """MenuWindow

    """
    def __init__(self):
        self.parent = None
        Container.__init__(self, 800, 600, (0, 0))
        self.running = True

        self.menupos = 0
        self.maxmenupos = 1

        # background
        imgpath = os.path.join("images", "gui", "mainmenubg.png")
        bgimage = pygame.image.load(imgpath).convert_alpha()
        bg = Image(bgimage, (0, 0))
        self.addwidget(bg)

        # start button
        self.menucursor = Label("-> ", (230, 120),
                                color=(255, 255, 0),
                                size=20)
        self.addwidget(self.menucursor)

        # start button
        self.startbutton = Button("Start game / Continue", (270, 120),
                                  color=(255, 255, 200),
                                  labelsize=20)
        self.startbutton.connect("clicked", self.on_startgame)
        self.addwidget(self.startbutton)

        # Quit button
        self.quitbutton = Button("Quit", (270, 160),
                                 color=(255, 0, 0),
                                 labelsize=20)
        self.quitbutton.connect("clicked", self.on_quit)
        self.addwidget(self.quitbutton)

        # Show window
        self.show()

    def on_quit(self, widget, **data):
        """quit

        :param widget:
        :param data:
        :return:
        """
        self.running = False

    def on_startgame(self, widget, **data):
        """start game

        :param widget:
        :param data:
        :return:
        """
        self.startbutton.settext("Loading...")
        self.parent.gamescreen = GameWindow()
        self.parent.set_active_screen(self.parent.gamescreen)
        self.parent.gamescreen.init()
        self.parent.inmenu = False
        self.parent.ingame = True
        self.running = False

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

        :param surface:
        :return:
        """
        Container.draw(self, surface)

    def update_menu_cursor(self):
        """update menu cursor

        :return:
        """
        if self.menupos < 0:
            self.menupos = 0
        if self.menupos > self.maxmenupos:
            self.menupos = self.maxmenupos
        newpos = [230, 120 + 40 * self.menupos]
        self.menucursor.position = newpos
        self.repaint()

    def events(self):
        """events

        :return:
        """
        for event in pygame.event.get():
            # poll event to window
            self.poll_event(event)

            if event.type == pygame.QUIT:
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    self.menupos += 1
                    self.update_menu_cursor()
                if event.key == pygame.K_UP:
                    self.menupos -= 1
                    self.update_menu_cursor()
                if event.key == pygame.K_RETURN:
                    if self.menupos == 0:
                        self.on_startgame(None)
                    if self.menupos == 1:
                        self.running = False
Example #14
0
    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 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)
Example #16
0
text = 'Play music with any keydown'

clock = pygame.time.Clock()
'''
初始化音频播放器
'''
# 初始化
pygame.mixer.init()


def click_test():
    print('button clicked')


button = Button(text='Start Game', callable=click_test)

# 1. 游戏死循环
while running:
    # 2. 获取事件流
    for event in pygame.event.get():
        button.on_event(event)
        # 3. 处理事件流
        if event.type == QUIT:
            # 结束运行
            running = False
    screen.fill((0xff, 0xff, 0xff))
    button.on_draw(screen)
    # 3. 刷新显示窗口
    pygame.display.flip()
    clock.tick(60)
Example #17
0
    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)