예제 #1
0
 def __init__(self, chest_inventory, player, imageurl):
     super(ChestGUI, self).__init__(player, imageurl)
     self.chest_inventory = chest_inventory
     self.transfer_down_image = Images.load_imageurl("img/gui/arrow_down.png")
     self.transfer_up_image = Images.load_imageurl("img/gui/arrow_up.png")
     self.transfer_down_position = (self.left + GUI.SCALING * 5 / 8, self.top + GUI.SCALING * 5 / 8)
     self.transfer_up_position = (self.left + GUI.SCALING * 5 / 8, self.top + GUI.SCALING * 39 / 8)
예제 #2
0
def doRawImageFileWithURL(context):
    url = GetURL(kRawColorImage)

    if url is not None:
        Images.drawImageFromURL(context, url,
            RAW_IMAGE_WIDTH, RAW_IMAGE_HEIGHT,
            8, True);   # 8 bits per component, isColor = True
예제 #3
0
def doRawImageFileWithCallbacks(context):
    url = GetURL(kRawColorImage)

    if url is not None:
        Images.doImageWithCallbacksCreatedFromURL(context, url,
                                                  RAW_IMAGE_WIDTH,
                                                  RAW_IMAGE_HEIGHT, 8, True)
예제 #4
0
def doRawImageFileWithCallbacks(context):
    url = GetURL(kRawColorImage)

    if url is not None:
        Images.doImageWithCallbacksCreatedFromURL(context, url,
                RAW_IMAGE_WIDTH, RAW_IMAGE_HEIGHT, 
                8, True);   # 8 bits per component, isColor = True
class Function(QtGui.QWidget,functions.Ui_functions):

    def __init__(self, conn, stackedWidget, parent=None):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.listImage.clicked.connect(lambda: self.toListImages(conn,stackedWidget))
        self.back1.clicked.connect(lambda  : self.toCreds(stackedWidget))
        self.window4 = None
        self.window5 = None
        self.window6 = None
        self.window7 = None
        self.window8 = None
        self.window9 = None
        self.window10 = None
        self.window11 = None
        self.window12 = None

    def toListImages(self,conn,stackedWidget):
        images = conn.list_images()
        if self.window4 == None:
            self.window4 = Images(images)
        self.window4.show()

    def toCreds(self,stackedWidget):
        creds=Creds(stackedWidget)
        stackedWidget.addWidget(creds)
        stackedWidget.setCurrentWidget(creds)
예제 #6
0
 def showTimer(self):
     image.Number(self.window, 204, 310, int((self.game.time / 1000) * 6))
     image.Number(self.window, 216, 310,
                  int((self.game.time / 1000) * 60) % 10)
     image.Number(self.window, 236, 310,
                  int((self.game.time / 1000) * 600) % 10)
     image.Number(self.window, 248, 310,
                  int((self.game.time / 1000) * 6000) % 10)
예제 #7
0
파일: Game.py 프로젝트: WasLop/Flappy_Bat
 def __init__(self, screen):
     self.screen = screen
     self.backgrounds = Images.background()
     self.backgrounds.background1 = self.backgrounds.set_size(
         self.backgrounds.background1, (5000, self.screen.get_height()))
     self.myfont1 = pygame.font.SysFont("Rosewood Std Regular", 70)
     self.events = events()
     self.pointer = Images.pointer()
     self.pos = (210, 120)
예제 #8
0
    def makingPuzzle(self):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        if mouse_x < 86 or mouse_x > 179 or mouse_y < 132 or mouse_y > 225:
            self.making_puzzle = False
            return

        ini_x = ini_y = -1
        pos_x = int((mouse_x - 86) / 15)
        pos_y = int((mouse_y - 132) / 15)

        for i in range(6):
            for j in range(6):
                if self.selected_piece[i][j] == 2:
                    ini_x = j
                    ini_y = i

        if pos_x != ini_x:
            if pos_x > ini_x:
                perm_x = [1, 2, 3, 4, 5, 0]
            else:
                perm_x = [5, 0, 1, 2, 3, 4]

            id_ = np.empty_like(perm_x)
            id_[perm_x] = np.arange(len(perm_x))
            self.selected_piece[:] = self.selected_piece[:, id_]

            if (self.selected_piece[:, 0] >
                    0).any() and (self.selected_piece[:, 5] > 0).any():
                self.making_puzzle = False
                return

        if pos_y != ini_y:
            if pos_y < ini_y:
                perm_y = [1, 2, 3, 4, 5, 0]
            else:
                perm_y = [5, 0, 1, 2, 3, 4]
            self.selected_piece[[0, 1, 2, 3, 4,
                                 5]] = self.selected_piece[perm_y]

            if (self.selected_piece[0] > 0).any() and (self.selected_piece[5] >
                                                       0).any():
                self.making_puzzle = False
                return

        table = np.copy(self.puzzle)
        for i in range(6):
            for j in range(6):
                if self.selected_piece[i][j] > 0:
                    if table[i][j] >= 0:
                        table[i][j] = 13
                    else:
                        table[i][j] = 14

        for i in range(6):
            for j in range(6):
                image.tileColor(self.window, 84 + 16 * i, 130 + 16 * j,
                                table[j][i])
예제 #9
0
def getImg():
    UpdateEverything()
    Im.generateImage()
    # update list
    giflst.clear()
    gif = os.listdir("output_img")
    for g in gif:
        if g.endswith(".gif"):
            giflst.append(g)
    animateCombo.config(values=sorted(giflst))
예제 #10
0
def getUMOSimg():
    UpdateEverything()
    t = UmosImgLocation.get()
    Im.generateUMOSImage(t)
    # this part updates the list
    giflst.clear()
    gif = os.listdir("output_img/")
    for g in gif:
        if g.endswith(".gif"):
            giflst.append(g)
    animateCombo.config(values=sorted(giflst))
예제 #11
0
    def showUserPlaces(self):
        image.Pos(self.window, 284, 84, self.game.player_human.game_place)

        if self.game.isAIPlaying(0):
            image.Pos(self.window, 1024, 80, self.game.player_ai[0].game_place)

        if self.game.isAIPlaying(1):
            image.Pos(self.window, 284, 398, self.game.player_ai[1].game_place)

        if self.game.isAIPlaying(2):
            image.Pos(self.window, 1024, 394,
                      self.game.player_ai[2].game_place)
예제 #12
0
파일: Button.py 프로젝트: kaikue/Oceania
 def __init__(self, pos, text, effect, small = False):
     self.pos = pos
     self.text = text
     self.effect = effect
     self.pressed = False
     self.font = Game.get_font()
     if small:
         url_base = "img/gui/button_small"
     else:
         url_base = "img/gui/button"
     self.unpressed_image = Images.load_imageurl(url_base + "_up.png")
     self.hovered_image = Images.load_imageurl(url_base + "_hover.png")
     self.pressed_image = Images.load_imageurl(url_base + "_down.png")
예제 #13
0
    def showUserGems(self):
        for i in range(4):
            image.Number(self.window, 194 + 32 * i, 208,
                         int(self.game.player_human.gems[i] / 10))
            image.Number(self.window, 206 + 32 * i, 208,
                         self.game.player_human.gems[i] % 10)

        if self.game.isAIPlaying(0):
            for i in range(4):
                image.Number(self.window, 932 + 32 * i, 204,
                             int(self.game.player_ai[0].gems[i] / 10))
                image.Number(self.window, 944 + 32 * i, 204,
                             self.game.player_ai[0].gems[i] % 10)

        if self.game.isAIPlaying(1):
            for i in range(4):
                image.Number(self.window, 194 + 32 * i, 520,
                             int(self.game.player_ai[1].gems[i] / 10))
                image.Number(self.window, 206 + 32 * i, 520,
                             self.game.player_ai[1].gems[i] % 10)

        if self.game.isAIPlaying(2):
            for i in range(4):
                image.Number(self.window, 932 + 32 * i, 516,
                             int(self.game.player_ai[2].gems[i] / 10))
                image.Number(self.window, 944 + 32 * i, 516,
                             self.game.player_ai[2].gems[i] % 10)
예제 #14
0
파일: Player.py 프로젝트: kaikue/Oceania
 def load_images_for(self, directory):
     img_idle_l = Images.load_imageurl("img/player/" + directory + "/idle.png")
     img_idle_r = Images.flip_horizontal(img_idle_l)
     imgs_idle = (img_idle_l, img_idle_r)
     img_swim_1_l = Images.load_imageurl("img/player/" + directory + "/swim1.png")
     img_swim_1_u = Images.rotate(img_swim_1_l, -90)
     img_swim_1_r = Images.flip_horizontal(img_swim_1_l)
     img_swim_1_d = Images.rotate(img_swim_1_l, 90)
     imgs_swim_1 = (img_swim_1_l, img_swim_1_u, img_swim_1_r, img_swim_1_d)
     img_swim_2_l = Images.load_imageurl("img/player/" + directory + "/swim2.png")
     img_swim_2_u = Images.rotate(img_swim_2_l, -90)
     img_swim_2_r = Images.flip_horizontal(img_swim_2_l)
     img_swim_2_d = Images.rotate(img_swim_2_l, 90)
     imgs_swim_2 = (img_swim_2_l, img_swim_2_u, img_swim_2_r, img_swim_2_d)
     return (imgs_idle, imgs_swim_1, imgs_swim_2)
예제 #15
0
    def showUnknownPieces(self):
        for i in range(4):
            image.Piece(self.window, 194 + 32 * i, 136, 12)

        if self.game.isAIPlaying(0):
            for i in range(4):
                image.Piece(self.window, 932 + 32 * i, 132, 12)

        if self.game.isAIPlaying(1):
            for i in range(4):
                image.Piece(self.window, 194 + 32 * i, 448, 12)

        if self.game.isAIPlaying(2):
            for i in range(4):
                image.Piece(self.window, 932 + 32 * i, 444, 12)
예제 #16
0
    def run(self):
        """ Perform Threaded Action """

        # get variables here
        path = self.path

        validExt = ["jpg", "jpeg"]

        count = 0

        for root, dirs, files in os.walk(path):
            for f in files:
                if (f.lower()[f.rfind(".") + 1:] in validExt):
                    self.im.append(Images.loader(root, f))
                    tmpim = Image.open(os.path.join(root, f))
                    tmpim.thumbnail((125, 125))
                    tmpim = Conversions.padpiltoimage(tmpim, 125,
                                                      125).ConvertToBitmap()

                    self.il.Add(tmpim)
                    count += 1

                    wx.PostEvent(self.frame, ReturnFunction(count, self.id, 0))

        self.imList.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
        #self.imList.SetImageList(self.il, wx.IMAGE_LIST_NORMAL)

        self.imList.InsertColumn(0, '', width=130)

        for i in range(count):
            self.imList.InsertStringItem(i, '')
            self.imList.SetItemImage(i, i)

        wx.PostEvent(self.frame, ReturnFunction("Ready...", self.id, 1))
예제 #17
0
    def __init__(self, *args, **kwds):
        # begin wxGlade: PreferencesDlg.__init__
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        wx.Dialog.__init__(self, *args, **kwds)
        self.panel_3 = wx.Panel(self, -1)
        self.l_dbfile = wx.StaticText(self.panel_3, -1, _("Database file"))
        self.dbfile = wx.TextCtrl(self.panel_3, ID_DB, "", style=wx.TE_READONLY)
        self.b_ok = wx.Button(self.panel_3, wx.ID_OK, "")
        self.b_apply = wx.Button(self.panel_3, wx.ID_APPLY, "")
        self.b_cancel = wx.Button(self.panel_3, wx.ID_CANCEL, "")

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_TEXT, self.OnChanged, id=ID_DB)
        self.Bind(wx.EVT_BUTTON, self.OnOK, self.b_ok)
        self.Bind(wx.EVT_BUTTON, self.OnApply, self.b_apply)
        # end wxGlade

        self.b_dbfile = wx.BitmapButton(self.panel_3, -1, bitmap=Images.getNetwork_server_databaseBitmap())
        self.Bind(wx.EVT_BUTTON, self.OnDBfile, self.b_dbfile)
        self.__do_layout_nowxglade()

        self.obj = defaultdict()

        # Register PubSub Listener
        pub.subscribe(self.Populate, 'dialog.preferences.populate') #@UndefinedVariable
예제 #18
0
    def run(self):
        """ Perform Threaded Action """

        # get variables here
        path = self.path

        validExt = ["jpg","jpeg"]

        count = 0

        for root, dirs, files in os.walk(path):
            for f in files:
                if(f.lower()[f.rfind(".")+1:] in validExt):
                    self.im.append(Images.loader(root,f))
                    tmpim = Image.open(os.path.join(root,f))
                    tmpim.thumbnail((125,125))
                    tmpim = Conversions.padpiltoimage(tmpim,125,125).ConvertToBitmap()

                    self.il.Add(tmpim)
                    count += 1

                    wx.PostEvent(self.frame,ReturnFunction(count,self.id,0))

        self.imList.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
        #self.imList.SetImageList(self.il, wx.IMAGE_LIST_NORMAL)

        self.imList.InsertColumn(0,'',width=130)

        for i in range(count):
            self.imList.InsertStringItem(i,'')
            self.imList.SetItemImage(i,i)

        wx.PostEvent(self.frame, ReturnFunction("Ready...",self.id,1))
예제 #19
0
    def manejar_video(self, video, socket):
        if (len(self) == 0):
            print("No hay ningun servidor de procesamiento registrado")
            return

        video_name = GetName()

        video_file = open(f'Videos/{video_name}.mp4', 'wb')
        video_file.write(video)

        Images.VideoToImage(f'Videos/{video_name}.mp4', video_name)

        frames = []

        for item in os.listdir(f'Images{video_name}/'):
            if (os.path.isfile(f"Images{video_name}/{item}")):
                frames.append(item)

        images_to_share = math.floor(len(frames) / len(self)) + 1
        shared_images = 0

        for i in range(len(self)):
            if (i != len(self) - 1):
                print(
                    f"Enviando al servidor {i} para que procese imagenes del {shared_images + 1} a {shared_images + images_to_share}"
                )
                shared_images += images_to_share
            else:
                print(
                    f"Enviando al servidor {i} para que procese imagenes del {shared_images + 1} a {len(frames) - 1}"
                )

        socket.send(b'{"type": "VIDEO_COMPLETE"}')
예제 #20
0
파일: Menu.py 프로젝트: kaikue/Oceania
 def __init__(self, buttons, labels = [], background = False):
     self.mouse_pressed = False
     self.buttons = buttons
     self.labels = labels
     self.background = background
     if background:
         self.background_img = Images.load_imageurl("img/gui/menu_background.png")
예제 #21
0
 def addWindowToolBar(self, parent):
     """Toolbar for changing frame views"""
     toolbar = ToolBar(parent, self)
     img = Images.closeframe()
     hlptxt="Close current sideframe"
     toolbar.addButton('tile vertical', self.closeChildFrame, img, hlptxt)
     img = Images.detachframe()
     hlptxt="Detach current sideframe as seperate window"
     toolbar.addButton('tile vertical', self.detachChildFrame, img, hlptxt)
     img = Images.tilevertical()
     hlptxt="Tile frames vertically"
     toolbar.addButton('x', self.tileVertical, img, hlptxt)
     img = Images.tilehorizontal()
     hlptxt="Tile frames horizontally"
     toolbar.addButton('tile horizontal', self.tileHorizontal, img, hlptxt)
     return toolbar
예제 #22
0
 def addWindowToolBar(self, parent):
     """Toolbar for changing frame views"""
     toolbar = ToolBar(parent, self)
     img = Images.closeframe()
     hlptxt = "Close current sideframe"
     toolbar.addButton('tile vertical', self.closeChildFrame, img, hlptxt)
     img = Images.detachframe()
     hlptxt = "Detach current sideframe as seperate window"
     toolbar.addButton('tile vertical', self.detachChildFrame, img, hlptxt)
     img = Images.tilevertical()
     hlptxt = "Tile frames vertically"
     toolbar.addButton('x', self.tileVertical, img, hlptxt)
     img = Images.tilehorizontal()
     hlptxt = "Tile frames horizontally"
     toolbar.addButton('tile horizontal', self.tileHorizontal, img, hlptxt)
     return toolbar
예제 #23
0
 def createToolBar(self):
     """Toolbar"""
     self.toolbar = ToolBar(self.main, self)
     self.toolbar.pack(side=TOP,fill=X,pady=1,before=self.m)
     img = Images.openproject()
     hlptxt="Open Project from file"
     self.toolbar.addButton('Open Project', self.openProject, img, hlptxt)
     img = Images.saveproject()
     hlptxt="Save Project"
     self.toolbar.addButton('Save Project', self.openProject, img, hlptxt)
     img = Images.undo()
     hlptxt="Undo"
     self.toolbar.addButton('Save Project', self.openProject, img, hlptxt)
     img = Images.zoomout()
     hlptxt="Zoom Out"
     self.toolbar.addButton('Save Project', self.sc.zoomOut, img, hlptxt)
     img = Images.zoomin()
     hlptxt="Zoom In"
     self.toolbar.addButton('Save Project', self.sc.zoomIn, img, hlptxt)
     img = Images.windowprefs()
     hlptxt="Seqeuence display preferences"
     self.toolbar.addButton('Seqeuence display preferences', self.sc.showPrefs,
                      img, hlptxt)
     img = Images.prefs()
     hlptxt="Preferences"
     self.toolbar.addButton('Preferences', self.globalPrefsDialog, img, hlptxt)
     return
예제 #24
0
 def createToolBar(self):
     """Toolbar"""
     self.toolbar = ToolBar(self.main, self)
     self.toolbar.pack(side=TOP, fill=X, pady=1, before=self.m)
     img = Images.openproject()
     hlptxt = "Open Project from file"
     self.toolbar.addButton('Open Project', self.openProject, img, hlptxt)
     img = Images.saveproject()
     hlptxt = "Save Project"
     self.toolbar.addButton('Save Project', self.openProject, img, hlptxt)
     img = Images.undo()
     hlptxt = "Undo"
     self.toolbar.addButton('Save Project', self.openProject, img, hlptxt)
     img = Images.zoomout()
     hlptxt = "Zoom Out"
     self.toolbar.addButton('Save Project', self.sc.zoomOut, img, hlptxt)
     img = Images.zoomin()
     hlptxt = "Zoom In"
     self.toolbar.addButton('Save Project', self.sc.zoomIn, img, hlptxt)
     img = Images.windowprefs()
     hlptxt = "Seqeuence display preferences"
     self.toolbar.addButton('Seqeuence display preferences',
                            self.sc.showPrefs, img, hlptxt)
     img = Images.prefs()
     hlptxt = "Preferences"
     self.toolbar.addButton('Preferences', self.globalPrefsDialog, img,
                            hlptxt)
     return
예제 #25
0
파일: Menu.py 프로젝트: kaikue/Oceania
 def __init__(self, text, pos, small = False):
     self.text = text
     self.pos = pos
     if small:
         imgurl = "img/gui/label_small.png"
     else:
         imgurl = "img/gui/label.png"
     self.img = Images.load_imageurl(imgurl)
     self.font = Game.get_font()
예제 #26
0
파일: Game.py 프로젝트: WasLop/Flappy_Bat
 def __init__(self, screen):
     self.img = Images.player()
     self.size_player = self.img.get_size(screen, 13, 10)
     self.img.player_image = self.img.set_size(self.img.player_image,
                                               self.size_player)
     self.pos = (screen.get_width() / 2 - 100, screen.get_height() / 2)
     self.speed = 20
     self.fl = False
     self.pos_max = self.pos[1] - 80
예제 #27
0
    def __init__(self, master, app=None):

        Frame.__init__(self, master)
        self.app = app
        self.E = None
        if hasattr(self.app,'p'):
            self.p = self.app.p     #reference to pipeline object
        fr = Frame(self)
        self.totalvar = IntVar()
        lfr=Frame(fr)
        lfr.pack()
        Label(lfr,text='Datasets:').pack(side=LEFT,fill=BOTH)
        l=Label(lfr,text='',textvariable=self.totalvar)
        l.pack(side=LEFT,fill=BOTH)
        b=Button(fr,text='update',command=self.update)
        b.pack(side=TOP,fill=BOTH)
        self.previmg = Images.prev()
        b=Button(fr,text='prev',image=self.previmg,compound='left',command=self.prev)
        b.pack(side=TOP,fill=BOTH)
        self.nextimg = Images.next()
        b=Button(fr,text='next',image=self.nextimg,compound='left',command=self.next)
        b.pack(side=TOP,fill=BOTH)
        self.numplotscounter = Pmw.Counter(fr,
                labelpos='w',
                label_text='plots:',
                entryfield_value=1,
                entry_width=3,
                datatype = 'integer',
                entryfield_command=self.replot,
                entryfield_validate={'validator':'numeric', 'min':1,'max':12})
        self.numplotscounter.pack()
        self.overlayvar = BooleanVar(); self.overlayvar.set(False)
        Checkbutton(fr, text='overlay plots', variable=self.overlayvar, command=self.replot).pack(side=TOP,fill=BOTH)
        self.normalizevar = BooleanVar(); self.normalizevar.set(False)
        Checkbutton(fr, text='normalize', variable=self.normalizevar, command=self.replot).pack(side=TOP,fill=BOTH)

        fr.pack(side=LEFT)
        self.plotframe = PlotPanel(parent=self, side=BOTTOM, height=200, tools=True)
        self.dsindex = 0
        self.plotframe.Opts.opts['fontsize']=10

        b=Button(fr,text='open in Ekin',command=self.loadEkin)
        b.pack(side=TOP,fill=BOTH)
        return
예제 #28
0
def main():

    # The main path is the place where the quote file is kept, along with the videos, and their subtitles
    fortune_file_path = Path(sys.argv[2].replace('\"', ''))
    base_path = Path(sys.argv[1].replace('\"', ''))
    # Modifing the quotes file from the actual fortune format to something managable, with warped lines
    # and removing the quotes that are too big to fit on a photo.

    try:
        os.mkdir(os.path.join(base_path, 'Wallpapers'))
    except:
        print('folders already exist')

    try:
        os.mkdir(os.path.join(base_path, 'Frames'))
    except:
        print('folders already exist')
    qt.modify_quotes(base_path, fortune_file_path)

    # Removing the brackets from the modified fortune files, putting into one chunk of string.
    quotes = qt.remove_brackets(os.path.join(
        base_path, f'Mod_{fortune_file_path.name}'))

    # making a quotelist, without the brackets so its ready for subtitles search
    quote_list = qt.make_quote_list(quotes)

    # making a list of just the search terms
    quote_search_list = qt.make_quote_search_list(quote_list)

    # Extracting the frames from the timestamps we got before.
    im.extract_frames(base_path, quote_search_list)

    # iterating over the extracted frames and putting text over them
    frames_path = Path(os.path.join(base_path, 'Frames'))
    files_in_frames = list(frames_path.iterdir())

    for _, item in enumerate(files_in_frames):
        if item.suffix == '.jpg':
            im.make_wallpapers(base_path, item, quote_list)

    # Remove the temporary folders and files.
    shutil.rmtree(os.path.join(base_path, 'Frames'))
    os.remove(os.path.join(base_path, f'Mod_{fortune_file_path.name}'))
예제 #29
0
파일: World.py 프로젝트: kaikue/Oceania
def load_items():
    items_file = open("items.json", "r")
    global items
    items = json.load(items_file)
    items_file.close()
    for itemname in items.keys():
        item = items[itemname]
        item["can_place"] = False
        if "class" not in item.keys():
            item["class"] = "ItemStack"
        if isinstance(item["description"], str):
            item["description"] = [item["description"]]
        img = Images.load_imageurl(item["image"])
        
        img_rotated = Images.rotate(img, 90)
        item_images[itemname] = [img,
                                Images.flip_horizontal(img),
                                img_rotated,
                                Images.flip_horizontal(img_rotated),
                                Images.flip_completely(img)]
예제 #30
0
파일: _App.py 프로젝트: kurtu5/Labeler
    def start(self):
        # I don't think I need further access to instances, but I'll save them anyway
        #        self.root = tk.Tk()
        self.parent = QtWidgets.QApplication([])

        # Gui to handle all main window operations
        self.guiO = Gui.Observer(
        )  # model observer callbacks to presenter set here
        self.guiM = Gui.Model('gui')
        self.guiV = Gui.View(self.parent)
        self.guiI = Gui.Interactor(
        )  # widget event callbacks to presenter set here
        self.guiP = Gui.Presenter(self.guiV, self.guiI, self.guiM, self.guiO)

        # Menu for Gui
        self.menuO = MenuBar.Observer()
        self.menuM = MenuBar.Model('menu')
        self.menuV = MenuBar.View(self.guiV)
        self.menuI = MenuBar.Interactor()
        self.menuP = MenuBar.Presenter(self.menuV, self.menuI, self.menuM,
                                       self.menuO)

        #        # Testing window
        self.testO = TestWindow.Observer()
        self.testM = TestWindow.Model('test')
        self.testV = TestWindow.View(self.guiV)
        self.testI = TestWindow.Interactor()
        self.testP = TestWindow.Presenter(self.testV, self.testI, self.testM,
                                          self.testO)
        #
        #        # Generic
        #        self.genM = GenericWindow.Model('generic', {'gui': self.guiM})
        #        self.genV = GenericWindow.View(self.guiV.window)
        #        self.genP = GenericWindow.Presenter(self.genV, self.genM)

        # Image labeling window
        self.imagesM = Images.Model('images')
        self.labelerO = LabelerWindow.Observer()
        self.labelerM = LabelerWindow.Model('labeler')
        self.labelerV = LabelerWindow.View(self.guiV)
        self.labelerI = LabelerWindow.Interactor()
        self.labelerP = LabelerWindow.Presenter(self.labelerV, self.labelerI,
                                                self.labelerM, self.labelerO)

        #         Options window
        self.optionsO = OptionsWindow.Observer()
        self.optionsM = OptionsWindow.Model('options')
        self.optionsV = OptionsWindow.View(self.guiV)
        self.optionsI = OptionsWindow.Interactor()
        self.optionsP = OptionsWindow.Presenter(self.optionsV, self.optionsI,
                                                self.optionsM, self.optionsO)

        # Make labeler the default window
        self.guiM.window_model_activate('labeler')
예제 #31
0
def init_aliens():
  global aliens
  alienX = 0
  alienY = 50
  for row in range(alien_rows):
    for i in range(alien_cols):
      alienX = i * 74 # 64 + 10
      alienY = row * 55 + 50
      alien = { "image" : Images.GetAlienImage(alienInfo[row][0]), "x" : alienX, "y" : alienY, "score" : alienInfo[row][1] }
      aliens.append(alien)
  print("alien init")
예제 #32
0
 def load_image(self):
     self.img = None
     self.imgs = []
     img = pygame.Surface((Game.BLOCK_SIZE * 3, Game.BLOCK_SIZE * 3), pygame.SRCALPHA, 32).convert_alpha() #not game scale
     center = img.get_rect().center
     #TODO: blit small diagonal arm image on img (after blitting item? but before rotation)
     if self.item is not None:
         #TODO: self.item may be a dummy pickled object that hasn't been loaded- what should we do?
         #does the parent reference also get lost? that would be bad
         #self.item.load_image()
         item_img = self.item.imgs[0]
         item_img = Images.scale(item_img, 1 / Game.SCALE)
         img.blit(item_img, (0, 0))
     start_deg = math.degrees(self.angle_start - 2 * self.angle_mid)
     end_deg = math.degrees(self.angle_end - 2 * self.angle_mid)
     for i in range(0, self.max_decay + 1, FRAME_LENGTH):
         t = (self.max_decay - i) / self.max_decay
         angle = (1 - t) * start_deg + t * end_deg + 225
         rotated_img = Images.rotate(img, angle)
         rotated_img.get_rect().center = center
         self.imgs.append(Images.scale(rotated_img, Game.SCALE))
예제 #33
0
 def loadSinks(self):
     self.sink_list.add(Info.init())
     self.sink_list.add(Buttons.init())
     self.sink_list.add(Menus.init())
     self.sink_list.add(Images.init())
     self.sink_list.add(Layouts.init())
     self.sink_list.add(Lists.init())
     self.sink_list.add(Popups.init())
     self.sink_list.add(Tables.init())
     self.sink_list.add(Text.init())
     self.sink_list.add(Trees.init())
     self.sink_list.add(Frames.init())
     self.sink_list.add(Tabs.init())
예제 #34
0
파일: Game.py 프로젝트: WasLop/Flappy_Bat
 def __init__(self, screen):
     self.options = options()
     self.screen = screen
     self.clock = pygame.time.Clock()
     self.backgrounds = Images.background()
     self.backgrounds.background1 = self.backgrounds.set_size(
         self.backgrounds.background1, (5000, self.screen.get_height()))
     self.events = events()
     self.x_city = 0
     self.player = player(self.screen)
     self.pipe = pipe()
     self.loop = True
     self.score = score()
예제 #35
0
 def loadSinks(self):
     self.sink_list.addSink(Info.init())
     self.sink_list.addSink(Buttons.init())
     self.sink_list.addSink(Menus.init())
     self.sink_list.addSink(Images.init())
     self.sink_list.addSink(Layouts.init())
     self.sink_list.addSink(Lists.init())
     self.sink_list.addSink(Popups.init())
     self.sink_list.addSink(Tables.init())
     self.sink_list.addSink(Text.init())
     self.sink_list.addSink(Trees.init())
     self.sink_list.addSink(Frames.init())
     self.sink_list.addSink(Tabs.init())
예제 #36
0
파일: Helper.py 프로젝트: shambo001/peat
 def formatPanel(self):
     """Showing format options"""
     self.img1 = Images.formatsDiagram()
     label1 = Label(self.main,image=self.img1)
     label1.pack(fill=BOTH,padx=4,pady=4,ipadx=2,ipady=2)
     text = """The layout/format of your data is specified in the configuration
     file under the 'format' keyword. 8 typical formats
     are built into DataPipeline, covering most simple cases."""
     text=text.replace('\t','')
     Label(self.main,text=text,wraplength=600).pack(fill=Y,side=TOP,pady=4)
     panel2 = Frame(self.main)
     panel2.pack(fill=Y,side=BOTTOM)
     self.doButtons(panel2)
     return
예제 #37
0
def main():
    images = Images.ImagesController(vehicles_path="C:\\Users\\orik\\DLImages\\vehicles\\",
                                     non_vehicles_path="C:\\Users\\orik\\DLImages\\non-vehicles\\",
                                     batch_size=100)
    ff = images.get_next_batch()
    file = images._get_next_path(True)
    f = cv2.imread(file)
    cv2.imshow("image1", f)
    f2 = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
    cv2.imshow("image2", f2)
    while True:
        key = cv2.waitKey(1) & 0xFF
        if key == 27:
            break
예제 #38
0
 def runConfig(self):
     image.gameConfig(self.window, 0, 0)
     image.Number(self.window, 560, 292, int(
         (self.game.set_time / 1000) * 6))
     image.Number(self.window, 572, 292,
                  int((self.game.set_time / 1000) * 60) % 10)
     image.Number(self.window, 566, 348, self.game.set_turn)
     image.Number(self.window, 566, 410, self.game.nPlayers() - 1)
     self.mouseHovering()
예제 #39
0
파일: Game.py 프로젝트: WasLop/Flappy_Bat
 def __init__(self, screen):
     self.screen = screen
     self.name = ""
     self.backgrounds = Images.background()
     self.backgrounds.background1 = self.backgrounds.set_size(
         self.backgrounds.background1, (5000, self.screen.get_height()))
     self.eventes = events()
     self.myfont1 = pygame.font.SysFont("Rosewood Std Regular", 30)
     self.list_records = []
     try:
         records = open("records.txt", "rb")
         self.list_records = pickle.load(records)
         records.close()
     except:
         pass
예제 #40
0
 def ImageTweet(self):
     # This should also be triggered in the PM if the weather is currently bad, or if it WAS bad during the AM
     self.paths = []
     for item in IMAGES_TO_PULL:
         image = Images.Image(item)
         if (image.isValid):
             self.tweetContents += image.description + ", "
             self.paths.append(image.localPath)
     if (self.tweetContents):
         #If we actually successfully pulled anything down
         self.tweetContents = "Current views of " + self.tweetContents
         self.tweetContents += " via DOT traffic camera feeds."
         #Could have a try/catch here
         self.addHashTag()
         TweetPublisher(self.tweetContents, self.paths)
예제 #41
0
파일: MainMenu.py 프로젝트: kaikue/Oceania
 def __init__(self):
     self.logo_image = Images.load_imageurl("img/title/logo.png")
     self.logo_x = Game.SCREEN_WIDTH / 2 - self.logo_image.get_width() / 2
     self.logo_y = Game.SCREEN_HEIGHT * 1 // 5
     self.back_image = Images.load_imageurl("img/title/back.png")
     self.back_width = self.back_image.get_width()
     self.bg_y = Game.SCREEN_HEIGHT - self.back_image.get_height()
     self.mid_image = Images.load_imageurl("img/title/mid.png")
     self.mid_width = self.mid_image.get_width()
     self.front_image = Images.load_imageurl("img/title/front.png")
     self.front_width = self.front_image.get_width()
     
     self.back_xs = [-self.back_width, 0, self.back_width]
     self.mid_xs = [-self.mid_width, 0, self.mid_width]
     self.front_xs = [-self.front_width, 0, self.front_width]
     
     play_button = Button.Button((Game.SCREEN_WIDTH / 2 - Button.WIDTH / 2, Game.SCREEN_HEIGHT * 8 // 15), "Start Game", "menu")
     if len(Game.get_worlds()) == 0:
         play_button.next_menu = WorldNameMenu(self)
     else:
         play_button.next_menu = WorldSelectMenu(self)
     options_button = Button.Button((Game.SCREEN_WIDTH / 2 - Button.WIDTH / 2, Game.SCREEN_HEIGHT * 10 // 15), "Options", "options")
     quit_button = Button.Button((Game.SCREEN_WIDTH / 2 - Button.WIDTH / 2, Game.SCREEN_HEIGHT * 12 // 15), "Quit", "quit")
     super().__init__([play_button, options_button, quit_button])
예제 #42
0
파일: Helper.py 프로젝트: yongwangCPH/peat
 def formatPanel(self):
     """Showing format options"""
     self.img1 = Images.formatsDiagram()
     label1 = Label(self.main, image=self.img1)
     label1.pack(fill=BOTH, padx=4, pady=4, ipadx=2, ipady=2)
     text = """The layout/format of your data is specified in the configuration
     file under the 'format' keyword. 8 typical formats
     are built into DataPipeline, covering most simple cases."""
     text = text.replace('\t', '')
     Label(self.main, text=text, wraplength=600).pack(fill=Y,
                                                      side=TOP,
                                                      pady=4)
     panel2 = Frame(self.main)
     panel2.pack(fill=Y, side=BOTTOM)
     self.doButtons(panel2)
     return
예제 #43
0
 def about(self):
     win = Toplevel()
     win.geometry('+500+350')
     win.title('About DNATool')
     win.maxsize(width=400, height=400)
     logo = Images.logo()
     label = Label(win, image=logo)
     label.image = logo
     label.pack(fill=BOTH, padx=4, pady=4)
     text = """DNATool App, Version 2
          is a python desktop application for DNA sequence manipulation.
          Released under GPL v3
          (C) Copyright 2012- Damien Farrell """
     text = text.replace('\t', '')
     text = ' '.join(text.split())
     Label(win, text=text, wraplength=400).pack(fill=Y, side=TOP, pady=4)
     return
예제 #44
0
 def about(self):
     win=Toplevel()
     win.geometry('+500+350')
     win.title('About DNATool')
     win.maxsize(width=400,height=400)
     logo = Images.logo()
     label = Label(win,image=logo)
     label.image = logo
     label.pack(fill=BOTH,padx=4,pady=4)
     text="""DNATool App, Version 2
          is a python desktop application for DNA sequence manipulation.
          Released under GPL v3
          (C) Copyright 2012- Damien Farrell """
     text=text.replace('\t','')
     text= ' '.join(text.split())
     Label(win,text=text,wraplength=400).pack(fill=Y,side=TOP,pady=4)
     return
예제 #45
0
 def about(self):
     win=Toplevel()
     win.geometry('+500+350')
     win.title('About DataPipeline')
     logo = Images.logo()
     label = Label(win,image=logo)
     label.image = logo
     label.pack(fill=BOTH,padx=4,pady=4)
     text="""DataPipeline App, Version 1.2
          is a python desktop and web application
          that uses a configuration file to automate the import of
          raw data in a variety of formats.\n
          Released under GPL v3\n
          (C) Copyright 2011- Damien Farrell """
     text=text.replace('\t','')
     text= ' '.join(text.split())
     Label(win,text=text,wraplength=400).pack(fill=Y,side=TOP,pady=4)
     return
예제 #46
0
    def showUsers(self):
        image.userPlayer(self.window, 474 + 34 * self.game.player_human.pos,
                         374)
        image.Shadow(self.window, 474 + 34 * self.game.player_human.pos, 394)

        for i in range(3):
            if self.game.player_ai[i].playing:
                image.userCPU(self.window,
                              474 + 34 * self.game.player_ai[i].pos,
                              374 + 30 * (i + 1), i + 1)
                image.Shadow(self.window,
                             474 + 34 * self.game.player_ai[i].pos,
                             394 + 30 * (i + 1))
예제 #47
0
 def loadSinks(self):
     #self.sink_list.addSink(DataTree.init())
     #self.sink_list.addSink(RecipeSystemIFACE.init())
     self.sink_list.addSink(ADViewerIFACE.init())
     self.sink_list.addSink(RecipeViewer.init())
     self.sink_list.addSink(FITSStoreFACE.init())
     self.sink_list.addSink(DisplayIFACE.init())
     self.sink_list.addSink(Info.init())
     if False:
         self.sink_list.addSink(Buttons.init())
         self.sink_list.addSink(Menus.init())
         self.sink_list.addSink(Images.init())
         self.sink_list.addSink(Layouts.init())
         self.sink_list.addSink(Lists.init())
         self.sink_list.addSink(Popups.init())
         self.sink_list.addSink(Tables.init())
         self.sink_list.addSink(Text.init())
     if False: #preserving originaly order
         self.sink_list.addSink(Frames.init())
         self.sink_list.addSink(Tabs.init())
예제 #48
0
    def showPuzzles(self):
        for i in range(6):
            for j in range(6):
                image.tileColor(self.window, 84 + 16 * i, 130 + 16 * j,
                                self.puzzle[j][i])

        if self.game.isAIPlaying(0):
            for i in range(6):
                for j in range(6):
                    image.tileColor(self.window, 822 + 16 * i, 126 + 16 * j,
                                    self.puzzle_ai[0][j][i])

        if self.game.isAIPlaying(1):
            for i in range(6):
                for j in range(6):
                    image.tileColor(self.window, 84 + 16 * i, 442 + 16 * j,
                                    self.puzzle_ai[1][j][i])

        if self.game.isAIPlaying(2):
            for i in range(6):
                for j in range(6):
                    image.tileColor(self.window, 822 + 16 * i, 438 + 16 * j,
                                    self.puzzle_ai[2][j][i])
예제 #49
0
    def showPieces(self):
        for i in range(4):
            image.Piece(self.window, 194 + 32 * i, 136,
                        self.game.getPieces(0)[i])
            if self.blocked_piece[i]:
                image.pieceBlocked(self.window, 194 + 32 * i, 136)

        if self.game.isAIPlaying(0):
            for i in range(4):
                image.Piece(self.window, 932 + 32 * i, 132,
                            self.game.getPieces(1)[i])

        if self.game.isAIPlaying(1):
            for i in range(4):
                image.Piece(self.window, 194 + 32 * i, 448,
                            self.game.getPieces(2)[i])

        if self.game.isAIPlaying(2):
            for i in range(4):
                image.Piece(self.window, 932 + 32 * i, 444,
                            self.game.getPieces(3)[i])
예제 #50
0
def main():
    # Initialize pygame
    # os.environ['SDL_VIDEODRIVER'] = 'windib'
    pygame.init()
    pygame.mouse.set_cursor(*pygame.cursors.tri_left)
    os.environ["SDL_VIDEO_CENTERED"] = "1"  #

    Game.framesPerSecond = 48
    Game.speedModifier = 1
    Game.autoMode = 0
    Game.balanceMode = 0
    drawTick = 0

    Game.state = STATE_INITMENU
    Game.mainMenuFont = pygame.font.Font(None, 32)
    Game.gameMenuFont = pygame.font.Font(None, 24)
    Game.enemyCountFont = pygame.font.Font(None, 24)
    Game.popUpFont = pygame.font.Font(None, 24)

    # Set the height and width of the screen
    size = [mapWidth * tileSize + rightMenuSize, mapHeight * tileSize + bottomMenuSize]
    screen = pygame.display.set_mode(size)
    screen.fill(background)
    layer = pygame.Surface(size)
    layer.set_colorkey(spritepink)
    layer.set_alpha(120)

    # Variables to tell Game what to draw
    Game.drawMouseOver = 0
    Game.drawMessage = 0
    Game.repaintMap = 0
    Game.placedTower = 0

    Game.EndLevelDraw = 0
    Game.restartWave = 0
    Game.nextWave = 0

    # Initialize the Images
    Images.init()

    # Initialize the MainMenu
    mainMenu = cMenu(
        128,
        320,
        20,
        5,
        "vertical",
        100,
        screen,
        [
            ("Campaign", 1, None),
            ("Challenge 1", 2, None),
            ("Challenge 2", 3, None),
            ("Challenge 3", 4, None),
            ("Challenge 4", 5, None),
            ("Challenge 5", 6, None),
            ("Random Level", 7, None),
            ("Exit", 8, None),
        ],
        Images.Background,
    )
    gameMenu = cMenu(
        128,
        320,
        20,
        5,
        "vertical",
        100,
        screen,
        [("Resume", 1, None), ("Back to main menu (current progress will be lost!)", 2, None)],
        Images.Background,
    )

    menubackground = Images.Background
    interfaceBGwashed = Images.InterfaceBGwashed
    InterfaceBGopaque = Images.InterfaceBGopaque
    rect_list = []

    # Initialize the map
    map = Map.Map(mapWidth, mapHeight)

    # Initialize the wave
    wave = Wave.Wave(map)

    # Initialize the Towers class
    towers = Towers.Towers(map, wave)
    wave.setTowers(towers)

    # Initialize the shot graphics
    shots = Shots()

    # Initialize the tower bar
    towerBar = TowerBar.TowerBar(0, mapHeight * tileSize, map, towers)

    # Initialize the menu
    menu = Menu.Menu(map, wave, towers)

    # Initialize the level
    Game.level = Level.Level(map, wave, towers, towerBar, menu)

    # Set title of screen
    pygame.display.set_caption("AI Tower Defense -- (c) POB & ND")

    # Loop until the user clicks the close button.
    close_game = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while close_game == False:
        ## Init menu
        if Game.state == STATE_INITMENU:
            screen.fill(background)
            screen.blit(menubackground, (0, 0))
            pygame.display.flip()
            mainMenustate = 0
            mainMenuprev_state = 1
            Game.state = STATE_MENU

        ## Menu
        elif Game.state == STATE_MENU:
            if mainMenuprev_state != mainMenustate:
                pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key=0))
                mainMenuprev_state = mainMenustate
            e = pygame.event.wait()
            if e.type == pygame.KEYDOWN or e.type == EVENT_CHANGE_STATE:
                if mainMenustate == 0:
                    rect_list, mainMenustate = mainMenu.update(e, mainMenustate)
                # Campagin
                elif mainMenustate == 1:
                    Game.state = STATE_LOADGAME
                    Game.level.loadLevel("Campaign1")
                # Challenges
                elif mainMenustate == 2:
                    Game.state = STATE_LOADGAME
                    Game.level.loadLevel("Challenge1")
                elif mainMenustate == 3:
                    Game.state = STATE_LOADGAME
                    Game.level.loadLevel("Challenge2")
                elif mainMenustate == 4:
                    Game.state = STATE_LOADGAME
                    Game.level.loadLevel("Challenge3")
                elif mainMenustate == 5:
                    Game.state = STATE_LOADGAME
                    Game.level.loadLevel("Challenge4")
                elif mainMenustate == 6:
                    Game.state = STATE_LOADGAME
                    Game.level.loadLevel("Challenge5")
                # Random Level
                elif mainMenustate == 7:
                    Game.state = STATE_LOADGAME
                    Game.level.loadLevel("Campaign1")
                # Quit
                else:
                    pygame.quit()
                    sys.exit()
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            pygame.display.update(rect_list)

        ## Init Game Menu
        elif Game.state == STATE_INITGAMEMENU:
            screen.fill(background)
            screen.blit(menubackground, (0, 0))
            pygame.display.flip()
            gameMenustate = 0
            gameMenuprev_state = 1
            Game.state = STATE_GAMEMENU

        ## Game Menu
        elif Game.state == STATE_GAMEMENU:
            if gameMenuprev_state != gameMenustate:
                pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key=0))
                gameMenuprev_state = gameMenustate
            e = pygame.event.wait()
            if e.type == pygame.KEYDOWN or e.type == EVENT_CHANGE_STATE:
                if e.key == pygame.K_ESCAPE:
                    Game.state = STATE_LOADGAME
                else:
                    if gameMenustate == 0:
                        rect_list, gameMenustate = gameMenu.update(e, gameMenustate)
                    elif gameMenustate == 1:
                        Game.state = STATE_LOADGAME
                    elif gameMenustate == 2:
                        shots.clear()
                        towers.clear()
                        wave.clear()
                        Game.state = STATE_INITMENU
            if e.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            pygame.display.update(rect_list)

        ## POP UP
        if Game.state == STATE_INITPOPUP:
            Game.state = STATE_POPUP
            # Add a background or the game behind the text...
            screen.blit(InterfaceBGopaque, (0, 0))
            drawMap(map, screen)
            menu.draw(screen)
            Game.redrawSPBtn = 1
            menu.drawSPBtn(screen)
            towerBar.draw(screen)
            towerBar.moneyUpdated(screen)
            towerBar.showTower(screen)
            towerBar.updateTowerCost = 0
            pygame.display.flip()

        elif Game.state == STATE_POPUP:
            drawTick += 1
            if drawTick >= clock.get_fps() / 24:
                drawTick = 0
                Game.popUp.paint(screen)
                pygame.display.update(167, 90, 658, 465)
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        Game.dialog.close()
                    elif event.key == pygame.K_RETURN:
                        Game.dialog.close()
                    elif event.key == pygame.K_SPACE:
                        Game.dialog.close()
                elif event.type == pygame.QUIT:
                    sys.exit()
                else:
                    Game.popUp.event(event)

        ## Wave finished [Draw then restartWave or start next Wave] -> PopUp lorsque level finished?
        elif Game.state == STATE_ENDWAVE:
            if not Game.autoMode and not Game.balanceMode:
                drawTick += 1
                if drawTick >= clock.get_fps() / 24:
                    Game.EndLevelDraw += 1
                    drawTick = 0
                    drawGame(map, towerBar, towers, wave, shots, menu, screen, layer)
                    if Game.EndLevelDraw >= 5:
                        Game.state = STATE_PREPARATION
                        Game.EndLevelDraw = 0
                        if Game.restartWave:
                            Game.restartWave = 0
                            Game.level.restartWave()
                        elif Game.nextWave:
                            Game.nextWave = 0
                            Game.level.nextWave()
                        else:
                            print "Confus :("
        else:
            for event in pygame.event.get():  # User did something
                # If user clicked close
                if event.type == pygame.QUIT:
                    close_game = True  # Flag that we are done so we exit this loop

                ## Mouse Events
                # User moves over the mouse
                elif event.type == pygame.MOUSEMOTION:
                    updateUnderMouse(map, towerBar, towers)

                # User clicks the mouse. Get the position
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    # Change the x/y screen coordinates to grid coordinates (For the map)
                    column = pos[0] // tileSize
                    row = pos[1] // tileSize
                    # Inside Map
                    if (column < mapWidth) and (row < mapHeight):
                        if towerBar.selectedTower > -1:
                            if map.M[row][column] == car_turret:
                                if map.T[row][column] == 0:
                                    # TODO : money check
                                    towers.placeTower(towerBar.selectedTower, 0, row, column)
                                    Game.placedTower = 1
                                else:
                                    towers.updateTower(towerBar.selectedTower, row, column)
                                    Game.placedTower = 1
                        elif towerBar.selectedTower == TowerUPGRADE:
                            if map.M[row][column] == car_turret:
                                if map.T[row][column] != 0:
                                    towers.updateTower(towerBar.selectedTower, row, column)
                                    Game.placedTower = 1
                        elif towerBar.selectedTower == TowerERASE:
                            if map.M[row][column] == car_turret:
                                if map.T[row][column] != 0:
                                    towers.eraseTower(row, column)
                                    Game.placedTower = 1
                        updateUnderMouse(map, towerBar, towers)

                    # Inside Menu
                    elif column >= mapWidth:
                        menu.onClick(pos, map)

                    # Inside Tower Bar
                    else:
                        towerBar.onClick(pos)

                ## Keyboard Events
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        Game.state = STATE_INITGAMEMENU
                    elif event.key == pygame.K_SPACE:
                        if Game.state == STATE_GAME:
                            Game.redrawSPBtn = 1
                            Game.state = STATE_PREPARATION
                        elif Game.state == STATE_PREPARATION:
                            Game.redrawSPBtn = 2
                            Game.state = STATE_GAME
                    elif event.key == pygame.K_1:
                        if 0 in Game.level.levelTowers:
                            towerBar.selectTower(0)
                    elif event.key == pygame.K_2:
                        if 1 in Game.level.levelTowers:
                            towerBar.selectTower(1)
                    elif event.key == pygame.K_3:
                        if 2 in Game.level.levelTowers:
                            towerBar.selectTower(2)
                    elif event.key == pygame.K_4:
                        if 3 in Game.level.levelTowers:
                            towerBar.selectTower(3)
                    elif event.key == pygame.K_5:
                        if 4 in Game.level.levelTowers:
                            towerBar.selectTower(4)
                    elif event.key == pygame.K_6:
                        if 5 in Game.level.levelTowers:
                            towerBar.selectTower(5)
                    elif event.key == pygame.K_EQUALS:
                        Game.increaseSpeed(menu)
                    elif event.key == pygame.K_MINUS:
                        Game.reduceSpeed(menu)
                    elif event.key == pygame.K_c:
                        towers.resetCooldowns()
                    elif event.key == pygame.K_r:
                        towerBar.selectTower(TowerUPGRADE)
                    elif event.key == pygame.K_e:
                        towerBar.selectTower(TowerERASE)
                    elif event.key == pygame.K_a:
                        towers.clear()
                        wave.clear()
                        shots.clear()
                    elif event.key == pygame.K_t:
                        towers.clear()
                        shots.clear()
                    elif event.key == pygame.K_v:
                        Evaluate.evalPlayerPosition()
                    elif event.key == pygame.K_b:
                        Progress.prog()

            ## Init Game
            if Game.state == STATE_LOADGAME:
                Game.redrawSPBtn = 1
                Game.state = STATE_PREPARATION
                screen.blit(InterfaceBGopaque, (0, 0))
                # screen.fill(background)
                # pygame.draw.rect(screen, background, ([mapWidth*tileSize, 0, rightMenuSize, mapHeight*tileSize + bottomMenuSize]))
                # pygame.draw.rect(screen, background, ([0, mapHeight*tileSize, mapWidth*tileSize, bottomMenuSize]))

                # Draw the map
                drawMap(map, screen)

                # Draw the game information menu
                menu.draw(screen)
                Game.redrawSPBtn = 1
                menu.drawSPBtn(screen)

                towerBar.moneyUpdated(screen)
                towerBar.showTower(screen)
                towerBar.updateTowerCost = 0

                # Draw the tower bar ~ 0
                towerBar.draw(screen)

                pygame.display.flip()

            ## Game Paused
            if Game.state == STATE_PREPARATION:
                if Game.autoMode or Game.balanceMode:
                    Game.redrawSPBtn = 1
                    Game.state = STATE_GAME
                else:
                    ## Display
                    drawTick += 1
                    # print(clock.get_fps())
                    if drawTick >= clock.get_fps() / 24:
                        # print(clock.get_fps())
                        drawTick = 0
                        drawGame(map, towerBar, towers, wave, shots, menu, screen, layer)

            ## Game Running
            elif Game.state == STATE_GAME:
                # Spawn any new enemy in the wave queue
                wave.spawn()
                # Move the enemies
                wave.move()
                # Tower target
                towers.target(shots)

                ## Display
                if not Game.autoMode and not Game.balanceMode:
                    drawTick += 1
                    # print(clock.get_fps())
                    if drawTick >= clock.get_fps() / 24:
                        # print(clock.get_fps())
                        drawTick = 0
                        drawGame(map, towerBar, towers, wave, shots, menu, screen, layer)

        # Limit to 24 frames per second
        # print(pygame.time.get_ticks())
        clock.tick(Game.framesPerSecond * Game.speedModifier)

    pygame.quit()
예제 #51
0
 def __init__(self, player, imageurl):
     super(HotbarGUI, self).__init__(imageurl)
     self.player = player
     self.img_heart_full = Images.load_imageurl("img/gui/heart.png")
     self.img_heart_empty = Images.load_imageurl("img/gui/heart_empty.png")
예제 #52
0
파일: World.py 프로젝트: kaikue/Oceania
def load_blocks():
    blocks_file = open("blocks.json", "r")
    global blocks
    blocks = json.load(blocks_file)["blocks"]
    blocks_file.close()
    
    water_image = pygame.image.load("img/water.png")
    st_water_image = water_image.copy()
    st_water_image.set_alpha(128)
    pygame.display.set_icon(water_image) #TODO: change the icon to something better
    
    bid = 0
    global block_images
    block_images = {False:{}, True:{}}
    global ctm_block_images
    ctm_block_images = {False:{}, True:{}}
    for block in blocks:
        #set some default attributes
        if "breakable" not in block.keys():
            block["breakable"] = True
        if "connectedTexture" not in block.keys():
            block["connectedTexture"] = None
        if "solid" not in block.keys():
            block["solid"] = True
        if "entity" not in block.keys():
            block["entity"] = ""
        if "item" not in block.keys():
            block["item"] = "ItemStack"
        if "description" not in block.keys():
            block["description"] = [""]
        if "harvestlevel" not in block.keys():
            block["harvestlevel"] = 0
        if "breaktime" not in block.keys():
            block["breaktime"] = 100
        if "image" not in block.keys():
            block["image"] = ""
        #add an id to the block
        block["id"] = bid
        global block_mappings
        block_mappings[block["name"]] = bid
        global id_mappings
        id_mappings[bid] = block["name"]
        
        if isinstance(block["description"], str):
            block["description"] = [block["description"]]
        
        #load the block image
        path = block["image"]
        if path != "":
            blockimg = pygame.image.load(path).convert_alpha()
            if block["connectedTexture"]:
                icon = pygame.Surface((Game.BLOCK_SIZE, Game.BLOCK_SIZE), pygame.SRCALPHA, 32)
                icon = icon.convert_alpha()
                icon.blit(blockimg, (0, 0))
            else:
                icon = blockimg.copy()
            item_images[block["name"]] = [Images.make_itemdrop_image(icon)]
            foreground_image = Images.scale(blockimg, Game.SCALE)
            block_images[False][bid] = Images.crop(foreground_image)
            #blit the image onto the water tile so it isn't just empty transparency
            image = blockimg.copy()
            for x in range(image.get_width() // Game.BLOCK_SIZE):
                for y in range(image.get_height() // Game.BLOCK_SIZE):
                    image.blit(water_image, (x * Game.BLOCK_SIZE, y * Game.BLOCK_SIZE))
            image.blit(blockimg, (0, 0))
            for x in range(image.get_width() // Game.BLOCK_SIZE):
                for y in range(image.get_height() // Game.BLOCK_SIZE):
                    image.blit(st_water_image, (x * Game.BLOCK_SIZE, y * Game.BLOCK_SIZE))
            background_image = Images.scale(image, Game.SCALE)
            block_images[True][bid] = background_image
            if block["connectedTexture"]:
                ctm_block_images[False][bid] = {}
                ctm_block_images[True][bid] = {}
                for x in range(4):
                    for y in range(4):
                        foreground_surf = pygame.Surface((Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE)).convert_alpha()
                        foreground_surf.fill((0, 0, 0, 0))
                        background_surf = foreground_surf.copy()
                        foreground_surf.blit(foreground_image, (0, 0),
                            pygame.Rect((x * Game.BLOCK_SIZE * Game.SCALE, y * Game.BLOCK_SIZE * Game.SCALE),
                                 (Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE)))
                        ctm_block_images[False][bid][(x, y)] = foreground_surf
                        background_surf.blit(background_image, (0, 0),
                            pygame.Rect((x * Game.BLOCK_SIZE * Game.SCALE, y * Game.BLOCK_SIZE * Game.SCALE),
                                 (Game.BLOCK_SIZE * Game.SCALE, Game.BLOCK_SIZE * Game.SCALE)))
                        ctm_block_images[True][bid][(x, y)] = background_surf
        #make the corresponding item
        items[block["name"]] = {"displayName": block["displayName"],
                                "image": block["image"],
                                "class": block["item"],
                                "description": block["description"],
                                "can_place": True}
        bid += 1
    block_images[False][get_block_id("water")] = pygame.Surface((Game.BLOCK_SIZE, Game.BLOCK_SIZE), pygame.SRCALPHA, 32)
예제 #53
0
파일: World.py 프로젝트: kaikue/Oceania
def load_data():
    load_biomes()
    load_structures()
    load_items()
    load_blocks()
    Images.load_images()
예제 #54
0
def doDrawImageWithCGImageSource(context):
    url = GetURL(kOurJPEG)
    if url is not None:
        Images.drawImageWithCGImageDataSource(context, url)
예제 #55
0
def exportImageWithMaskFromURLWithDestination(context, imageURL, imagewidth,
                                              imageheight, bitsPerComponent,
                                              theMaskingImageURL, maskwidth,
                                              maskheight):

    imageBitsPerPixel = bitsPerComponent * 3
    bytesPerRow = ((imagewidth * imageBitsPerPixel) + 7) / 8
    shouldInterpolate = True
    imageDataProvider = Quartz.CGDataProviderCreateWithURL(imageURL)
    if imageDataProvider is None:
        print("Couldn't create Image Data provider!")
        return

    colorspace = Utilities.getTheCalibratedRGBColorSpace()
    image = Quartz.CGImageCreate(imagewidth, imageheight, bitsPerComponent,
                                 imageBitsPerPixel, bytesPerRow, colorspace,
                                 Quartz.kCGImageAlphaNone, imageDataProvider,
                                 None, shouldInterpolate,
                                 Quartz.kCGRenderingIntentDefault)
    del imageDataProvider
    if image is None:
        print("Couldn't create CGImageRef for this data!")
        return

    imageRect = Quartz.CGRectMake(0.0, imageheight, imagewidth, imageheight)
    # Draw the image.
    Quartz.CGContextDrawImage(context, imageRect, image)

    # Now the mask.
    maskDataProvider = Quartz.CGDataProviderCreateWithURL(theMaskingImageURL)
    if maskDataProvider is None:
        print("Couldn't create Image Data provider!")
        return

    mask = Quartz.CGImageMaskCreate(maskwidth, maskheight, bitsPerComponent,
                                    bitsPerComponent, maskwidth,
                                    maskDataProvider, None, shouldInterpolate)
    del maskDataProvider
    if mask is None:
        print("Couldn't create CGImageRef for mask data!")
        return

    # Draw the mask below the image.
    maskRect = Quartz.CGRectMake(0.0, 0.0, maskwidth, maskheight)
    Quartz.CGContextDrawImage(context, maskRect, mask)

    # Create a new CGImage object, the image, masked with mask.
    imageMaskedWithImage = Quartz.CGImageCreateWithMask(image, mask)
    # Once the new image is created, we can release the image
    # and the mask which make it up. Quartz retains what it needs
    # for the new masked image.
    del image
    del mask

    if imageMaskedWithImage is None:
        print("Couldn't create image masked with mask!")
        return

    imageRect = Quartz.CGRectMake(imagewidth, imageheight / 2, imagewidth,
                                  imageheight)
    # Draw the masked image to the right of the image and its mask.
    Quartz.CGContextDrawImage(context, imageRect, imageMaskedWithImage)

    # Of course this is a total hack.
    outPath = b"/tmp/imageout.png"
    exportURL = Cocoa.CFURLCreateFromFileSystemRepresentation(
        None, outPath, len(outPath), False)

    if exportURL is not None:
        Images.exportCGImageToPNGFileWithDestination(imageMaskedWithImage,
                                                     exportURL)
예제 #56
0
def doIncrementalImage(context):
    url = GetURL(kOurJPEG)

    if url is not None:
        Images.doIncrementalImageWithURL(context, url)
예제 #57
0
def doDrawJPEGFile(context):
    ourJPEGurl = GetURL(kOurJPEG)

    if ourJPEGurl is not None:
        Images.drawJPEGImage(context, ourJPEGurl)
예제 #58
0
def DispatchDrawing(context, drawingType):
    """ Drawing dispatcher """
    if drawingType == UIHandling.kHICommandSimpleRect:
            DrawingBasics.doSimpleRect(context)

    elif drawingType == UIHandling.kHICommandStrokedRect:
            DrawingBasics.doStrokedRect(context)
    
    elif drawingType == UIHandling.kHICommandStrokedAndFilledRect:
            DrawingBasics.doStrokedAndFilledRect(context)

    elif drawingType == UIHandling.kHICommandPathRects:
            DrawingBasics.doPathRects(context)
    
    elif drawingType == UIHandling.kHICommandAlphaRects:
            DrawingBasics.doAlphaRects(context)
    
    elif drawingType == UIHandling.kHICommandDashed:
            DrawingBasics.doDashedLines(context)
    
    elif drawingType == UIHandling.kHICommandSimpleClip:
            DrawingBasics.doClippedCircle(context)
    
    elif drawingType == UIHandling.kHICommandPDFDoc:
            callPDFDrawProc(context, DrawingBasics.doPDFDocument, kCatPDF)
        
    elif drawingType == UIHandling.kHICommandRotatedEllipses:
            CoordinateSystem.doRotatedEllipses(context)

    elif drawingType == UIHandling.kHICommandDrawSkewCoordinates:
            CoordinateSystem.drawSkewedCoordinateSystem(context)

    elif drawingType == UIHandling.kHICommandBezierEgg:
            PathDrawing.doEgg(context)

    elif drawingType == UIHandling.kHICommandRoundedRects:
            PathDrawing.doRoundedRects(context)

    elif drawingType == UIHandling.kHICommandStrokeWithCTM:
            PathDrawing.doStrokeWithCTM(context)

    elif drawingType == UIHandling.kHICommandRotatedEllipsesWithCGPath:
            PathDrawing.doRotatedEllipsesWithCGPath(context)

    elif drawingType == UIHandling.kHICommandPixelAligned:
            PathDrawing.doPixelAlignedFillAndStroke(context)

    elif drawingType == UIHandling.kHICommandDeviceFillAndStrokeColor:
            ColorAndGState.doColorSpaceFillAndStroke(context)

    elif drawingType == UIHandling.kHICommandCLUTDrawGraphics:
            ColorAndGState.doIndexedColorDrawGraphics(context)
            
    elif drawingType == UIHandling.kHICommandDrawWithGlobalAlpha:
            ColorAndGState.drawWithGlobalAlpha(context)

    elif drawingType == UIHandling.kHICommandDrawWithBlendMode:
            callPDFDrawProc(context, ColorAndGState.drawWithColorBlendMode, kPDFForBlendMode)

    elif drawingType == UIHandling.kHICommandDrawWithColorRefs:
            ColorAndGState.drawWithColorRefs(context)

    elif drawingType == UIHandling.kHICommandFunctionsHaveOwnGSave:
            ColorAndGState.doClippedEllipse(context)

    elif drawingType == UIHandling.kHICommandDrawJPEGImage:
            doDrawJPEGFile(context)

    elif drawingType == UIHandling.kHICommandColorImageFromFile:
            doRawImageFileWithURL(context)

    elif drawingType == UIHandling.kHICommandColorImageFromData:
            Images.doColorRampImage(context)

    elif drawingType == UIHandling.kHICommandColorImageFromCallbacks:
            doRawImageFileWithCallbacks(context)

    elif drawingType == UIHandling.kHICommandGrayRamp:
            Images.doGrayRamp(context)

    elif drawingType == UIHandling.kHICommandDrawWithCGImageSource:
            doDrawImageWithCGImageSource(context)

    elif drawingType == UIHandling.kHICommandDrawWithCGImageSourceIncremental:
            doIncrementalImage(context)

    elif drawingType == UIHandling.kHICommandDrawWithQuickTime:
            doQTImage(context)

    elif drawingType == UIHandling.kHICommandSubstituteImageProfile:
            doJPEGDocumentWithMultipleProfiles(context)

    elif drawingType == UIHandling.kHICommandDoSubImage:
            Images.doColorRampSubImage(context)

    elif drawingType == UIHandling.kHICommandExportWithQuickTime:
            Images.exportColorRampImageWithQT(context)

    elif drawingType == UIHandling.kHICommandMaskTurkeyImage:
            ImageMasking.doOneBitMaskImages(context)

    elif drawingType == UIHandling.kHICommandImageMaskedWithMask:
            doMaskImageWithMask(context)

    elif drawingType == UIHandling.kHICommandImageMaskedWithGrayImage:
            doMaskImageWithGrayImage(context)

    elif drawingType == UIHandling.kHICommandMaskImageWithColor:
            doImageMaskedWithColor(context)

    elif drawingType == UIHandling.kHICommandClipToMask:
            doClipMask(context)

    elif drawingType == UIHandling.kHICommandExportWithCGImageDestination:
            exportImageMaskedWithImage(context)

    elif drawingType == UIHandling.kHICommandSimpleCGLayer:
            BitmapContext.doSimpleCGLayer(context)

    elif drawingType == UIHandling.kHICommandAlphaOnlyContext:
            BitmapContext.doAlphaOnlyContext(context)

    elif drawingType == UIHandling.kHICommandDrawNoOffScreenImage:
            tilePDFDocument(context, noOffScreen)

    elif drawingType == UIHandling.kHICommandDrawOffScreenImage:
            tilePDFDocument(context, bitmapOffScreen)

    elif drawingType == UIHandling.kHICommandDrawWithLayer:
            tilePDFDocument(context, layerOffScreen)

    elif drawingType == UIHandling.kHICommandQuartzRomanText:
            QuartzTextDrawing.drawQuartzRomanText(context)

    elif drawingType == UIHandling.kHICommandQuartzTextModes:
            QuartzTextDrawing.drawQuartzTextWithTextModes(context)

    elif drawingType == UIHandling.kHICommandQuartzTextMatrix:
            QuartzTextDrawing.drawQuartzTextWithTextMatrix(context)

    elif drawingType == UIHandling.kHICommandSimplePattern:
            PatternDrawing.doRedBlackCheckerboard(context)

    elif drawingType == UIHandling.kHICommandPatternPhase:
            PatternDrawing.doPatternPhase(context)

    elif drawingType == UIHandling.kHICommandPatternMatrix:
            PatternDrawing.doPatternMatrix(context)

    elif drawingType == UIHandling.kHICommandUncoloredPattern:
            PatternDrawing.doStencilPattern(context)
            
    elif drawingType == UIHandling.kHICommandDrawWithPDFPattern:
            callPDFDrawProc(context, PatternDrawing.drawWithPDFPattern, kCatPDF)

    elif drawingType == UIHandling.kHICommandSimpleShadow:
            ShadowsAndTransparencyLayers.drawSimpleShadow(context)
        
    elif drawingType == UIHandling.kHICommandShadowScaling:
            ShadowsAndTransparencyLayers.doShadowScaling(context)
    
    elif drawingType == UIHandling.kHICommandShadowProblems:
            ShadowsAndTransparencyLayers.showComplexShadowIssues(context)

    elif drawingType == UIHandling.kHICommandComplexShadow:
            ShadowsAndTransparencyLayers.showComplexShadow(context)
    
    elif drawingType == UIHandling.kHICommandMultipleShapeComposite:
            ShadowsAndTransparencyLayers.doLayerCompositing(context)

    elif drawingType == UIHandling.kHICommandFillAndStrokeWithShadow:
            ShadowsAndTransparencyLayers.drawFillAndStrokeWithShadow(context)

    elif drawingType == UIHandling.kHICommandPDFDocumentShadow:
            callPDFDrawProc(context, ShadowsAndTransparencyLayers.shadowPDFDocument, kCatPDF)

    elif drawingType == UIHandling.kHICommandSimpleAxialShading:
            Shadings.doSimpleAxialShading(context)
            
    elif drawingType == UIHandling.kHICommandExampleAxialShadings:
            Shadings.doExampleAxialShading(context)

    elif drawingType == UIHandling.kHICommandSimpleRadialShading:
            Shadings.doSimpleRadialShading(context)

    elif drawingType == UIHandling.kHICommandExampleRadialShadings:
            Shadings.doExampleRadialShadings(context)

    elif drawingType == UIHandling.kHICommandEllipseShading:
            Shadings.doEllipseShading(context)

    elif drawingType == UIHandling.kHICommandDoCompatibleEPS:
            doCompatibleEPSDrawing(context)
예제 #59
0
def doJPEGDocumentWithMultipleProfiles(context):
    url = GetURL(kOurSubstituteJPG)

    if url is not None:
        Images.drawJPEGDocumentWithMultipleProfiles(context, url)
예제 #60
0
def doQTImage(context):
    url = GetURL(kQTImage)

    if url is not None:
        Images.drawQTImageWithQuartz(context, url)