Example #1
0
    def openFile():
        fileName = tk.filedialog.askopenfilename()
        if fileName:
            data = json.load(open(fileName, encoding='utf8'))
            fileType = list(data.keys())[0]

            if fileType == "kanjis":
                kanjiBank.clear()
                for element in data[fileType]:
                    kanji = list(element.keys())[0]
                    meanings = ';'.join(element[kanji]["Meanings"])
                    kunyomi = ';'.join(element[kanji]["Kunyomi"])
                    onyomi = ';'.join(element[kanji]["Onyomi"])
                    kanjiBank.append(
                        elems.Kanji(kanji, meanings, kunyomi, onyomi))
                KanjiBank()

            elif fileType == "words":
                wordBank.clear()
                for element in data[fileType]:
                    word = list(element.keys())[0]
                    wordBank.append(
                        elems.Word(word, element[word]["Reading"],
                                   element[word]["Definition"]))
                WordBank()
Example #2
0
 def start(self,
           capabilities,
           port='9000',
           driver_name='chrome',
           host='http://127.0.0.1'):
     '''
     Starts the webdriver and creates the session
     :param capabilities: The capabilities to run the session
     :param port: the port where the web driver will run
     :param driver_name: chrome (more to come soon...)
     :param host: by default 127.0.0.1 if you want to run this from another site put your host.
     :return: X
     '''
     self.webdriver_exec.launch_driver(port, driver_name)
     self.host = host + ':' + port + '/'
     response = requests.request(
         'POST',
         self.host + 'session',
         data=json.dumps(capabilities).encode('utf8'))
     self.session_id = json.loads(response.text)[
         'sessionId']  # Todo: see if session_id variable is necesary
     self.request_url = self.host + 'session/' + self.session_id
     self.interactions = Interactions(self.host, self.session_id)
     self.elements = Elements(self.host, self.session_id)
     self.browser = Browser(self.request_url)
Example #3
0
    def reset(self):
        self.base = Elements.Base()
        self.base.setSpeed(0, 0)
        self.base.setPosition(100, 100)

        self.player = Elements.Player()
        self.player.setSpeed(0, 0)
        self.player.setPosition(200, 200)
Example #4
0
    def insert_layer(__self__, e=""):
        values = sorted([i for i in Elements.ListDatabase().keys()])
        values.insert(0, "Custom")

        __self__.layer_count += 1

        label = f"Layer {__self__.layer_count}"
        Label(__self__.frame, text=label).grid(row=__self__.layer_count,
                                               column=0)

        # Comboboxes in the middle
        __self__.layers.append(StringVar())
        __self__.thicknesses.append(DoubleVar())

        cbb = ttk.Combobox(__self__.frame,
                           values=values,
                           textvariable=__self__.layers[__self__.layer_count -
                                                        1])
        cbb.grid(row=__self__.layer_count, column=1, padx=(6, 3))
        cbb.bind("<<ComboboxSelected>>", __self__.write_layer_info)
        __self__.comboboxes.append(cbb)
        ttk.Entry(__self__.frame,
                  textvariable=__self__.thicknesses[__self__.layer_count - 1],
                  width=7).grid(row=__self__.layer_count,
                                column=2,
                                padx=(3, 6))

        __self__.add.grid(row=__self__.layer_count + 1,
                          column=0,
                          columnspan=3,
                          pady=(8, 8))
        return
def generateAtoms(maxHalfLifeInMinutes, numberOfAtoms):
	atomFactory = Elements.AtomFactory(maxHalfLife=maxHalfLifeInMinutes)

	atoms = []
	for x in range(numberOfAtoms):
		atom = atomFactory.createAtom()
		atoms.append(atom)
	return atoms
Example #6
0
def addWordToList():
    w = WordForm.word_entry.get()
    r = WordForm.reading_entry.get()
    d = WordForm.def_entry.get()
    word = elems.Word(w, r, d)
    wordBank.append(word)
    WordForm.word_entry.delete(0, 'end')
    WordForm.reading_entry.delete(0, 'end')
    WordForm.def_entry.delete(0, 'end')
    WordBank.refreshWordBankHolder()
Example #7
0
 def elem_quad9_to_quad8(self):
     """ Substitutes elem quad 9s for quad 8s """
     counter = 0
     for eleid, elem in self.elems.items():
         if isinstance(elem, Elements.ElemQuad9):
             old = elem
             nodes = elem.nodes
             self.elems[eleid] = Elements.ElemQuad8(self.nodes, nodes[0:8])
             counter += 1
     print("ElemMesh:\tSwapped " + str(counter) + " quad8 elements " + \
         "for quad9s.")
Example #8
0
def addKanjiToList():
    k = KanjiForm.kanji_entry.get()
    m = KanjiForm.meanings_entry.get()
    kunr = KanjiForm.kunr_entry.get()
    onr = KanjiForm.onr_entry.get()
    kanji = elems.Kanji(k, m, kunr, onr)
    kanjiBank.append(kanji)
    KanjiForm.kanji_entry.delete(0, 'end')
    KanjiForm.meanings_entry.delete(0, 'end')
    KanjiForm.kunr_entry.delete(0, 'end')
    KanjiForm.onr_entry.delete(0, 'end')
    KanjiBank.refreshKanjiBankHolder()
Example #9
0
 def write_layer_info(__self__, e=""):
     value = e.widget.get()
     if value == "Custom":
         CustomCompound(root=__self__)
     else:
         __self__.species.delete(0, END)
         __self__.quantity.delete(0, END)
         c = Elements.compound()
         c.set_compound(value)
         for el, w in c.weight.items():
             __self__.species.insert(END, el)
             __self__.quantity.insert(END, f"{w*100:.2f}%")
     return
Example #10
0
def monoisotopicMass(mf, **kw):
    elements = Elements.MonoIsotopicElements()
    sum_ = 0.0
    for sym, n in re.findall("([A-Z][a-z]?)(\d*)", mf):
        m0 = elements.getProperty(sym, "m0")  # (elements.getRowFor(a), "m0")
        overRideData = kw.get(sym)
        if overRideData is not None:
            m0 = overRideData.get("mass", m0)
        if m0 is None:
            return None
        if n == "":
            sum_ += m0
        else:
            sum_ += m0 * int(n)
    return sum_
Example #11
0
    def setupQuizz():
        elements_list = []
        for fileName in QuizzFileSelection.files_list:
            elements = open(fileName, encoding='utf8')
            data = json.load(elements)
            if list(data.keys(
            ))[0] == "kanjis" and QuizzFileSelection.quizz_type == "kanjis":
                for element in data[QuizzFileSelection.quizz_type]:
                    kanji = list(element.keys())[0]
                    meanings = ';'.join(element[kanji]["Meanings"])
                    kunyomi = ';'.join(element[kanji]["Kunyomi"])
                    onyomi = ';'.join(element[kanji]["Onyomi"])
                    elements_list.append(
                        elems.Kanji(kanji, meanings, kunyomi, onyomi))

            elif list(data.keys(
            ))[0] == "words" and QuizzFileSelection.quizz_type == "words":
                for element in data[QuizzFileSelection.quizz_type]:
                    word = list(element.keys())[0]
                    elements_list.append(
                        elems.Word(word, element[word]["Reading"],
                                   element[word]["Definition"]))

        QuizzGenerator(QuizzFileSelection.quizz_type, elements_list)
Example #12
0
 def __init__(self, *args, **kwargs):
     super(UtVisitor, self).__init__(*args, **kwargs)
     self._shopcart = [
         Elements.Product(productType=Elements.ProductTypeEnum.Book,
                          name="設計模式的解析與活用",
                          unitPrice=480,
                          amount=20),
         Elements.Product(productType=Elements.ProductTypeEnum.Living,
                          name="吸塵器",
                          unitPrice=2000,
                          amount=2),
         Elements.Product(productType=Elements.ProductTypeEnum.Book,
                          name="使用者故事對照",
                          unitPrice=580,
                          amount=5),
         Elements.Product(productType=Elements.ProductTypeEnum.Living,
                          name="毛巾",
                          unitPrice=50,
                          amount=10),
         Elements.Product(productType=Elements.ProductTypeEnum.Electronic,
                          name="Surface Pro",
                          unitPrice=50000,
                          amount=2)
     ]
Example #13
0
    def __init__(self):

        self.heroRace = Race()
        self.heroClass = ""

        #Получаем Данные от пользователя
        self.getName()
        self.getClass()
        self.getRace()

        super().__init__(self.name, self.heroRace.stats, Elements(), 0)

        ## Инвентарь героя
        self.inventory = Inventory()
        ## Обмундирование героя
        self.equipment = Equipment()
        ## Карман с Лечебками героя
        self.potionsPocket = PotionsPocket()
Example #14
0
    def highlight_tags(self, sel):

        # Make sure only clicking
        if sel.empty() != True:
            blotch = True

        bufferSize = self.view.size()
        bufferRegion = sublime.Region(0, bufferSize)
        bufferText = self.view.substr(bufferRegion)
        curPosition = sel.begin()
        foundTags = Elements.match(bufferText, curPosition, "html")
        tag1 = {"match": foundTags[0]}
        tag2 = {"match": foundTags[1]}
        if (
            str(tag1["match"]) != "None"
            and self.view.substr(tag1["match"] + 1) != "!"
            and self.view.substr(tag1["match"] - 1) != "`"
            and self.view.substr(tag1["match"]) == "<"
            and self.view.substr(curPosition) != "<"
        ):

            # Get 1st Tag
            blotch = False
            tag1["begin"] = tag1["match"]
            tag1["end"] = tag1["match"]
            while self.view.substr(tag1["end"]) != ">":
                tag1["end"] = tag1["end"] + 1
                if self.view.substr(tag1["end"]) == "<":
                    blotch = True
            tag1["region"] = sublime.Region(tag1["begin"], tag1["end"] + 1)

            # Get 2nd Tag
            tag2["end"] = tag2["match"] - 1
            tag2["begin"] = tag2["end"]
            while self.view.substr(tag2["begin"]) != "<":
                tag2["begin"] = tag2["begin"] - 1
            tag2["region"] = sublime.Region(tag2["begin"], tag2["end"] + 1)

            # Highlight
            if blotch == False:
                self.highlight_us.append(tag1["region"])
                self.highlight_us.append(tag2["region"])
Example #15
0
    def enrich_elems(self, physgrp, enrich, deriv_enrich, ngp, eclass, ident):
        """ Enrich a set of elements within a physical group
        
        physgrp - string representing group to enrich.\n
        enrich - enrichment function - function of form f(x) where x is an 
        array.\n
        deriv_enrich - tuple of derivatives of the enrichment function.\n
        ngp - number of gauss points per dimension for integration.\n
        ident - the identity of the enrichment. Shares degrees of freedom with
        enrichment of the same id.
        """
        try:
            grp_num = [key for key, value in self.phys_group_names.items() \
                    if value == physgrp][0]
            elemset = set(self.elems_in_physical_groups[grp_num])
        except:
            print(
                "##########################################################" +
                "#####################")
            print("ElemMesh:\tFATAL ERROR!")
            print("ElemMesh:\tTrying to build enrichement with identity " +
                  str(ident) + " on physical group " + physgrp + ".")
            print("ElemMesh:\tCould not find group " + physgrp + ".")
            print("ElemMesh:\tAvailible groups are:")
            for key, val in self.phys_group_names.items():
                print(str(key) + ":\t" + str(val))
            print(
                "##########################################################" +
                "#####################")
            raise KeyError

        enrichment = Elements.Enrichment(eclass, ident)
        enrichment.define_func(enrich)
        enrichment.define_deriv_func(deriv_enrich)
        enrichment.define_gauss_order(ngp)

        for eleid in elemset:
            enrichment.enrich_elem(self.elems[eleid])
        print("ElemMesh:\tApplied enrichment with id "+str(ident)+\
              " to " + str(len(elemset)) +" elements in set " + physgrp + ".")
Example #16
0
  def highlight_tags(self, sel):

    # Make sure only clicking
    if(sel.empty() != True):
      blotch = True

    bufferSize = self.view.size()
    bufferRegion = sublime.Region(0, bufferSize)
    bufferText = self.view.substr(bufferRegion)
    curPosition = sel.begin()
    foundTags = Elements.match(bufferText, curPosition, 'html')
    tag1 = { "match": foundTags[0] }
    tag2 = { "match": foundTags[1] }
    if( str(tag1['match']) != 'None' and 
        self.view.substr(tag1['match'] + 1) != '!' and 
        self.view.substr(tag1['match'] - 1) != '`' and 
        self.view.substr(tag1['match']) == '<' and 
        self.view.substr(curPosition) != '<'):

      # Get 1st Tag
      blotch = False
      tag1['begin'] = tag1['match']
      tag1['end'] = tag1['match']
      while(self.view.substr(tag1['end']) != '>'):
        tag1['end'] = tag1['end'] + 1
        if(self.view.substr(tag1['end']) == '<'):
          blotch = True
      tag1['region'] = sublime.Region(tag1['begin'], tag1['end'] + 1)

      # Get 2nd Tag
      tag2['end'] = tag2['match'] - 1
      tag2['begin'] = tag2['end']
      while(self.view.substr(tag2['begin']) != '<'):
        tag2['begin'] = tag2['begin'] - 1
      tag2['region'] = sublime.Region(tag2['begin'], tag2['end'] + 1)

      # Highlight
      if(blotch == False):
        self.highlight_us.append(tag1['region'])
        self.highlight_us.append(tag2['region'])
Example #17
0
    def mass(self, **specialisations):
        """
        specialisations maps symbol to a dictionary d providing a mass
        by d["mass"], eg:

            specialisations = { 'C' : 12.0 }
            inst.mass(C=12.0)

        or if you use the mass module:

            inst.mass(C=mass.C12)

        or you use mass in connection with the elements module:

            inst.mass(C=elements.C12)
        """

        el = Elements.Elements()
        items = self.dictForm.items()
        def get_mass(sym, massnum):
            # if mass num is None, and there is a specialisation
            # provided, we take this specialisation. Else we use
            # data from el, where a massnumber None is mapped to the
            # monoisotopic element:
            if massnum is None:
                specialisation = specialisations.get(sym)
                if specialisation is not None:
                    if isinstance(specialisation, collections.Mapping):
                        return specialisation["mass"]
                    try:
                        return float(specialisation)
                    except:
                        raise Exception("specialisation %r for %s invalid"\
                                        % (specialisation, sym))

            return el.getMass(sym, massnum)
        masses = list(get_mass(sym, massnum) for (sym, massnum), _  in items)
        if None in masses:
            return None
        return sum(m * c for m, (_, c) in zip(masses, items) )
Example #18
0
def calculation(Y,M,D,H):
    # Y = int(input('输入阳历年:'))
    # M = int(input('输入月份:'))
    # D = int(input('输入日期:'))
    # H = int(input('输入时间:'))
    lunar = sxtwl.Lunar()  #实例化日历库
    day = lunar.getDayBySolar(int(Y),int(M), int(D))  # 查询年月日
    gz = lunar.getShiGz(day.Lday2.tg,  int(H))
    Branch = [Gan[day.Lyear2.tg],Zhi[day.Lyear2.dz],Gan[day.Lmonth2.tg],Zhi[day.Lmonth2.dz],Gan[day.Lday2.tg], Zhi[day.Lday2.dz],Gan[gz.tg], Zhi[gz.dz]]
    elements=element(Branch)
    elements =Elements.elements(elements)
    # print("公历:", day.y, "年", day.m, "月", day.d, "日")
    if day.Lleap:
        Lunar_c = "润"+ymc[day.Lmc]+"月 "+rmc[day.Ldi]+"日"
    else:
        Lunar_c = ymc[day.Lmc]+"月 "+rmc[day.Ldi]+"日"
    # print("儒略日:JD", sxtwl.J2000 + day.d0)
    # print("星期", numCn[day.week])
    # print(Gan[day.Lyear2.tg], Zhi[day.Lyear2.dz], "年", Gan[day.Lmonth2.tg],Zhi[day.Lmonth2.dz], "月", \
    #       Gan[day.Lday2.tg], Zhi[day.Lday2.dz], "日", Gan[gz.tg], Zhi[gz.dz], "时")
    # print(Branch)
    # print(elements)
    return Lunar_c,Branch,elements
Example #19
0
import pygame
import Elements

background_color = (0, 0, 0)
wh = (1280, 720)

screen = pygame.display.set_mode(wh)
pygame.display.set_caption('Test of Physics')
running = True
Universe = Elements.NCUniverse(screen, wh)
TestObj = Elements.NC_Particle(screen,
                               pos=(wh[0] / 2, wh[1] / 2),
                               Radius=20,
                               Mass=50)
TestObj2 = Elements.NC_Particle(screen,
                                pos=(wh[0] / 2, wh[1] / 4),
                                Radius=10,
                                Mass=10)
TestObj2.Vector.x = 1.1

Universe.AddObject(TestObj)
Universe.AddObject(TestObj2)
print("Universe created. %sx%s" % (wh))
while running:
    screen.fill(background_color)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    #Code Of Draw
    Universe.TickUniverse()
    TestObj.Position.x = wh[0] / 2
Example #20
0
def getElementByAtomicNumber(atnum):
	for e in Elements.allElements():
		if e.atomicNumber() == atnum:
			return e
	return None
Example #21
0
def getElementBySymbol(symbol):
	for e in Elements.allElements():
		if e.symbol() == symbol:
			return e
	return None
Example #22
0
class Driver:
    '''
    This class is the Cherry Driver. With this you will interact with your browser

    Methods
    -------
    start: Runs the webdriver
    close_browser: Closes the browser... it is obvious...
    '''
    def __init__(self):
        self.host = ''
        self.session_id = ''
        self.interactions = ''
        self.elements = ''
        self.browser = ''
        self.webdriver_exec = WebDriverExecutioner()
        self.request_url = ''

    def start(self,
              capabilities,
              port='9000',
              driver_name='chrome',
              host='http://127.0.0.1'):
        '''
        Starts the webdriver and creates the session
        :param capabilities: The capabilities to run the session
        :param port: the port where the web driver will run
        :param driver_name: chrome (more to come soon...)
        :param host: by default 127.0.0.1 if you want to run this from another site put your host.
        :return: X
        '''
        self.webdriver_exec.launch_driver(port, driver_name)
        self.host = host + ':' + port + '/'
        response = requests.request(
            'POST',
            self.host + 'session',
            data=json.dumps(capabilities).encode('utf8'))
        self.session_id = json.loads(response.text)[
            'sessionId']  # Todo: see if session_id variable is necesary
        self.request_url = self.host + 'session/' + self.session_id
        self.interactions = Interactions(self.host, self.session_id)
        self.elements = Elements(self.host, self.session_id)
        self.browser = Browser(self.request_url)

    def close_browser(self):
        '''
        Closes the browser
        :return: X
        '''
        self.browser.close_browser()

    def click(self, element):
        self.interactions.click(element)

    def write(self, element, text):
        self.interactions.write(element, text)

    def navigate(self, url):
        self.browser.navigate(url)

    def quit(self):
        requests.request('DELETE', self.host + 'session/' + self.session_id)
        self.webdriver_exec.terminate_driver()

    def maximize(self):
        self.browser.maximize()

    def minimize(self):
        self.browser.minimize()

    def fullscreen(self):
        self.browser.full_screen()

    def new_window(self):
        self.browser.new_window()

    def get_url(self):
        return self.browser.get_url()

    def get_title(self):
        return self.browser.get_title()

    def direction(self, direction):
        if direction.upper() == 'BACK':
            self.browser.back()
        else:
            self.browser.forward()

    def back(self):
        self.browser.back()

    def forward(self):
        self.browser.forward()

    def refresh(self):
        self.browser.refresh()

    # GET ELEMENT METHODS

    def get_element(self, locator, value):
        '''
        Gets and element
        :param locator: The actual locator (property, id, xpath, link_text, css, partial_link_text,tag)
        :param value: The value to search the locator
        :return: an element.
        '''
        element = self.elements.get_element(locator, value)
        if element == 'Error':
            print("The element was not located")
            self.quit()
            # Probably something will go here to mark the error
            quit()
        return element

    def get_element_by_property(self, prop, value):
        value = '//*[@' + prop + ' ="' + value + '"]'
        return self.elements.get_element('xpath', value)

    def get_element_by_id(self, value):
        value = '//*[@id ="' + value + '"]'
        return self.elements.get_element('xpath', value)

    def get_element_by_xpath(self, value):
        return self.elements.get_element('xpath', value)

    def get_element_by_link_text(self, value):
        return self.elements.get_element('link text', value)

    def get_element_by_css(self, value):
        return self.elements.get_element('css selector', value)

    def get_element_by_partial_link_text(self, value):
        return self.elements.get_element('partial link text', value)

    def get_element_by_tag(self, value):
        return self.elements.get_element('tag name', value)
b = file.getBridge()

bridge = next(b)
print(bridge)
nodes = []
trusses = []
forces = []
cost = 0

memberForces = []
memberForcesEq = []

# Load everything to list of objects
for node in bridge['nodes']:
    # Load nodes
    nodes.append(el.Node(node, [float(n) for n in bridge['nodes'][node]]))
    for force in bridge['forces']:
        if node == force[0]:
            f = el.Force(force[0], [float(n) for n in force[1]])
            forces.append(f)
            nodes[-1].external.append(f)
for truss in bridge['trusses']:
    # Load trusses
    trusses.append(el.Truss(truss))
    trusses.append(el.Truss([truss[1], truss[0]]))

# Load trusses into the nodes
for truss in trusses:
    for node in nodes:
        if truss.startID == node.id:
            node.connections.append(truss)
Example #24
0
    du = funcs.d_exact_linear
    uh_f = funcs.approx_linear
    f_string = ["x", ""]
elif choice == "quadratic":
    f = funcs.quadratic
    fab = funcs.fe
    u = funcs.exact_quadratic
    du = funcs.d_exact_quadratic
    uh_f = funcs.approx_quadratic
    f_string = ["----", "----"]

# assign nodes to elements
k = nodes_per_element - 2
m = 0  # factor for shifting up initial node number in each element
for i in range(1, num_elements + 1):  # go through last node in each element
    this_element = Elements.Element(i)
    nodes_to_add = []
    for j in range(0,
                   nodes_per_element):  # go through each node in the element
        nodes_to_add.append(Nodes.nodes_list[(i + m) + j])
    this_element.add_nodes(nodes_to_add)
    m += k

# initialize K matrix
K = np.zeros((len(active_nodes), len(active_nodes)), dtype=np.float16).tolist()
# F = np.zeros((1, len(active_nodes)), dtype=np.float16)
F = []
for node in active_nodes:
    F.append(0.0)

# create ID matrix
Example #25
0
    def launch(__self__, __input__=None):
        global DETECTOR
        if not DETECTOR.Configured:
            messagebox.showerror(
                "Detector not configured!",
                "SDD Detector parameters are not configured!")
            return

        if __input__ is not None:
            input_file, output_file = __input__, __self__.out
            exe_str = r"xrmc {}".format(input_file)
            print("SIMULATION START!")
            p1 = subprocess.Popen(
                exe_str, stderr=subprocess.PIPE)  #, stdout=subprocess.PIPE)
            p1.wait()
            print("SIMULATION DONE")
            for file_ in __self__.temp:
                os.remove(file_)
                print(f"Removed {file_}")

        else:
            compounds, materials, thicknesses = [], [], []
            skipped_materials, skipped_thick = [], []
            for i in range(len(__self__.layers)):
                if __self__.layers[i].get() \
                        and __self__.layers[i].get() != "Custom"\
                        and __self__.thicknesses[i].get() > 0.0:
                    materials.append(__self__.layers[i].get())
                    thicknesses.append(__self__.thicknesses[i].get())
                else:
                    skipped_materials.append(__self__.layers[i].get())
                    skipped_thick.append(i)
            if skipped_materials != []:
                text1 = ""
                for mat, l in zip(skipped_materials, skipped_thick):
                    if mat == "": mat = "Empty"
                    text1 = str(mat) + f" - Layer {l}"
                messagebox.showinfo("Invalid layers!",
                                    f"Ignoring layers: {text1}")
            for material in materials:
                a = Elements.compound()
                a.set_compound(material)
                compounds.append(a)

            pars = Configure.Parser()
            pars.get_planes(thicknesses)
            input_file, output_file = pars.write_inputs(compounds)

            exe_str = r"xrmc {}".format(input_file)
            print("SIMULATION START!")
            p1 = subprocess.Popen(
                exe_str, stderr=subprocess.PIPE)  #, stdout=subprocess.PIPE)
            p1.wait()
            print("SIMULATION DONE")
            if __self__.EraseVar.get():
                for f in pars.temporary_files:
                    try:
                        os.remove(f)
                        print(f"Got rid of {f}")
                    except:
                        print(f"Could not remove {f}!")

        print("Output file: ", output_file)
        load_dat(output_file=output_file)
        return
def run_elements(src_dir, dest_dir, sub_dir):
    shutil.rmtree(os.path.join(dest_dir, sub_dir), ignore_errors=True)
    Elements.process(src_dir, dest_dir, sub_dir)
Example #27
0
from Hero import *
from Monster import *
from Elements import *
from Potion import *
from Item import *
from Battle import *
from Stats import *
#TODO!! Сделать отмени в бою!
#TODO! Добавить canUse методы в другие классы (weapon,armor - может можно просто в ITEM)
#TODO! внутри spell.__str__() выводится имя спелла и Описани того что он делает( зависит от спелла )

player = Hero()
dragonMonster = Monster("Dragon", Stats(9, 10, 4, 4, 6, 1), Damage(2, 6), 4,
                        Elements(), 10)
puppyMonster = Monster("Puppy", Stats(1, 2, 1, 2, 1, 1), Damage(1, 1), 1,
                       Elements(), 5)

# TODO Если player.class = "Warrior" сделать
# player = Warrior(player)
#

magicBow = Weapon("Magic Bow", Stats(Agi=3, Dex=2), Damage(1, 5))
fireSword = Weapon("Fire Sword", Stats(Str=3, Con=2), Damage(1, 5))

player.inventory.addItem(magicBow)
player.inventory.addItem(fireSword)

player.equip(
    utils.getChoice("Choose weapon to equip:", player.inventory.items()))

bronzeHead = Armor("Bronze Helmet", Stats(Con=1), 1, armorType.Head)
def run_elements(src_dir, dest_dir, sub_dir):
    shutil.rmtree(os.path.join(dest_dir, sub_dir), ignore_errors=True)
    Elements.process(src_dir, dest_dir, sub_dir)
import Elements
from Debugger import Debugger


def CreateOrbitSpeed(mass, distance):
    return ((6.67408e-11 * mass) / distance)**0.5


pygame.font.init()
background_color = (0, 0, 0)
wh = (1600, 1000)
AU = 1500000000000
screen = pygame.display.set_mode(wh)
pygame.display.set_caption('Test of Scaled Physics')
running = True
Universe = Elements.NCSUniverse(screen, wh)
GBX = Elements.GridBarX(screen, wh, Universe.scaler)
GBY = Elements.GridBarY(screen, wh, Universe.scaler)
mscaler = AU / 8000 / wh[0]
Universe.scaler.SetRate(1, mscaler)
print("Size : X: %.1fm - Y: %1.fm" % (Universe.scaler.ConvertMeters(
    wh[0]), Universe.scaler.ConvertMeters(wh[1])))
TestObj = Elements.NCS_Particle(screen,
                                pos=(0, 0),
                                Radius=6371000,
                                Mass=5.9736e+24,
                                scaler=Universe.scaler,
                                name="Dunya",
                                Color=Elements.WavelengthToRgb(720))
TestObj2 = Elements.NCS_Particle(
    screen,
def detect_line_segments_demo():
    cap = cv2.VideoCapture(0)
    flag = False
    circlelist = []
    r,g,b = (0,0,0)
    iCP = None
    drow =  True
    color = (0,0,0) 

    while True:
        _, img = cap.read()
        if img is None:
            break
        img = cv2.medianBlur(img,5)
        cimg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        circles = cv2.HoughCircles(cimg,cv2.HOUGH_GRADIENT,1,20,
                            param1=50,param2=75,minRadius=15,maxRadius=150)

        if (circles is None) and (flag == False):
            pass
        else:
            flag = True
            if (circles is not None):
                circles = np.int16(np.around(circles))
                for i in circles[0,:]:
                    
                    if iCP is None:
                        iCP = i

                    #circle同士が若干離れていたら間にcircleを距離に応じて入れる
                    xsub=abs(i[0]-iCP[0])
                    ysub=abs(i[1]-iCP[1])
                    sub = xsub if xsub > ysub else ysub
                    sub = int(sub/5)
                    z = int(math.sqrt(xsub**2 + ysub**2))
                    
                    #print(f'sub = {sub: 4d}', end='\r')
                    if ((z > 10 and z < 80)and drow == True): 
                        xsum =  iCP[0] + ( (i[0]-iCP[0]) / sub )
                        ysum =  iCP[1] + ( (i[1]-iCP[1]) / sub )
                        xtemp = xsum - iCP[0]
                        ytemp = ysum - iCP[1]

                        k=0
                        while k < sub:
                            xsumtemp = xsum + (xtemp * k)
                            ysumtemp = ysum + (ytemp * k)
                            ele = Elements()
                            ele.setAll(int(xsumtemp), int(ysumtemp), i[2], color)
                            circlelist.append(ele)
                            k += 1
                            
                    ele = Elements()
                    ele.setAll(i[0],i[1],i[2],color)

                    if drow== False :
                        deleteCircles(circlelist,ele)
                    else:
                        circlelist.append(ele)
                    #print(f'circlelist = {len(circlelist): 4d}', end='\r')
                    iCP=i
            j = 0 
            while j < len(circlelist):
                cv2.circle(img,(circlelist[j].x, circlelist[j].y),int(circlelist[j].r/2),circlelist[j].color,-1) 
                j += 1

        
        # 画像の高さ、幅を取得
        height = img.shape[0]
        width = img.shape[1]

        # フォント指定
        fontType = cv2.FONT_HERSHEY_SIMPLEX
        # テキスト表示
        mode = "oekaki mode" if drow else "keshigomu mode"  
        cv2.putText(img, mode,(int(width)-200,int(height)-20), fontType, 0.7, (0, 0, 0), 2, -1)  

        cv2.imshow('detected 1',img)

        key = cv2.waitKey(10)

        if key is ord('x'):
            circlelist = []
            flag = False

        if key is ord('d'):
            drow = False

        if key is ord('w'):
            drow = True

        if (key is ord('r')
        or key is ord('g')
        or key is ord('b')
        or key is ord('k')):
            color=change_color(key)

        if key is ord('q'):
            picture(img)

        if key is ord('e'):
            break


    cv2.destroyAllWindows()
    cap.release()
Example #31
0
 def reset(self):
     self.ball = Elements.Base()
     self.player1 = Elements.Player()
     self.player2 = Elements.Player()
     self.inter = Interactions.Interactions()
     self.cage = Elements.Box(20, 20, (100, 100))