def __init__(self): pygame.init() ICON_IMG = pygame.transform.scale( pygame.image.load(os.path.join('assets', 'img', 'chocolate.png')), (32, 32)) self._BACKGROUND_IMG = pygame.image.load( os.path.join('assets', 'img', 'background.jpg')) self._GROUND_IMG = pygame.image.load( os.path.join('assets', 'img', 'ground.png')) self._PICKED_EGG_SOUND = pygame.mixer.Sound( os.path.join('assets', 'sfx', 'picked_egg.wav')) self._LOST_EGG_SOUND = pygame.mixer.Sound( os.path.join('assets', 'sfx', 'lost_egg.wav')) self._GAME_OVER_SOUND = pygame.mixer.Sound( os.path.join('assets', 'sfx', 'game_over.wav')) self._WIDTH, self._HEIGHT = 800, 480 self._WIN = pygame.display.set_mode((self._WIDTH, self._HEIGHT)) pygame.display.set_caption("Egg Hunt") pygame.display.set_icon(ICON_IMG) self._BLACK = (0, 0, 0) self._WHITE = (255, 255, 255) self._FONT = pygame.font.Font(None, 60) self._CLOCK = pygame.time.Clock() self._FPS = 60 self._basket = Basket(self._WIN) self._egg = Egg(self._WIN) self._score_bar = ScoreBar(self._WIN)
def test_constructor(self): self.assertIsInstance(self.egg, Egg) with self.assertRaises(ValueError): e = Egg(self._ID, -1, "Calgary") with self.assertRaises(TypeError): e = Egg(self._ID, 6, 2)
def _create_egg(self, egg_number, row_number): """Create an egg and place it in the row""" egg = Egg(self) #create an egg egg_width, egg_height = egg.rect.size #Each egg is pushed to the right one 'egg size' from the left margin. then x2 to account for width of each egg. #multiply it by egg position. Egg.x attribute sets postion of rect. egg.x = egg_width + 2 * egg_width * egg_number egg.rect.x = egg.x egg.rect.y = egg.rect.height + 2 * egg.rect.height * row_number self.eggs.add(egg)
class EggRing(object): def __init__(self, x, y, t, sp): self.ovoid = Egg(x, y, t, sp) self.circle = Ring() self.circle.start(x, y - sp / 2) def transmit(self): self.ovoid.wobble() self.ovoid.display() self.circle.grow() self.circle.display() if self.circle.on == False: self.circle.on = True
def create_member(self, member_type: str, pokedex_num: int, source: str, nickname: str = None, item: str = None, ability: str = None, json: Dict = None) -> int: """ Adds a member (egg or Pokemon) to the player's _pc. Depending on the type of member, this function adds a new entry to the player's party. It also assigns the Pokemon an ID, and then increments it by 1 so that it is unique for the next member that is added. :param member_type: The party member type, either "Egg" or "Pokemon" :param pokedex_num: The Pokedex number that corresponds with the Pokemon species. :param source: The location that the Pokemon/Egg was acquired. :param nickname: The given name for the Pokemon. :param item: The item that the Pokemon is currently holding. :param ability: The Pokemon's special ability. :return: No return :rtype: None """ self._validate_pokedex_number(pokedex_num) if not nickname: nickname = self._POKEDEX[pokedex_num][0] if member_type == Pokemon.member_type(): self._pc_pokemon[self._ID] = Pokemon(self._ID, pokedex_num, source, nickname=nickname, item=item, ability=ability, json=json) self._ID += 1 elif member_type == Egg.member_type(): self._pc_pokemon[self._ID] = Egg(self._ID, pokedex_num, source, nickname=nickname, item=item, json=json) self._ID += 1 else: raise ValueError(f"{member_type} is not a valid Party Member type") self._write_to_file() return self._ID - 1
def __init__(self, parent=None): super(EggEditor, self).__init__(parent) self.editor = TextEdit() self.editor.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # self.editor.setTextInteractionFlags(Qt.LinksAccessibleByMouse) # 링크로 접속 허용?? layout = QVBoxLayout() # appear virtically layout.setMargin(0) layout.addWidget(self.editor) self.menuBar = QMenuBar(self) layout.setMenuBar(self.menuBar) self.setupMenu() self.setLayout(layout) self.resize(700, 700) self.__defineAttributes() self.__setShortCut() self.note = Egg()
class ConfigXML(object): """Interact with config file in xml format""" def __init__(self, strPackageName, strPath, strXMLFile): self.egg = Egg(strPackageName) self.config_full_path = self.egg.resource_filename(strPath, strXMLFile) def __del__(self): del self.config_full_path #Call class Egg's destructor del self.egg def save(self, dictData): """ Save data to xml file in temp folder. Used to be called saveXMLData""" with codecs.open(self.config_full_path, "r", "utf-8", "replace") as fIn: strXML = fIn.read() dom = parseString(strXML) #Update xml values for strKey in dictData.keys(): #Fix case: xml element (text node) "data" is non-existant ( i.e <pop3_port/> ) child = dom.getElementsByTagName(strKey)[0].firstChild if child is None and dictData[strKey] is not None: parent = dom.getElementsByTagName(strKey)[0] child_text = dom.createTextNode('text') parent.appendChild(child_text) #createTextNode() then appendChild() else: pass try: dom.getElementsByTagName(strKey)[0].firstChild.data = dictData[strKey] except AttributeError, why: print "ConfigXML->save No key %(key)s" % {'key': strKey} print "\tdom", dom.getElementsByTagName(strKey)[0].firstChild pass else: #print "ConfigXML->save strKey %(key)s: %(value)s " % { 'key': strKey, 'value': dictData[strKey]} pass #Update temp file with codecs.open(self.config_full_path, "wb", "utf-8", "replace") as fOut: fOut.write( dom.toxml("utf-8") )
def _create_fleet(self): """Create the fleet of eggs.""" #Create an egg and find the number of eggs ina row # Spacing between each egg is equal to one egg width egg = Egg(self) # need an egg to calculate width/height egg_width, egg_height = egg.rect.size #get the egg's w + h from tuple size attribute and store it in a variable available_space_x = self.settings.screen_width - (2 * egg_width) #calc horizontal space number_eggs_x = available_space_x // (2 * egg_width) #calcs number of eggs in row #Determine the number of rows of eggs that fit on the screen. owl_height = self.owl.rect.height #calc the avail space, find vertical space by subtracting the egg height from the top of the game # and the owl height from the bottom + 2 egg heights from bottom available_space_y = (self.settings.screen_height - (3 * egg_height) - owl_height) number_rows = available_space_y // (2 * egg_height) #create the full fleet of eggs. for row_number in range(number_rows): # creates number of rows we want for egg_number in range(number_eggs_x): #creates the eggs in one row self._create_egg(egg_number, row_number) # creates an egg per number of eggs per row
def setUp(self): random.seed(13) self.egg = Egg(self._ID, 7, "Calgary", nickname="Flyboy")
class EggTestClass(unittest.TestCase): _ID = 1 def setUp(self): random.seed(13) self.egg = Egg(self._ID, 7, "Calgary", nickname="Flyboy") # print(self.egg.steps_remaining, self.egg.steps_required) def test_constructor(self): self.assertIsInstance(self.egg, Egg) with self.assertRaises(ValueError): e = Egg(self._ID, -1, "Calgary") with self.assertRaises(TypeError): e = Egg(self._ID, 6, 2) def test_steps_required(self): self.assertEqual(self.egg.steps_required, 3801) self.egg.add_steps(1) self.assertEqual(self.egg.steps_required, 3801) def test_steps_remaining(self): self.assertEqual(self.egg.steps_remaining, 3801) self.egg.add_steps(1) self.assertEqual(self.egg.steps_remaining, 3800) def test_add_steps(self): steps_remaining = self.egg.steps_remaining self.egg.add_steps(10) self.assertEqual(self.egg.steps_remaining, steps_remaining - 10) self.egg.add_steps(steps_remaining) self.assertTrue(self.egg.hatched) def test_description(self): print(self.egg.height, self.egg._weight) self.assertEqual( self.egg.description, "Your Flyboy is 1053.07cm tall and 296.06kg. Not currently in party" ) def test_hatched(self): self.egg.add_steps(self.egg.steps_remaining) self.assertTrue(self.egg.hatched) def test_member_type(self): self.assertEqual(self.egg.member_type(), "Egg") def test_to_dict(self): egg_dict = self.egg.to_dict() test_dict = { "id": self.egg.id, "member_type": self.egg.member_type(), "pokedex_num": self.egg.pokedex_num, "source": self.egg.source, "nickname": self.egg.nickname, "item": None, "in_party": self.egg.in_party, "weight": self.egg.weight, "height": self.egg.height, "date_acquired": str(self.egg.date_acquired), "steps_required": self.egg.steps_required, "steps_remaining": self.egg.steps_remaining, "hatched": self.egg.hatched } self.assertEqual(egg_dict, test_dict)
def __init__(self, x, y, t, sp): self.ovoid = Egg(x, y, t, sp) self.circle = Ring() self.circle.start(x, y - sp / 2)
def read_images(): n_image = Egg("nhk_logo_n.png", 372, 242, 0) h_image = Egg("nhk_logo_h.png", 372, 242, 290) k_image = Egg("nhk_logo_k.png", 372, 242, 579) return n_image, h_image, k_image
def main(): pokeball = Egg() answer_input = ["Y", "N", "M", "F"] answer_input = [answer.casefold() for answer in answer_input] while True: if isinstance(pokeball, Egg): print( "You received a new Pokeball, would you like to see your new Pokemon? (Y/N):" ) choice = input().casefold() if choice == answer_input[0]: # YES pokeball = pokeball.hatch() print("========================") print("You got...", Egg.intro_header_name()) print("========================") elif choice == answer_input[1]: # NO print("Sad to see you go. Goodbye! 👋") return else: print("Sorry, your choice is invalid!\n") else: choice = UserInterface.menu(pokeball) if choice == "1": # game game_choice = UserInterface.game_menu() pokeball.play_game(game_choice) elif choice == "2": # feed feed_choice = input("(F)ood or (M)edicine: ").casefold() if feed_choice == answer_input[2]: # MEDICINE pokeball.eat_medicine() elif feed_choice == answer_input[3]: # FOOD food_choice = UserInterface.food_menu() pokeball.eat_food(food_choice) elif choice == "3": # status check status = pokeball.check_status() if status == -1: # checks the returned status of dead pokemon pokeball = Egg() elif choice == "4": print("Thanks for playing, Goodbye! 👋") return
class Game: def __init__(self): pygame.init() ICON_IMG = pygame.transform.scale( pygame.image.load(os.path.join('assets', 'img', 'chocolate.png')), (32, 32)) self._BACKGROUND_IMG = pygame.image.load( os.path.join('assets', 'img', 'background.jpg')) self._GROUND_IMG = pygame.image.load( os.path.join('assets', 'img', 'ground.png')) self._PICKED_EGG_SOUND = pygame.mixer.Sound( os.path.join('assets', 'sfx', 'picked_egg.wav')) self._LOST_EGG_SOUND = pygame.mixer.Sound( os.path.join('assets', 'sfx', 'lost_egg.wav')) self._GAME_OVER_SOUND = pygame.mixer.Sound( os.path.join('assets', 'sfx', 'game_over.wav')) self._WIDTH, self._HEIGHT = 800, 480 self._WIN = pygame.display.set_mode((self._WIDTH, self._HEIGHT)) pygame.display.set_caption("Egg Hunt") pygame.display.set_icon(ICON_IMG) self._BLACK = (0, 0, 0) self._WHITE = (255, 255, 255) self._FONT = pygame.font.Font(None, 60) self._CLOCK = pygame.time.Clock() self._FPS = 60 self._basket = Basket(self._WIN) self._egg = Egg(self._WIN) self._score_bar = ScoreBar(self._WIN) def update(self): if not self._score_bar.is_empty(): keys_pressed = pygame.key.get_pressed() if keys_pressed[pygame.K_q] or keys_pressed[pygame.K_LEFT]: self._basket.move_left() elif keys_pressed[pygame.K_d] or keys_pressed[pygame.K_RIGHT]: self._basket.move_right() elif keys_pressed[pygame.K_ESCAPE]: pygame.quit() quit() else: self._basket.idle() self._basket.update() self._egg.fall() # Collision if pygame.sprite.collide_rect(self._basket, self._egg): self._egg.go_top(self._score_bar) self._score_bar.increase_score() self._PICKED_EGG_SOUND.play() elif self._egg.has_fallen(): self._egg.go_top(self._score_bar) self._score_bar.decrease_score() self._LOST_EGG_SOUND.play() def draw_background(self): self._WIN.fill(self._WHITE) self._WIN.blit(self._BACKGROUND_IMG, (0, 0)) self._WIN.blit(self._GROUND_IMG, (0, 0)) def draw_entities(self): self._basket.draw(self._WIN) self._egg.draw(self._WIN) self._score_bar.draw(self._WIN) def run(self): timer = 0 is_running = True while is_running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() self.update() self.draw_background() if not self._score_bar.is_empty(): self.draw_entities() else: # Show game over for 2 seconds self.game_over() timer += 1 if timer == 1: self._GAME_OVER_SOUND.play() if timer > self._FPS // 2: is_running = False pygame.display.update() self._CLOCK.tick(self._FPS) def game_over(self): label = self._FONT.render("Game Over", True, self._BLACK) self._WIN.blit(label, ((self._WIDTH - label.get_width()) // 2, (self._HEIGHT - label.get_height()) // 2))
def addEggs(self, count): for c in range(count): self.eggs.append(Egg()) print str(count) + ' eggs were added to ' + str(self.hashid)
def spawnEgg(self, energy, spawningUnitClass): ''' Если у юнита достаточно энергии, то он откладывает яйцо ''' Egg(field=self.field, center=(self.x, self.y), color=self.color, type_='Civilian',\ energy=energy, maxEnergy=energy, energyCons=self.energyCons/2, spawningUnitClass=spawningUnitClass) self.decreaseEnergy(energy)
class EggEditor(QDialog): def __init__(self, parent=None): super(EggEditor, self).__init__(parent) self.editor = TextEdit() self.editor.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # self.editor.setTextInteractionFlags(Qt.LinksAccessibleByMouse) # 링크로 접속 허용?? layout = QVBoxLayout() # appear virtically layout.setMargin(0) layout.addWidget(self.editor) self.menuBar = QMenuBar(self) layout.setMenuBar(self.menuBar) self.setupMenu() self.setLayout(layout) self.resize(700, 700) self.__defineAttributes() self.__setShortCut() self.note = Egg() def __defineAttributes(self): self.color_white = color['white'] self.color_highlight = color['highlight'] self.mouse_under_text = '' self.is_editing_title = False self.highlight_information = self.editor.highlight.highlight_information def __setShortCut(self): pass def isTitle(self): return True if self.editor.textCursor().blockNumber() == 0 else False def setupMenu(self): fileMenu = QMenu("&File", self) editMenu = QMenu("&Edit", self) styleMenu = QMenu("S&tyle", self) # sizeMenu = QMenu("&Size", self) # indentMenu = QMenu("&Indent", self) self.menuBar.addMenu(fileMenu) # self.menuBar.addMenu(editMenu) self.menuBar.addMenu(styleMenu) # self.menuBar.addMenu(sizeMenu) # self.menuBar.addMenu(indentMenu) # fileMenu.addAction("&Save...", self.saveFile, "Ctrl+S") # editMenu.addAction("&Copy", self.copy, "Ctrl+C") # editMenu.addAction("Cu&t", self.cut, "Ctrl+X") # editMenu.addAction("&Paste", self.paste, "Ctrl+V") styleMenu.addAction("&Bold", self.textBold, "Ctrl+B") styleMenu.addAction("&Italic", self.textItalic, "Ctrl+I") styleMenu.addAction("&Highlight", self.textHighlight, "Ctrl+H") styleMenu.addAction("&Strikethrough", self.textStrikethrough, "Ctrl+T") styleMenu.addAction("&Underline", self.textUnderline, "Ctrl+U") styleMenu.addSeparator() styleMenu.addAction("(&0) Normal", self.textSizeNormal, "Ctrl+0") styleMenu.addAction("(&1) Small", self.textSizeSmall, "Ctrl+1") styleMenu.addAction("(&2) Large", self.textSizeLarge, "Ctrl+2") styleMenu.addAction("(&3) Huge", self.textSizeHuge, "Ctrl+3") styleMenu.addSeparator() styleMenu.addAction("(&]) Indent", self.textIndent, "Alt+Right") styleMenu.addAction("(&[) Dedent", self.textDedent, "Alt+Left") def setNote(self, note): self.note = note html = note.html self.editor.setHtml(html) # self.last_block_number = self.getLastBlockNumber() ## MenuBar Function ## # File Menu # def test(self): log.debug('function for testing.') def saveFile(self): html = self.editor.toHtml() self.note.setHtml(self.editor.toHtml()) self.note.saveFile() # Edit Menu # # Style Menu # def textBold(self): if self.isTitle(): return if self.editor.fontWeight() == QFont.Bold: self.editor.setFontWeight(QFont.Normal) else: self.editor.setFontWeight(QFont.Bold) def textItalic(self): if self.isTitle(): return state = self.editor.fontItalic() self.editor.setFontItalic(not state) def textHighlight(self): if self.isTitle(): return color = self.editor.textBackgroundColor() if color.name() == self.color_highlight: color.setNamedColor(self.color_white) else: color.setNamedColor(self.color_highlight) self.editor.setTextBackgroundColor(color) def textStrikethrough(self): if self.isTitle(): return fmt = self.editor.currentCharFormat() fmt.setFontStrikeOut(not fmt.fontStrikeOut()) self.editor.setCurrentCharFormat(fmt) def textUnderline(self): if self.isTitle(): return state = self.editor.fontUnderline() self.editor.setFontUnderline(not state) def textSizeSmall(self): if self.isTitle(): return self.editor.setFontPointSize(font_size['Small']) def textSizeNormal(self): if self.isTitle(): return self.editor.setFontPointSize(font_size['Normal']) def textSizeLarge(self): if self.isTitle(): return self.editor.setFontPointSize(font_size['Large']) def textSizeHuge(self): if self.isTitle(): return self.editor.setFontPointSize(font_size['Huge']) def textIndent(self): if self.isTitle(): return def indentLine(c): textList = c.currentList() if type(textList) == QTextList: self.editor.giveList(c, 1) else: c.createList(-1) c = self.editor.textCursor() if c.hasSelection(): temp = c.blockNumber() c.setPosition(c.anchor()) diff = c.blockNumber() - temp direction = QTextCursor.Up if diff > 0 else QTextCursor.Down for n in range(abs(diff) + 1): indentLine(c) c.movePosition(direction) else: indentLine(c) def textDedent(self): if self.isTitle(): return def dedentLine(c): self.editor.giveList(c, -1) c = self.editor.textCursor() if c.hasSelection(): temp = c.blockNumber() c.setPosition(c.anchor()) diff = c.blockNumber() - temp direction = QTextCursor.Up if diff > 0 else QTextCursor.Down for n in range(abs(diff) + 1): dedentLine(c) c.movePosition(direction) else: dedentLine(c) ## Event Set ## def eventFilter(self, source, event): if event.type() == QEvent.MouseMove: self._mouseEventFilter(event) elif event.type() == QEvent.KeyRelease: self._keyReleaseEventFilter(event) elif event.type() == QEvent.KeyPress: self._keyPressEventFilter(event) return self.editor.eventFilter(source, event) def _mouseEventFilter(self, event): """""" def eventNoButton(): virtual_cursor = self.editor.cursorForPosition(mouse_pos) # 설렉션 잡을 때 마다 생성해줘야 함. virtual_cursor_move = self.editor.cursorForPosition(mouse_pos) virtual_cursor_move.movePosition(virtual_cursor.StartOfWord) cursor_rect_start = self.editor.cursorRect(virtual_cursor_move) virtual_cursor_move.movePosition(virtual_cursor.EndOfWord) cursor_rect_end = self.editor.cursorRect(virtual_cursor_move) word_position = (cursor_rect_start.x(), cursor_rect_end.x(), cursor_rect_start.top(), cursor_rect_start.top() + cursor_rect_start.height()) allow_point = 8 virtual_cursor.select(QTextCursor.WordUnderCursor) self.virtual_cursor = virtual_cursor text = virtual_cursor.selectedText() in_wide = word_position[0] - allow_point <= mouse_pos.x() <= word_position[1] + allow_point in_height = word_position[2] - allow_point <= mouse_pos.y() <= word_position[3] + allow_point if in_wide and in_height: if len(text) > 0: if self.mouse_under_text == text: if self.editor.viewport().cursor().shape() == 4 \ and virtual_cursor.charFormat().isAnchor(): self.editor.viewport().setCursor(QCursor(Qt.PointingHandCursor)) else: sentence = 'selectedText: %s' % text sentence = sentence.encode('utf-8') self.mouse_under_text = text if virtual_cursor.charFormat().isAnchor(): log.info(virtual_cursor.charFormat().anchorHref()) self.editor.viewport().setCursor(QCursor(Qt.PointingHandCursor)) else: self.editor.viewport().setCursor(QCursor(Qt.IBeamCursor)) else: self.mouse_under_text = '' pass # do other stuff else: self.editor.viewport().setCursor(QCursor(Qt.IBeamCursor)) def eventNoButton2(): def isPositionInLink(): if block_number in self.highlight_information: highlight_info = self.highlight_information[block_number] highlight_info.sort() for info_list in highlight_info: print(cursor_number_in_block, info_list) if info_list[0] <= cursor_number_in_block: if cursor_number_in_block <= info_list[1]: return True else: break return False virtual_cursor = self.editor.cursorForPosition(mouse_pos) # 설렉션 잡을 때 마다 생성해줘야 함. block_number = virtual_cursor.block().blockNumber() cursor_number_in_block = virtual_cursor.positionInBlock() virtual_cursor_move = self.editor.cursorForPosition(mouse_pos) virtual_cursor_move.movePosition(virtual_cursor.StartOfWord) cursor_rect_start = self.editor.cursorRect(virtual_cursor_move) virtual_cursor_move.movePosition(virtual_cursor.EndOfWord) cursor_rect_end = self.editor.cursorRect(virtual_cursor_move) word_position = (cursor_rect_start.x(), cursor_rect_end.x(), cursor_rect_start.top(), cursor_rect_start.top() + cursor_rect_start.height()) allow_point = 8 virtual_cursor.select(QTextCursor.WordUnderCursor) self.virtual_cursor = virtual_cursor text = virtual_cursor.selectedText() in_wide = word_position[0] - allow_point <= mouse_pos.x() <= word_position[1] + allow_point in_height = word_position[2] - allow_point <= mouse_pos.y() <= word_position[3] + allow_point if in_wide and in_height: if len(text) > 0: isPositionInLink() if self.mouse_under_text == text: # and virtual_cursor.charFormat().isAnchor(): if self.editor.viewport().cursor().shape() == Qt.IBeamCursor \ and isPositionInLink(): self.editor.viewport().setCursor(QCursor(Qt.PointingHandCursor)) else: sentence = 'selectedText: %s' % text sentence = sentence.encode('utf-8') self.mouse_under_text = text if virtual_cursor.charFormat().isAnchor(): log.info(virtual_cursor.charFormat().anchorHref()) self.editor.viewport().setCursor(QCursor(Qt.PointingHandCursor)) else: self.editor.viewport().setCursor(QCursor(Qt.IBeamCursor)) else: self.mouse_under_text = '' pass # do other stuff else: self.editor.viewport().setCursor(QCursor(Qt.IBeamCursor)) mouse_pos = event.pos() if event.buttons() == Qt.NoButton: # eventNoButton() eventNoButton2() def _keyReleaseEventFilter(self, event): # print(key_type[event.key()]) pass def _keyPressEventFilter(self, event): """
def connect(): global table, x_angle, y_angle, root, embedFrame, play server = tkFileDialog.askopenfilename(initialdir=".", title="Select server", filetypes=(("Python files", "*.py"), ("All Files", "*.*"))) print server if server == "": # if server openning was cancelled then return return else: try: path = server.split('/') serverfilename = path[len(path) - 1] cmd = 'python ' + server p = subprocess.Popen( cmd, shell=False ) #p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) #out, err = p.communicate() #result = out.split('\n') #for lin in result: # if not lin.startswith('#'): # print(lin) # TODO 4: improve process control: https://stackoverflow.com/questions/3781851/run-a-python-script-from-another-python-script-passing-in-args # Show Confirmation if the connection was set up correctly except: tkMessageBox.showerror("Error", "Server failed!") return # TODO 3: Check if another process is not open and if is close it before staretin gthe new one. # If another file is open already then close it if table != None: closefile() # Change App title to include currently open file root.title('Smart Egg 3D Visualisation - ' + serverfilename) # Create embed frame for pygame window embedFrame = tk.Frame(root, width=1100, height=650) embedFrame.grid(row=0, column=0) # Initiate and embed pygame os.environ['SDL_WINDOWID'] = str(embedFrame.winfo_id()) screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE | OPENGL | DOUBLEBUF) resize(*FULLSCREEN_SIZE) pygame.init() pygame.display.init() # Initiate OpenGL init_opengl() #clock = pygame.time.Clock() # Create OpenGL object egg = Egg((0.7, 0.0, 0.0), (1, .95, .8)) root.update() # loop control variable play = True while play: #then = pygame.time.get_ticks() values = read_values() x_angle = values[1] y_angle = values[2] drawXYZCoordinate() # Draw XYZ axis labels drawText3D(-1.2, -1.0, -2.4, 'x') drawText3D(-2.2, -0.6, -2.4, 'y') drawText3D(-2.2, -1.0, -2.0, 'z') glPushMatrix() # rotate object glRotate(float(x_angle), 0, 0, 1) glRotate(float(y_angle), 1, 0, 0) # render object and text egg.render(pygame) glPopMatrix() # refresh screen pygame.display.flip()
def openfile(): global table, time, x_angle, y_angle, day, month, year, root, embedFrame, recordsFrame, play name = tkFileDialog.askopenfilename(initialdir=".", title="Select file", filetypes=(("Text File", "*.txt"), ("All Files", "*.*"))) if name == "": # if file openning was cancelled then return return else: try: path = name.split('/') # get date from file name filename = path[len(path) - 1] day = filename[6:8] month = filename[4:6] year = filename[2:4] # create data model = TableModel() # load data data = load_data(name) # import data ti tablemodel model.importDict(data) except: tkMessageBox.showerror("Error", "File reading failed!") return # If another file is open already then close it if table != None: closefile() # Change App title to include currently open file root.title('Smart Egg 3D Visualisation ver.1.1 - ' + filename) # Create embed frame for pygame window embedFrame = tk.Frame(root, width=700, height=600) embedFrame.grid(row=0, column=0) # Create embed frame for table recordsFrame = tk.Frame(root, width=450, height=600) recordsFrame.grid(row=0, column=1) recordsFrame.pack_propagate(0) # Create table for records preview table = TableCanvas(recordsFrame, name="tablica", model=model, width=420, height=600, cols=0, rows=0, cellwidth=50, editable=False, showkeynamesinheader=True, reverseorder=0) table.grid(row=0, sticky=W + N + S) table.createTableFrame() # arrange columns width and order model.moveColumn(model.getColumnIndex('time'), 1) model.moveColumn(model.getColumnIndex('x'), 2) model.moveColumn(model.getColumnIndex('y'), 3) model.moveColumn(model.getColumnIndex('z'), 4) model.moveColumn(model.getColumnIndex('roll'), 5) model.moveColumn(model.getColumnIndex('pitch'), 6) model.columnwidths['time'] = 150 table.redrawTable() # Initiate and embed pygame os.environ['SDL_WINDOWID'] = str(embedFrame.winfo_id()) #os.environ['SDL_VIDEODRIVER'] = 'windib' screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE | OPENGL | DOUBLEBUF) resize(*SCREEN_SIZE) pygame.init() pygame.display.init() #Bind keys and buttons events root.bind('<ButtonRelease-1>', handle_click) #click release event root.bind_all("<Up>", handle_arrow_keys) #press Up key event root.bind_all("<Down>", handle_arrow_keys) #press Down key event root.bind_all("<Left>", handle_arrow_keys) #press Left key event root.bind_all("<Right>", handle_arrow_keys) #press Right key event # Initiate OpenGL init_opengl() # Create OpenGL object egg = Egg((0.7, 0.0, 0.0), (1, .95, .8)) # Load first element values = get_record(0) if values != None: time = values[0] + ' ' + values[1] x_angle = values[2] y_angle = values[3] root.update() # loop control variable play = True while play: drawXYZCoordinate() # Draw XYZ axis labels drawText3D(-1.2, -1.0, -2.4, 'x') drawText3D(-2.2, -0.6, -2.4, 'y') drawText3D(-2.2, -1.0, -2.0, 'z') for event in pygame.event.get(): if event.type == KEYUP: handle_arrow_keys(event.key) glPushMatrix() # rotate object glRotate(float(x_angle), 0, 0, 1) glRotate(float(y_angle), 1, 0, 0) # render object and text egg.render(pygame) glPopMatrix() drawText(0, 2, time) # refresh screen pygame.display.flip() root.update()
def __init__(self, strPackageName, strPath, strXMLFile): self.egg = Egg(strPackageName) self.config_full_path = self.egg.resource_filename(strPath, strXMLFile)