def __init__(self): """Constructor of the Game""" self._running = True self.size = self.width, self.height = 450, 600 # create main display - 640x400 window # try to use hardware acceleration self.screen = pygame.display.set_mode((400,200))#, pygame.HWSURFACE pygame.display.set_caption('AirHockey Server') self.clock = pygame.time.Clock() # set default tool self.tool = 'run' self.player = Player.Player(1,r = 30 ) # Синий нижний игрок self.player.start_pos(self) self.cursor1 = Cursor.Cursor(player=self.player,game=self) self.player0 = Player.Player(0,r = 30 ) # Красный верхний игрок self.player0.start_pos(self) self.cursor0 = Cursor.Cursor(player=self.player0,game=self) self.players = (self.player0, self.player) self.ball = Ball.Ball(x = self.width/2, y = self.height/2) self.ethik = 10 # Толщина отступов self.ecolor = (255,179,0) self.gate = 40 # Полудлина ворот self.pressed = pygame.key.get_pressed() self.cursor_text = 5 self.start_server() self.cursors = (self.cursor0,self.cursor1) self.mode = 3
def draw(frame_time): global objList, map clear_canvas() map.Draw() for k in objList.keys(): for o in objList[k]: o.Draw(frame_time) Cursor.draw(frame_time) update_canvas()
def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME + '/music/' + self.party['map']['music'] + '.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME + "/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME + "/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME + "/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME + "/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME + "/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask, 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start()
def __init__(self, posx, posy, width, height, cursor_size, background_colour = (255,255,255), buttons = [], text_size = 25): self.posx = posx self.posy = posy self.buttons = buttons self.background = pygame.Surface((width, height), pygame.SRCALPHA) self.background.fill(background_colour) self.option = 0 self.num_options = 0 self.text_size = text_size self.cursor = Cursor(size = cursor_size)
class Menu: def __init__(self, posx, posy, width, height, cursor_size, background_colour = (255,255,255), buttons = [], text_size = 25): self.posx = posx self.posy = posy self.buttons = buttons self.background = pygame.Surface((width, height), pygame.SRCALPHA) self.background.fill(background_colour) self.option = 0 self.num_options = 0 self.text_size = text_size self.cursor = Cursor(size = cursor_size) #We need to pass the set of buttons just in case you added a new set for submenues def update(self, buttons = None): if buttons == None: buttons = self.buttons button = self.getButton(self.option) (surf,rect) = button self.cursor.update(rect) def render(self, screen, buttons = None): if buttons == None: buttons = self.buttons self.update() screen.blit(self.background, (self.posx,self.posy)) for ((buttonSurf, buttonRect), text) in buttons: screen.blit(buttonSurf, buttonRect) self.cursor.render(screen) def changeOption(self, offset): self.option = (self.option + offset)%len(self.buttons) if self.option < 0: self.option = len(self.buttons) def getOption(self): return self.option def setOption(self, option): self.option = option def getTextSize(self): return self.text_size def appendButton(self, text, posx, posy, colour=(255, 255, 255), size = 25, position = TextPosition.left, font = F_DROID_SANS): self.buttons.append((writeText(text, posx, posy, colour, size, position, font), text)) self.num_options += 1 def getButtonText(self, index = -1): if index != -1: opt = index else: opt = self.option (button, text) = self.buttons[opt] return text def getButton(self, index): (button, text) = self.buttons[index] return button def getNumOptions(self): return self.num_options
def SendMouseClick(a): x, y = Recognition.getXYCoord(a) print(x,y) if (x != -999 & y != -999): Cursor.MoveCursor(x,y) pyautogui.click(x,y) time.sleep(0.5)
def schettings(oldSpeed): selfIntro = True largeText = pygame.font.Font('freesansbold.ttf', 30) TextSurfSchpeed, TextRectSchpeed = text_objects("Schpeed", largeText) TextRectSchpeed.left = ((width / 4)) TextRectSchpeed.centery = ((height / 4)) TextSurfBonus, TextRectBonus = text_objects("Bonus", largeText) TextRectBonus.left = ((width / 4)) TextRectBonus.centery = ((height / 2)) menuPoints = ((TextSurfSchpeed, TextRectSchpeed, "Schpeed"), (TextSurfBonus, TextRectBonus, "Bonus")) cursor = Cursor.Cursor(cursorImage, 10, 10, 25, 25) currentCursor = 0 returnValue = None while selfIntro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == KEYDOWN: if event.key == 13: selfIntro = False returnValue = oldSpeed elif event.key == 27: pygame.quit() quit() elif event.key == 274: if currentCursor < (len(menuPoints) - 1): currentCursor = currentCursor + 1 elif event.key == 273: if currentCursor > 0: currentCursor = currentCursor - 1 elif event.key == 276: oldSpeed = oldSpeed - 1 elif event.key == 275: oldSpeed = oldSpeed + 1 elif event.key == 93: oldSpeed = oldSpeed + 10 elif event.key == 47: oldSpeed = oldSpeed - 10 screen.fill(black) TextSurfSchpeedValue, TextRectSchpeedValue = text_objects( str(oldSpeed), largeText) TextRectSchpeedValue.left = (width / 1.5) TextRectSchpeedValue.centery = (TextRectSchpeed.centery) count = 0 while count < len(menuPoints): if currentCursor == count: cursor.setPos(menuPoints[count][1].left - 26, menuPoints[count][1].top + 2) count = count + 1 screen.blit(cursor.image, cursor.rectPoint) screen.blit(TextSurfSchpeed, TextRectSchpeed) screen.blit(TextSurfSchpeedValue, TextRectSchpeedValue) screen.blit(TextSurfBonus, TextRectBonus) pygame.display.update() clock.tick(15) if returnValue is not None: return returnValue
def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME+'/music/'+self.party['map']['music']+'.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME+"/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME+"/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME+"/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME+"/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME+"/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask , 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start()
def gameIntro(): selfIntro = True largeText = pygame.font.Font('freesansbold.ttf', 30) TextSurfSchnake, TextRectSchnake = text_objects("Schnake", largeText) TextRectSchnake.left = ((width / 4)) TextRectSchnake.centery = ((height / 4)) TextSurfSchettings, TextRectSchettings = text_objects( "Schettings", largeText) TextRectSchettings.left = ((width / 4)) TextRectSchettings.centery = ((height / 2)) TextSurfSchcoreboard, TextRectSchcoreboard = text_objects( "Schcoreboard", largeText) TextRectSchcoreboard.left = ((width / 4)) TextRectSchcoreboard.centery = ((height / 4 * 3)) menuPoints = ((TextSurfSchnake, TextRectSchnake, "Schnake"), (TextSurfSchettings, TextRectSchettings, "Schettings"), (TextSurfSchcoreboard, TextRectSchcoreboard, "Schcoreboard")) cursor = Cursor.Cursor(cursorImage, 10, 10, 25, 25) currentCursor = 0 returnValue = None while selfIntro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == KEYDOWN: if event.key == 13: selfIntro = False returnValue = menuPoints[currentCursor][2] elif event.key == 27: pygame.quit() quit() elif event.key == 274: if currentCursor < (len(menuPoints) - 1): currentCursor = currentCursor + 1 elif event.key == 273: if currentCursor > 0: currentCursor = currentCursor - 1 screen.fill(black) count = 0 while count < len(menuPoints): if currentCursor == count: cursor.setPos(menuPoints[count][1].left - 26, menuPoints[count][1].top + 2) count = count + 1 screen.blit(cursor.image, cursor.rectPoint) screen.blit(TextSurfSchnake, TextRectSchnake) screen.blit(TextSurfSchettings, TextRectSchettings) screen.blit(TextSurfSchcoreboard, TextRectSchcoreboard) pygame.display.update() clock.tick(15) if returnValue is not None: return returnValue
def __init__(self, options): self.options = [] font = pygame.font.Font("Fonts/dejavu.ttf", 20) x = 105 y = 305 reference = 1 self.cursor = Cursor.cursor(x - 30, y, 30) for title, function in options: self.options.append( Option.option(font, title, x, y, reference, function)) y += 30 if reference == 1: reference = -1 else: reference = 1 self.select = 0 self.total = len(self.options) self.m_pulse = False
def __init__(self): self.mode = MODE_COMMANDS # Other is MODE_USERPLAY where you are in control of the hero if CURSES: # Initialize curses cbreak() noecho() # Initialize the Kernel Kernel() # Set's up the socket NethackSock() # Socket observers SocketLogger( ) # This should be before other stuff for easier debugging FramebufferParser() DGLParser() # Stuff Console() Cursor() Dungeon() Hero() MonsterSpoiler() ItemDB() Inventory() # AI Personality() Senses() Pathing() # Brains curBrain = TestBrain() Kernel.instance.Personality.setBrain(curBrain) # Default brain
# If the map was loaded successfully, finish setting everything up and run the event. if not battleGraphics is None: # Light the scene battleGraphics.lightScene() # Bind camera controls to keys. camhandler = CameraHandler.CameraHandler() camhandler.accept('escape', lambda: sys.exit()) # Play the background music music = base.loader.loadSfx(GAME + '/music/' + mapJSON['music'] + '.ogg') music.setLoop(True) music.play() # Place highlightable tiles on the map matrix = Matrix(battleGraphics, mapJSON) # Cursor stuff cursor = Cursor(battleGraphics, matrix.container) # Add the special effects battleGraphics.addEffects() try: # Load event. imp.load_source('event', EVENT) # print "" print "" print "Controls: " print "" print " G: Rotate Map Left" print " F: Rotate Map Right" print " H: Ascend/Descend" print " D: Zoom In/Zoom Out" print " ESC: End Test"
def generic(self): logger.info("Generic") lord_units = [ unit for unit in self.allunits if unit.position and 'Lord' in unit.tags and unit.team == 'player' ] lord_position = lord_units[0].position if lord_units else (0, 0) # Certain variables change if this is being initialized at beginning of game, and not a save state self.phase = CustomObjects.Phase(self) self.statedict = { 'previous_cursor_position': lord_position, 'levelIsComplete': False, # Whether the level is complete 'outroScriptDone': False } # Whether the outro script has been played # For hiding menus self.hidden_active = None self.hidden_child = None self.main_menu = None # Combat slots self.combatInstance = None self.levelUpScreen = [] # Banner slots self.banners = [] # Status slots self.status = None # AI slots self.ai_current_unit = None self.ai_unit_list = None self.ai_build_flag = True # Movement manager self.moving_units = set() # Handle cursor if any(unit.team == 'player' and unit.position for unit in self.allunits): # cursor_position = [unit.position for unit in self.allunits if unit.team == 'player' and unit.position][0] cursor_position = lord_position else: cursor_position = (0, 0) self.cursor = Cursor.Cursor('Cursor', cursor_position) self.fake_cursors = [] self.tutorial_mode = False # Handle cameraOffset # Track how much camera has moved in pixels: self.cameraOffset = CustomObjects.CameraOffset(self.cursor.position[0], self.cursor.position[1]) self.cursor.autocursor(self, force=True) # Other slots self.highlight_manager = CustomObjects.HighlightController() self.allarrows = [] self.allanimations = [] # Reset the units updates on load # And have the units arrive on map for unit in self.allunits: unit.resetUpdates() if unit.position: unit.place_on_map(self) unit.arrive(self, serializing=False) self.info_menu_struct = { 'current_state': 0, 'scroll_units': [], 'one_unit_only': False, 'chosen_unit': None }
import pygame, sys, os, media, Zombie, Hero, Cursor from pygame.locals import * FPS = 24 pygame.init() window = pygame.display.set_mode((media.WINDOW_WIDTH, media.WINDOW_HEIGHT), pygame.DOUBLEBUF) pygame.mixer.init(11025) media.prepare() window.blit(media.BACKGROUND, (0,0)) pygame.display.flip() pygame.display.set_caption('ZOMBIE') cursor = Cursor.Cursor() cgroup = pygame.sprite.RenderUpdates() cgroup.add(cursor) zombies = pygame.sprite.RenderUpdates() heroes = pygame.sprite.RenderUpdates() for i in xrange(0,1): heroes.add(Hero.Hero()) for i in xrange(0,6): zombies.add(Zombie.Zombie(heroes)) def update(): cgroup.clear(window, media.BACKGROUND) zombies.clear(window, media.BACKGROUND)
def __init__(self, client, scenario, faction): global _gui _gui = self self.scenario = scenario self.client = client self.faction = faction self.lightEnv = scenario.lightEnvironment() self.setLighting() self.focusedElement = None self.fsm = ScenarioGUIFSM(self) self.m = scenario.map() m = self.m for j in xrange(0, m.height): for i in xrange(0, m.width): self.compileMapSquareList(m.squares[i][j]) self._highlightAlpha = 1.0 self.camera = Camera.Camera() self.lastCameraRotation = None self.sortedMapSquares = [] # FIXME: make a single chatbox object textColor = (64, 0, 0) self.textEntry = Sprite.TextEntry() self.textEntry.setPosn((10, 160)) self.textEntry.setColor(textColor) # FIXME: 0-255 color self.chatBox1 = Sprite.TextDisplayer() self.chatBox1.setPosn((10, 60)) self.chatBox1.setColor(textColor) # FIXME: 0-255 color self.chatBox1.setText("") self.chatBox2 = Sprite.TextDisplayer() self.chatBox2.setPosn((10, 80)) self.chatBox2.setColor(textColor) # FIXME: 0-255 color self.chatBox2.setText("") self.chatBox3 = Sprite.TextDisplayer() self.chatBox3.setPosn((10, 100)) self.chatBox3.setColor(textColor) # FIXME: 0-255 color self.chatBox3.setText("") self.chatBox4 = Sprite.TextDisplayer() self.chatBox4.setPosn((10, 120)) self.chatBox4.setColor(textColor) # FIXME: 0-255 color self.chatBox4.setText("") self.chatBox5 = Sprite.TextDisplayer() self.chatBox5.setPosn((10, 140)) self.chatBox5.setColor(textColor) # FIXME: 0-255 color self.chatBox5.setText("") self.cursor = Cursor.Cursor(m) self.cursorPosnDisplayer = Sprite.CursorPosnDisplayer(self.cursor) self.unitNameDisplayer = Sprite.UnitNameDisplayer(self.cursor) self.unitMovementDisplayer = Sprite.UnitMovementDisplayer(self.cursor) self.unitHPDisplayer = Sprite.UnitHPDisplayer(self.cursor) self.unitSPDisplayer = Sprite.UnitSPDisplayer(self.cursor) self.unitPhysicalDisplayer = Sprite.UnitPhysicalDisplayer(self.cursor) self.unitMagicalDisplayer = Sprite.UnitMagicalDisplayer(self.cursor) self.unitClassDisplayer = Sprite.UnitClassDisplayer(self.cursor) self.unitSpeedDisplayer = Sprite.UnitSpeedDisplayer(self.cursor) tdbWidth = 250 tdbHeight = 8 tdbY = MainWindow.get().size()[1] - tdbHeight * 20 - 30 self.textDisplayerBox = Sprite.TextDisplayerBox([ self.unitNameDisplayer, self.unitClassDisplayer, self.unitHPDisplayer, self.unitSPDisplayer, self.unitMovementDisplayer, self.unitSpeedDisplayer, self.unitPhysicalDisplayer, self.unitMagicalDisplayer, ], (10, tdbY) , tdbWidth) self._battleMenu = Sprite.BattleMenu((290, tdbY)) self._specialMenu = Sprite.SpecialMenu((420, tdbY)) self._centeredTextDisplayer = Sprite.TextDisplayer() self._centeredTextDisplayer.setCenterX(True) self._centeredTextDisplayer.setCenterY(True) self._centeredTextDisplayer.setFont(Resources.font(size=36, bold=True)) self._centeredTextDisplayer.setPosn((MainWindow.get().size()[0]/2, MainWindow.get().size()[1]/2)) self._centeredTextDisplayer.setBorder(True) self._centeredTextDisplayer.setEnabled(False) self._topTextDisplayer = Sprite.TextDisplayer() self._topTextDisplayer.setCenterX(True) self._topTextDisplayer.setCenterY(False) self._topTextDisplayer.setFont(Resources.font(size=16, bold=True)) self._topTextDisplayer.setPosn((MainWindow.get().size()[0]/2, 10)) self._topTextDisplayer.setBorder(True) self._topTextDisplayer.setEnabled(False) self._topTextDisplayerClearer = None self.units = scenario.units() self.battle = scenario.battle() self.unitDisplayers = [] self.unitDisplayersDict = {} for u in self.units: ud = Sprite.UnitDisplayer(u) self.unitDisplayers.append(ud) self.unitDisplayersDict[u] = ud self.highlights = {} self.cursorHighlightAlpha = 0.0 self.highlightEnabled = False self.normalObjects = [self.cursor] self.fgObjects = [self.textEntry, self.chatBox1, self.chatBox2, self.chatBox3, self.chatBox4, self.chatBox5, self.cursorPosnDisplayer, self.textDisplayerBox, self._battleMenu, self._specialMenu, self._centeredTextDisplayer, self._topTextDisplayer] self.gameObjects = [] self.gameObjects.extend(self.normalObjects) self.gameObjects.extend(self.fgObjects) self.gameObjects.extend(self.unitDisplayers) # FIXME: rename/remove these self._unitMoving = None self.unitTarget = None self.originalUnitPosn = None self.lastUnitMove = None self.nextUnitMovePosn = None self.unitMoveZDiff = None Sound.playMusic(scenario.music()) (clearr, clearg, clearb) = self.lightEnv.skyColor() glClearColor(clearr, clearg, clearb, 0.0) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) self.scrollTo((self.m.width/2.0, self.m.height/2.0))
def main(speed, score): print("main") intro = True screen.fill(black) snake = Snake.Snake(snakeImage, 10, 10, 10, 10) seperator = Cursor.Cursor(seperatorImage, 0, 410, 450, 10) pygame.display.flip() direction = (10, 0) foodx = (randint(1, 20) - 1) * 10 foody = (randint(1, 20) - 1) * 10 food = Food.Food(foodImage, foodx, foody, 10, 10) snakeLength = 0 snakeChain = [] gameOver = False while 1: #normal game start screen.fill(black) if snake.rectPoint[0] == food.rectPoint[0] and snake.rectPoint[ 1] == food.rectPoint[1]: food = None snakeChainImage = pygame.image.load('snake.png').convert() snakeChain.append( Snake.Snake(snakeChainImage, snake.rectPoint[0], snake.rectPoint[1], 10, 10)) snakeLength = snakeLength + 1 score = score + 1 if food is None: foodx = (randint(1, 20) - 1) * 10 foody = (randint(1, 20) - 1) * 10 food = Food.Food(foodImage, foodx, foody, 10, 10) food.move(foodx, foody) screen.blit(food.image, food.rectPoint) else: screen.blit(food.image, food.rectPoint) clock.tick(speed) temp = directionKey(direction) if temp is not None: direction = temp count = snakeLength while (count != 0): if count == 1: snakeChain[count - 1].setPos(snake.rectPoint[0], snake.rectPoint[1]) else: snakeChain[count - 1].setPos( snakeChain[count - 2].rectPoint[0], snakeChain[count - 2].rectPoint[1]) screen.blit(snakeChain[count - 1].image, snakeChain[count - 1].rectPoint) count = count - 1 snake.move(direction[0], direction[1]) if snake.rectPoint[0] < 0 or snake.rectPoint[ 0] > 400 or snake.rectPoint[1] < 0 or snake.rectPoint[1] > 400: gameOver = True if selfCollision(snake, snakeChain) == True: gameOver = True screen.blit(snake.image, snake.rectPoint) screen.blit(seperator.image, seperator.rectPoint) scoreUp(score) pygame.display.update() if gameOver == True: dbconnection = DBConnect.DBConnect("localhost", "schnake", "schnake", "schnake").connection dbcursor = dbconnection.cursor() query = ( "SELECT count(*), min(score_value), score_name FROM scoreboard ORDER BY score_value DESC LIMIT 10" ) insert = ( "INSERT INTO scoreboard(score_name, score_value) VALUES('REN', " + score + ")") dbcursor.execute(query) for a in dbcursor: lowestScore = a[1] scoreCount = a[0] if score > lowestScore or scoreCount < 10: largeText = pygame.font.Font('freesansbold.ttf', 30) TextSurfHS, TextRectHS = text_objects("NEW HIGHSCORE", largeText) TextRectHS.centerx = ((width / 2)) TextRectHS.centery = ((200)) screen.blit(TextSurfHS, TextRectHS) pygame.display.update() dbconnection.close() dbcursor.close() else: largeText = pygame.font.Font('freesansbold.ttf', 30) TextSurfGO, TextRectGO = text_objects("Game Over", largeText) TextRectGO.centerx = ((width / 2)) TextRectGO.centery = ((200)) screen.blit(TextSurfGO, TextRectGO) pygame.display.update() enter = False while enter is not True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == KEYDOWN: if event.key == 13: enter = True break
class Client(object): def __init__(self): self.music = base.loader.loadSfx(GAME+'/music/24.ogg') self.music.setLoop(True) self.music.play() self.background = GUI.Background(self.loginScreen) # Display the login window def loginScreen(self): self.loginwindow = GUI.LoginWindow(self.authenticate) def processData(self, datagram): iterator = PyDatagramIterator(datagram) source = datagram.getConnection() callback = iterator.getString() getattr(globals()[callback], 'execute')(self, iterator) # This task process data sent by the server, if any def tskReaderPolling(self, taskdata): if self.cReader.dataAvailable(): datagram=NetDatagram() if self.cReader.getData(datagram): self.processData(datagram) return Task.cont # Setup connection and send the LOGIN datagram with credentials def authenticate(self): login = self.loginwindow.loginEntry.get() password = self.loginwindow.passwordEntry.get() self.cManager = QueuedConnectionManager() self.cListener = QueuedConnectionListener(self.cManager, 0) self.cReader = QueuedConnectionReader(self.cManager, 0) self.cReader.setTcpHeaderSize(4) self.myConnection = self.cManager.openTCPClientConnection(IP, PORT, 5000) if self.myConnection: self.cReader.addConnection(self.myConnection) self.send = Send(self.cManager, self.myConnection) print 'Client listening on', IP, ':', PORT taskMgr.add(self.tskReaderPolling, "Poll the connection reader") self.send.LOGIN_MESSAGE(login, password) else: print 'Can\'t connect to server on', IP, ':', PORT # The battle begins def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME+'/music/'+self.party['map']['music']+'.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME+"/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME+"/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME+"/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME+"/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME+"/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask , 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start() def updateAllSpritesAnimations(self, animation): for i,charid in enumerate(self.matrix.sprites): Sequence( Wait(float(i)/6.0), Func(self.updateSpriteAnimation, charid, animation), ).start() def end(self): taskMgr.remove('characterDirectionTask') for child in render.getChildren(): child.removeNode() self.camhandler.destroy() self.coords.destroy() self.sky.remove() self.background = GUI.Background(self.send.GET_PARTIES) def showMenu(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() canmove = self.party['chars'][charid]['canmove'] canact = self.party['chars'][charid]['canact'] columns = [ { 'x': -25, 'font': GUI.regularfont, 'align': TextNode.ALeft }, ] rows = [ { 'cells': ['Move' ], 'enabled': canmove, 'callback': lambda: self.send.GET_WALKABLES (charid) }, { 'cells': ['Act' ], 'enabled': canact , 'callback': lambda: self.onAttackClicked(charid) }, { 'cells': ['Wait' ], 'enabled': True , 'callback': lambda: self.onWaitClicked (charid) }, { 'cells': ['Status' ], 'enabled': False , 'callback': lambda: self.onWaitClicked (charid) }, { 'cells': ['Auto-Battle' ], 'enabled': False , 'callback': lambda: self.onWaitClicked (charid) }, ] GUI.ScrollableList( 'shadowed', 73, -8, 62.0, 91.0, 16, columns, rows, 5, lambda: self.onCancelClicked(charid), 'Menu' ) def moveCheck(self, charid, orig, origdir, dest): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.MoveCheck( lambda: self.send.MOVE_TO(charid, dest), lambda: self.cancelMove(charid, orig, origdir) ) def cancelMove(self, charid, orig, origdir): self.matrix.sprites[charid].node.setPos(self.battleGraphics.logic2terrain(orig)) self.matrix.sprites[charid].setRealDir(origdir) self.send.UPDATE_PARTY() # Makes a character look at another one def characterLookAt(self, charid, targetid): (x1, y1, z1) = self.matrix.getCharacterCoords(charid) (x2, y2, z2) = self.matrix.getCharacterCoords(targetid) if x1 > x2: self.matrix.sprites[charid].setRealDir(3) if x1 < x2: self.matrix.sprites[charid].setRealDir(1) if y1 > y2: self.matrix.sprites[charid].setRealDir(4) if y1 < y2: self.matrix.sprites[charid].setRealDir(2) # Update the status (animation) of a sprite after something happened def updateSpriteAnimation(self, charid, animation=False): if animation: self.matrix.sprites[charid].animation = animation else: stats = self.party['chars'][charid] if stats['hp'] >= (stats['hpmax']/2): self.matrix.sprites[charid].animation = 'walk' if stats['hp'] < (stats['hpmax']/2): self.matrix.sprites[charid].animation = 'weak' if stats['hp'] <= 0: self.matrix.sprites[charid].animation = 'dead' self.die_snd.play() h = self.camhandler.container.getH() self.matrix.sprites[charid].updateDisplayDir( h, True ) def updateCursorPos(self, pos): self.camhandler.move(self.battleGraphics.logic2terrain(pos)) (x, y, z) = pos tile = self.party['map']['tiles'][x][y][z] self.cursor.move(x, y, z, tile) if self.charbars: self.charbars.hide() if self.party['map']['tiles'][x][y][z].has_key('char'): charid = self.party['map']['tiles'][x][y][z]['char'] char = self.party['chars'][charid] if self.subphase == 'attack': self.charbars = GUI.CharBarsRight(char) else: self.charbars = GUI.CharBarsLeft(char) try: self.coords.update(tile) except: self.coords = GUI.Coords(tile) ### Events # Battle func def setupWalkableTileChooser(self, charid, walkables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'move' self.matrix.setupWalkableZone(charid, walkables) if self.charcard: self.charcard.hide() # Battle func def setupAttackableTileChooser(self, charid, attackables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'attack' self.matrix.setupAttackableZone(charid, attackables) if self.charcard: self.charcard.hide() # Battle func def setupDirectionChooser(self, charid): self.inputs.ignoreAll() self.camhandler.acceptAll() self.at.hide() DirectionChooser(charid, self.matrix.sprites[charid], self.camhandler, self.send.WAIT, self.send.UPDATE_PARTY) # Attack button clicked def onAttackClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 155, 44, 'shadowed', 'Check', 'Specify the target with the cursor.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.send.GET_ATTACKABLES(charid), self.send.UPDATE_PARTY, ) # Wait menu item chosen def onWaitClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 135, 60, 'shadowed', 'Check', 'Specify the direction with\nthe Directional buttons.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.setupDirectionChooser(charid), self.send.UPDATE_PARTY, ) # Cancel menu item chosen def onCancelClicked(self, charid): self.inputs.acceptAll() self.camhandler.acceptAll() if self.charcard: self.charcard.hide() ### Tasks # Updates the displayed direction of a character according to the camera angle def characterDirectionTask(self, task): h = self.camhandler.container.getH() for charid in self.matrix.sprites: self.matrix.sprites[charid].updateDisplayDir( h ); return Task.cont
import TitleState as StartStage import Player import Object import Gun import Monster import Cursor import Item from pico2d import * open_canvas(sync=True) # 믹서 채널 할당 Mix_AllocateChannels(50) # 커서 숨기기 hide_cursor() # 커서 로딩 Cursor.init() # 폰트 로딩 game_framework.font = load_font('resource/pf_arma_five.ttf') # 오브젝트 데이터 로드 with open('resource/player.json', 'r') as f: Player.playerData = json.load(f) with open('resource/monster.json', 'r') as f: Monster.monsterData = json.load(f) with open('resource/teleporter.json', 'r') as f: Object.Teleporter.data = json.load(f) with open('resource/item.json', 'r') as f: Item.itemData = json.load(f) with open('resource/pistol.json', 'r') as f: Gun.pistolData = json.load(f) with open('resource/machine_gun.json', 'r') as f: Gun.machineGunData = json.load(f)
menu_img = "menu.jpg" instructions_img = "instructions.jpg" game_back_img = "Stock.jpg" correct_sound_file = "correct_sound_effect.wav" wrong_sound_file = "wrong_sound_effect.wav" screen = pygame.display.set_mode((1018,516),0,32) pygame.display.set_caption('Purple Hammer') game_back = pygame.image.load(game_back_img).convert() menu = pygame.image.load(menu_img).convert_alpha() instructions = pygame.image.load(instructions_img).convert_alpha() correct_sound = pygame.mixer.Sound(correct_sound_file) wrong_sound = pygame.mixer.Sound(wrong_sound_file) cursor = Cursor() dots = Dots() cursor.move_cursor(menu, screen, 1, cursor.start_pos_1) cursor.NavigateOptions(Dots, menu, screen, instructions) cursor.redraw(dots, screen, game_back, False, "None", True) count = 1 done = False first = True while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit()
def __init__(self, config): super(Window, self).__init__() self.currentPath = '' self._mode = "pan" self.photoList = [] self.pathList = [] self.tabClosed = False self.config = config #Defaults self.windowDefault = dict(self.config['windowDefault'].items()) self.propertiesDefault = dict(self.config['propertiesDefault'].items()) self.canvasDefault = dict(self.config['canvasDefault'].items()) self.chartDefault = dict(self.config['chartDefault'].items()) self.HS = int(self.windowDefault['hs']) self.VS = int(self.windowDefault['vs']) self.energy = int(self.windowDefault['energy']) self.azimuth = int(self.windowDefault['azimuth']) self.scaleBarLength = int(self.windowDefault['scalebarlength']) self.chiRange = int(self.windowDefault['chirange']) self.width = float(self.windowDefault['width']) self.widthSliderScale = int(self.windowDefault['widthsliderscale']) self.radius = int(self.windowDefault['radius']) self.radiusMaximum = int(self.windowDefault['radiusmaximum']) self.radiusSliderScale = int(self.windowDefault['radiussliderscale']) self.tiltAngle = int(self.windowDefault['tiltangle']) self.tiltAngleSliderScale = int( self.windowDefault['tiltanglesliderscale']) #Menu bar self.menu = QtWidgets.QMenuBar() self.menuFile = self.menu.addMenu("File") self.menuPreference = self.menu.addMenu("Preference") self.menu2DMap = self.menu.addMenu("2D Map") self.menuFit = self.menu.addMenu("Fit") self.menuHelp = self.menu.addMenu("Help") self.setMenuBar(self.menu) #File Menu self.openFile = self.menuFile.addAction("Open", self.MenuActions_Open) self.export = self.menuFile.addMenu("Export") self.saveCanvasAsImage = self.export.addAction( "RHEED pattern", self.MenuActions_Save_As_Image) self.saveProfileAsText = self.export.addAction( "Line Profile", self.MenuActions_Save_As_Text) #Preference Menu self.defaultSettings = self.menuPreference.addAction("Default Settings",\ self.MenuActions_Preference_DefaultSettings) #2D Map Menu self.Two_Dimensional_Mapping = self.menu2DMap.addAction("Configuration", \ self.MenuActions_Two_Dimensional_Mapping) self.Three_Dimensional_Graph = self.menu2DMap.addAction("3D Graph", \ self.MenuActions_Three_Dimensional_Graph) #Help Menu self.about = self.menuHelp.addAction("About", self.MenuActions_About) #Center Widget self.image_crop = [ 1200 + self.VS, 2650 + self.VS, 500 + self.HS, 3100 + self.HS ] self.mainSplitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal) self.mainTab = QtWidgets.QTabWidget() self.mainTab.setContentsMargins(0, 0, 0, 0) self.mainTab.setTabsClosable(True) self.controlPanelFrame = QtWidgets.QWidget(self) self.controlPanelGrid = QtWidgets.QGridLayout(self.controlPanelFrame) self.controlPanelGrid.setContentsMargins(0, 0, 0, 0) self.controlPanelSplitter = QtWidgets.QSplitter(QtCore.Qt.Vertical) self.browser = Browser(self) self.controlPanelBottomWidget = QtWidgets.QWidget() self.controlPanelBottomGrid = QtWidgets.QGridLayout( self.controlPanelBottomWidget) self.controlPanelBottomGrid.setContentsMargins(0, 0, 2, 0) self.properties = Properties(self, self.config) self.cursorInfo = Cursor(self) self.profile = ProfileChart.ProfileChart(self.config) self.controlPanelBottomGrid.addWidget(self.properties, 0, 0) self.controlPanelBottomGrid.addWidget(self.cursorInfo, 1, 0) self.controlPanelBottomGrid.addWidget(self.profile, 2, 0) self.controlPanelSplitter.addWidget(self.browser) self.controlPanelSplitter.addWidget(self.controlPanelBottomWidget) self.controlPanelSplitter.setSizes([100, 500]) self.controlPanelSplitter.setStretchFactor(0, 1) self.controlPanelSplitter.setStretchFactor(1, 1) self.controlPanelSplitter.setCollapsible(0, False) self.controlPanelSplitter.setCollapsible(1, False) self.controlPanelGrid.addWidget(self.controlPanelSplitter, 0, 0) self.mainSplitter.addWidget(self.mainTab) self.mainSplitter.addWidget(self.controlPanelFrame) self.mainSplitter.setSizes([800, 400]) self.mainSplitter.setStretchFactor(0, 1) self.mainSplitter.setStretchFactor(1, 1) self.mainSplitter.setCollapsible(0, False) self.mainSplitter.setCollapsible(1, False) #Tool bar self.toolBar = QtWidgets.QToolBar(self) self.toolBar.setFloatable(False) self.toolBar.setMovable(False) self.open = QtWidgets.QAction(QtGui.QIcon("./icons/open.svg"), "open", self) self.saveAs = QtWidgets.QAction(QtGui.QIcon("./icons/save as.svg"), "save as", self) self.zoomIn = QtWidgets.QAction(QtGui.QIcon("./icons/zoom in.svg"), "zoom in (Ctrl + Plus)", self) self.zoomIn.setShortcut(QtGui.QKeySequence.ZoomIn) self.zoomOut = QtWidgets.QAction(QtGui.QIcon("./icons/zoom out.svg"), "zoom out (Ctrl + Minus)", self) self.zoomOut.setShortcut(QtGui.QKeySequence.ZoomOut) self.fitCanvas = QtWidgets.QAction(QtGui.QIcon("./icons/fit.svg"), "fit in view", self) self.line = QtWidgets.QAction(QtGui.QIcon("./icons/line.svg"), "line", self) self.line.setCheckable(True) self.rectangle = QtWidgets.QAction( QtGui.QIcon("./icons/rectangle.svg"), "rectangle", self) self.rectangle.setCheckable(True) self.arc = QtWidgets.QAction(QtGui.QIcon("./icons/arc.svg"), "arc", self) self.arc.setCheckable(True) self.pan = QtWidgets.QAction(QtGui.QIcon("./icons/move.svg"), "pan", self) self.pan.setCheckable(True) self.buttonModeGroup = QtWidgets.QActionGroup(self.toolBar) self.buttonModeGroup.addAction(self.line) self.buttonModeGroup.addAction(self.rectangle) self.buttonModeGroup.addAction(self.arc) self.buttonModeGroup.addAction(self.pan) self.toolBar.addAction(self.open) self.toolBar.addAction(self.saveAs) self.toolBar.addSeparator() self.toolBar.addAction(self.line) self.toolBar.addAction(self.rectangle) self.toolBar.addAction(self.arc) self.toolBar.addAction(self.pan) self.toolBar.addSeparator() self.toolBar.addAction(self.zoomIn) self.toolBar.addAction(self.zoomOut) self.toolBar.addAction(self.fitCanvas) self.addToolBar(self.toolBar) #Status bar self.statusBar = QtWidgets.QStatusBar(self) self.messageLoadingImage = QtWidgets.QLabel("Processing ... ", self) self.messageLoadingImage.setVisible(False) self.progressBar = QtWidgets.QProgressBar(self) self.progressBar.setMaximumHeight(12) self.progressBar.setMaximumWidth(200) self.progressBar.setVisible(False) self.progressBar.setOrientation(QtCore.Qt.Horizontal) self.editPixInfo = QtWidgets.QLabel(self) self.editPixInfo.setAlignment(QtCore.Qt.AlignRight) self.editPixInfo.setMinimumWidth(150) self.statusBar.addWidget(self.messageLoadingImage) self.statusBar.insertPermanentWidget(1, self.progressBar) self.statusBar.addPermanentWidget(self.editPixInfo) self.setStatusBar(self.statusBar) #Main Window Settings self.setCentralWidget(self.mainSplitter) self.mainSplitter.setContentsMargins(2, 2, 0, 0) self.setWindowTitle("PyRHEED") #Main Tab Connections self.mainTab.currentChanged.connect(self.switchTab) self.mainTab.tabCloseRequested.connect(self.closeTab) #Toolbar Connections self.open.triggered.connect( lambda path: self.openImage(path=self.getImgPath())) self.line.triggered.connect( lambda cursormode: self.toggleCanvasMode(cursormode="line")) self.rectangle.triggered.connect( lambda cursormode: self.toggleCanvasMode(cursormode="rectangle")) self.arc.triggered.connect( lambda cursormode: self.toggleCanvasMode(cursormode="arc")) self.pan.triggered.connect( lambda cursormode: self.toggleCanvasMode(cursormode="pan")) #Progress Bar Connections self.progressAdvance.connect(self.progress) self.progressEnd.connect(self.progressReset) self.profile.progressAdvance.connect(self.progress) self.profile.progressEnd.connect(self.progressReset) #Browser Connections self.fileOpened.connect(self.browser.treeUpdate) self.imgCreated.connect(self.profile.setImg) self.browser.fileDoubleClicked.connect(self.openImage) #Parameters Page Connections self.properties.sensitivityEdit.textChanged.connect( self.changeSensitivity) self.properties.energyEdit.textChanged.connect(self.changeEnergy) self.properties.azimuthEdit.textChanged.connect(self.changeAzimuth) self.properties.scaleBarEdit.textChanged.connect(self.changeScaleBar) self.properties.labelButton.clicked.connect(self.labelImage) self.properties.calibrateButton.clicked.connect(self.calibrateImage) #Image Adjust Page Connections self.properties.brightnessSlider.valueChanged.connect( self.changeBrightness) self.properties.blackLevelSlider.valueChanged.connect( self.changeBlackLevel) self.properties.autoWBCheckBox.stateChanged.connect(self.changeAutoWB) self.properties.applyButton2.clicked.connect(self.applyImageAdjusts) self.properties.resetButton2.clicked.connect(self.resetImageAdjusts) #Profile Options Page Connections self.properties.integralHalfWidthSlider.valueChanged.connect( self.changeWidth) self.properties.chiRangeSlider.valueChanged.connect( self.changeChiRange) self.properties.radiusSlider.valueChanged.connect(self.changeRadius) self.properties.tiltAngleSlider.valueChanged.connect( self.changeTiltAngle) self.properties.applyButton3.clicked.connect(self.applyProfileOptions) self.properties.resetButton3.clicked.connect(self.resetProfileOptions) #Cursor Information Connections self.cursorInfo.choosedXYEdit.textChanged.connect(self.editChoosedXY) self.cursorInfo.startXYEdit.textChanged.connect(self.editStartXY) self.cursorInfo.endXYEdit.textChanged.connect(self.editEndXY) self.cursorInfo.widthEdit.textEdited.connect(self.editWidth) #Profile Canvas Connections self.scaleFactorChanged.connect(self.profile.setScaleFactor) self.profile.chartMouseMovement.connect(self.photoMouseMovement) #Refresh Connections self.propertiesRefresh.connect(self.properties.refresh) self.chartRefresh.connect(self.profile.refresh) self.getScaleFactor() self.window_initialized.emit()
def paintGL(self): """ first call requires initialization """ if self.initialized == False: self.initialized = True self.initializeGL() print("initialization done") """ ----------------- """ """ >>> main loop <<< """ """ ----------------- """ # keep track of loop frequency flagStart = time.clock() """ Events management. Keyboard interactions between the user and the software are done here. """ Events.manage() """ Update all entities ID """ ID.setId([ Avatar.virtuMan.limbs, Avatar.virtuMan.muscles, Sensors.virtuSens, Sensors.zoiSens ]) """ Preprocess entities. Store all needed transformations to significantly lower calculation cost when rendering (redundancy otherwise between display buffer, ID buffer and bindings) """ # Preprocess of limbs Definitions.modelMatrix.push() Definitions.modelMatrix.translate(Avatar.virtuMan.position[0], Avatar.virtuMan.position[1], Avatar.virtuMan.position[2]) R = Definitions.vector4D.Quat2Vec( Definitions.vector4D((Avatar.virtuMan.orientation))) Definitions.modelMatrix.rotate(R.o, R.x, R.y, R.z) Avatar.limb = -1 # initialize the recursivity here Sensors.countID = 0 Graphics.SaturationModelMatrix = [] Avatar.stick(Avatar.virtuMan) Definitions.modelMatrix.pop() Avatar.oneMesh(Avatar.virtuMan) Muscles.preprocessMuscle(Avatar.virtuMan) Scene.preprocessScene() """ update camera """ Definitions.viewMatrix.push() Definitions.viewMatrix.translate(0, 0, Events.frontBack_cam) Definitions.viewMatrix.rotate(Events.upDown_cam, 1, 0, 0) Definitions.viewMatrix.rotate(Events.leftRight_cam, 0, 1, 0) if Definitions.lookingAtID != 0: Definitions.viewMatrix.translate(-Definitions.lookingAt[0][0], -Definitions.lookingAt[0][1], -Definitions.lookingAt[0][2]) glUniformMatrix4fv(Shaders.view_loc, 1, GL_FALSE, Definitions.viewMatrix.peek()) Definitions.viewMatrix.pop() """ Draw on the ID buffer. The ID BUFFER is used for the mouse implementation, to know which entity is targeted with the cursor. """ # bind the ID buffer glBindFramebuffer(GL_FRAMEBUFFER, self.idFBO) # clear the ID buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # fill ID buffer glViewport(0, 0, Graphics.display[0], Graphics.display[1]) Graphics.modelView(Graphics.opaque) Limbs.drawBodySurface(Avatar.virtuMan, Graphics.idBuffer, Events.SHOW) Muscles.drawMuscleSurface(Avatar.virtuMan, Graphics.idBuffer, Events.SHOW) Sensors.drawZoi(Graphics.idBuffer) Sensors.drawSensor(Graphics.idBuffer) """ Mouse interaction with ID buffer. Read the value of the ID buffer at mouse position, do some stuff. """ dx = -8 dy = -30 Cursor.mouse = [ QtGui.QCursor().pos().x() + dx, QtGui.QCursor().pos().y() + dy ] Cursor.mouseManage() """ Draw on the display buffer. The display buffer is what the user will see on his screen. """ # bind the display buffer glBindFramebuffer(GL_FRAMEBUFFER, self.displayFBO) # clear the display buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glViewport(0, 0, Graphics.display[0], Graphics.display[1]) # draw scene Graphics.modelView(Graphics.blending) Scene.drawScene() # draw saturation balls Graphics.modelView(Graphics.blending) Saturations.drawSaturationBalls(Avatar.virtuMan) # draw FADE body Graphics.modelView(Graphics.blending) Limbs.drawBodySurface(Avatar.virtuMan, Events.style, Events.FADE) # draw FADE muscles Graphics.modelView(Events.style) Muscles.drawMuscleSurface(Avatar.virtuMan, Events.style, Events.FADE) # draw SHOW body Graphics.modelView(Events.style) Limbs.drawBodySurface(Avatar.virtuMan, Events.style, Events.SHOW) Limbs.drawBodyEdge(Avatar.virtuMan, Events.style) # draw SHOW muscles Graphics.modelView(Events.style) Muscles.drawMuscleSurface(Avatar.virtuMan, Events.style, Events.SHOW) Muscles.drawMuscleEdge(Avatar.virtuMan, Events.style) # draw saturation lines Graphics.modelView(Graphics.opaque) Saturations.drawSaturationLines(Avatar.virtuMan) # draw sensors Graphics.modelView(Graphics.opaque) Sensors.drawLink(Events.style) Sensors.drawZoi(Events.style) Sensors.drawSensor(Events.style)
def onVisibilityCursor(self, visibleFlag): if not visibleFlag and self.__denyHideCursor: return Cursor.forceShowCursor(visibleFlag) entity = BigWorld.player() entity.setFlyMouseInputAllowed(not visibleFlag)
def DebugSwitch(event): # Open or close the debugger window try: # If Debugger window can be destroyed, do so... Cfg.debugger.destroy() Cfg.debugger = None except: # Otherwise create the debugger window... # Create Toplevel window for the debugger Cfg.debugger = Toplevel() Cfg.debugger.title("Reflection Debugger") Cfg.debugger.config(bg="#C0C0C0") Cfg.debugger.bind("<F1>", DebugSwitch) Cfg.debugger.bind("<F2>", quit) userslist = None # Create System Frame systemframe = LabelFrame(Cfg.debugger, text="System") systemframe.pack( side = LEFT, fill = Y ) sfb_invert = Button(systemframe, text="Invert background", command=SysBgInvert) sfb_invert.pack( side = TOP, fill = X ) sfb_deluser = Button(systemframe, text = "Delete users", command = api_init3.destroyUsers) sfb_deluser.pack( side = TOP, fill = X ) sfb_username = Entry(systemframe) sfb_username.pack( side = TOP, fill = X ) sfb_newuser = Button(systemframe, text="New user", command= lambda: User_Control.UserCreate(sfb_username.get())) sfb_newuser.pack( side = TOP, fill = X ) sfb_login = Button(systemframe, text="Log in user", command = lambda: User_Control.UserLogIn(userslist.index(ACTIVE))) sfb_login.pack( side = TOP, fill = X ) sfb_cursoron = Button(systemframe, text="Cursor On", command = Cursor.CursorOn) sfb_cursoron.pack( side = TOP, fill = X ) sfb_cursoroff = Button(systemframe, text="Cursor Off", command = Cursor.CursorOff) sfb_cursoroff.pack( side = TOP, fill = X ) sfb_cursorup = Button(systemframe, text="Cursor Up", command = lambda: Cursor.CursorMove("UP")) sfb_cursorup.pack( side = TOP, fill = X ) sfb_cursordown = Button(systemframe, text="Cursor Down", command = lambda: Cursor.CursorMove("DOWN")) sfb_cursordown.pack( side = TOP, fill = X ) sfb_cursorleft = Button(systemframe, text="Cursor Left", command = lambda: Cursor.CursorMove("LEFT")) sfb_cursorleft.pack( side = TOP, fill = X ) sfb_cursorright = Button(systemframe, text="Cursor Right", command = lambda: Cursor.CursorMove("RIGHT")) sfb_cursorright.pack( side = TOP, fill = X ) sfb_savesettings = Button(systemframe, text="Save Settings", command = User_Control.UserSaveSettings) sfb_savesettings.pack( side = TOP, fill = X ) #sfb_loadsettings = Button(systemframe, text="Load Settings", command = User_Control.UserLogin) #sfb_loadsettings.pack( side = TOP, fill = X ) # Create Users Frame usersframe = LabelFrame(Cfg.debugger, text="Users") usersframe.pack( side = LEFT, fill = Y ) userslist = Listbox(usersframe) userslist.pack(side = TOP) Users_Fill(userslist) # Create Task Controller moveframe = LabelFrame(Cfg.debugger, text="Move app") moveframe.pack( side = LEFT, fill = Y ) # Create place buttons cfb_NW = Button(moveframe, text = "NW" , command = lambda: AppControl.App_Move(app_list[taskbox.index(ACTIVE)],NW)) cfb_NW.grid( row = 0, column = 0 , ipadx=2 ) cfb_W = Button(moveframe, text = "W" , command = lambda: AppControl.App_Move(app_list[taskbox.index(ACTIVE)],W)) cfb_W.grid( row = 1, column = 0 , ipadx=6 ) cfb_SW = Button(moveframe, text = "SW" , command = lambda: AppControl.App_Move(app_list[taskbox.index(ACTIVE)],SW)) cfb_SW.grid( row = 2, column = 0 , ipadx=4 ) cfb_NE = Button(moveframe, text = "NE" , command = lambda: AppControl.App_Move(app_list[taskbox.index(ACTIVE)],NE)) cfb_NE.grid( row = 0, column = 1 , ipadx=4 ) cfb_E = Button(moveframe, text = "E" , command = lambda: AppControl.App_Move(app_list[taskbox.index(ACTIVE)],E)) cfb_E.grid( row = 1, column = 1 , ipadx=9 ) cfb_SE = Button(moveframe, text = "SE" , command = lambda: AppControl.App_Move(app_list[taskbox.index(ACTIVE)],SE)) cfb_SE.grid( row = 2, column = 1 , ipadx=6 ) # Create Task Manager taskframe = LabelFrame(Cfg.debugger, text="Task manager") taskframe.pack( side = LEFT, fill = Y ) # Create new task button tfb_new = Button(taskframe, text="Run...", command = Task_New ) tfb_new.pack( side = TOP, fill = X ) # Create open tasks listbox taskbox = Listbox(taskframe) taskbox.pack(side = TOP) Fill_Manager(taskbox) # Create close task button tfb_close = Button(taskframe, text="Close task", command = lambda: Task_Close(taskbox.index(ACTIVE)) ) tfb_close.pack( side = TOP, fill = X ) # Make sure that the debugger is in the front Cfg.debugger.lift()
def initEnvironment(): global curs initPlayers() initZombies(ZOMBS) curs = Cursor.Cursor()
def main(): State.loadQuater() """ Create list of models """ State.createList() State.updateTemplateList() """ Create Entities """ StickMan.virtuMan = StickMan.characteristics(1.7, (0, 0, 0), StickMan.parts) State.loadModel(StickMan.virtuMan) Saturations.preprocessSaturations(StickMan.virtuMan) State.loadSensors() """ Create a window """ pygame.init() screen = pygame.display.set_mode( Events.display, pygame.DOUBLEBUF | pygame.OPENGL | pygame.OPENGLBLIT | RESIZABLE | NOFRAME) glClearColor(0.0, 0.0, 0.0, 0.0) """ texture for ID buffer """ # create texture plane_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, plane_texture) # texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) # texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, Events.display[0], Events.display[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, None) glBindTexture(GL_TEXTURE_2D, 0) """ render buffer for depth for ID buffer """ # create render buffer rbo = glGenRenderbuffers(1) glBindRenderbuffer(GL_RENDERBUFFER, rbo) glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, Events.display[0], Events.display[1]) glBindRenderbuffer(GL_RENDERBUFFER, 0) """ frame buffer object as ID buffer """ # create frame buffer FBO = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, FBO) # attach texture to frame buffer glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, plane_texture, 0) # attach render buffer to frame buffer glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo) glBindFramebuffer(GL_FRAMEBUFFER, 0) """ Generate the VBOs """ Graphics.VBO_init() """ Create the shaders """ Shaders.shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(Shaders.vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(Shaders.fragment_shader, GL_FRAGMENT_SHADER)) glUseProgram(Shaders.shader) """ Enable position attrib ? """ position = glGetAttribLocation(Shaders.shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(position) """ Initialize some more stuff""" glEnable(GL_TEXTURE_2D) glDepthFunc(GL_LEQUAL) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) """ Shader var. locations """ Shaders.proj_loc = glGetUniformLocation(Shaders.shader, "projection") Shaders.view_loc = glGetUniformLocation(Shaders.shader, "view") Shaders.model_loc = glGetUniformLocation(Shaders.shader, "model") Shaders.setColor_loc = glGetUniformLocation(Shaders.shader, "setColor") Definitions.projectionMatrix.perspectiveProjection( 90, 0.5 * Events.display[0] / Events.display[1], 0.1, 100.0) glUniformMatrix4fv(Shaders.proj_loc, 1, GL_FALSE, Definitions.projectionMatrix.peek()) glUniformMatrix4fv(Shaders.model_loc, 1, GL_FALSE, Definitions.modelMatrix.peek()) """ Initialize UI Window """ #menuWindow.init_window() """ Create Sensors Instances""" for imu in range(0, NB_IMU): IMU.createInstance() for emg in range(0, NB_EMG): EMG.createInstance() """ Initialize Data aquisition """ Data_aquisition.initSerial() #Data_aquisition.initBuffers() Data_aquisition.initPoller() start_calib = True end_init = True t_start_init = 10000 """ >>> main loop <<< """ glViewport(0, 0, Events.display[0], Events.display[1]) while True: # keep track of loop frequency flagStart = time.clock() """ Events management. Most interactions between the user and the software is aknowledged here. """ Events.manage() refreshId() # TODO : only when adding/removing sensors """ Aquire Data from serial port and update values""" Data_aquisition.getData() IMU.updateSensors(end_init) EMG.updateSensors() """ Initiate calibration phase""" if start_calib == True: t_start_init = timer() start_calib = False print("START CALIBRATION") t_init = timer() - t_start_init """ Calibrate EMG during calibration phase""" if t_init < CALIB_TIME: EMG.calibration() """ Terminate calibration phase and set-up EMG data""" if t_init >= CALIB_TIME and end_init == True: print("END CALIBRATION") for imu in IMU.IMUs: imu.get_correct() for emg in EMG.EMGs: emg.updateBoundaries() end_init = False """ Correct coordinate frame and kinematics""" for imu in IMU.IMUs: imu.apply_correct() """ Apply quaternions to the virtual limbs""" armData = [imu.quater for imu in IMU.IMUs if imu.bodyPart == IMU.arm] if armData: Qarm = Definitions.vector4D([ imu.quater for imu in IMU.IMUs if imu.bodyPart == IMU.arm ][0]) #[1,1,0,0] StickMan.virtuMan.parts[StickMan.ARM][StickMan.Data_angle] = [ Qarm.o, Qarm.x, Qarm.y, Qarm.z ] forearmData = [ imu.quater for imu in IMU.IMUs if imu.bodyPart == IMU.forearm ] if forearmData: Qforearm = Definitions.vector4D([ imu.quater for imu in IMU.IMUs if imu.bodyPart == IMU.forearm ][0]) #[1,0,0,0] StickMan.virtuMan.parts[StickMan.FOREARM][StickMan.Data_angle] = [ Qforearm.o, Qforearm.x, Qforearm.y, Qforearm.z ] # handData = [imu.quater for imu in IMU.IMUs if imu.bodyPart == IMU.hand] if handData: Qhand = Definitions.vector4D([ imu.quater for imu in IMU.IMUs if imu.bodyPart == IMU.hand ][0]) StickMan.virtuMan.parts[StickMan.HAND][StickMan.Data_angle] = [ Qhand.o, Qhand.x, Qhand.y, Qhand.z ] """ Preprocess entities. Store all needed transformations to significantly lower calculation cost when rendering (redundancy otherwise between display buffer, ID buffer and bindings) """ Definitions.modelMatrix.translate(-StickMan.lookingAt[0][0], -StickMan.lookingAt[0][1], -StickMan.lookingAt[0][2]) StickMan.part = -1 # initialize the recursivity here Sensors.countID = 0 Graphics.SaturationModelMatrix = [] StickMan.stick( StickMan.virtuMan, (StickMan.virtuMan.x, StickMan.virtuMan.y, StickMan.virtuMan.z)) i = 0 for package in Definitions.packagePreprocess: j = 0 for pack in package: if pack[Definitions.packParent] == "Ground": Definitions.packageIndices[ 0] = Definitions.packageIndices[0] + [ [i, j], ] elif pack[Definitions.packParent] == "Body": Definitions.packageIndices[ 1] = Definitions.packageIndices[1] + [ [i, j], ] elif pack[Definitions.packParent] == "Sensor": Definitions.packageIndices[ 2] = Definitions.packageIndices[2] + [ [i, j], ] elif pack[Definitions.packParent] == "Link": Definitions.packageIndices[ 3] = Definitions.packageIndices[3] + [ [i, j], ] j += 1 i += 1 """ Draw on the ID buffer. The ID BUFFER is used for the mouse implementation, to know which body/sensor/gui part is targeted with the cursor. """ # bind the ID buffer glBindFramebuffer(GL_FRAMEBUFFER, FBO) # clear the ID buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # fill ID buffer Graphics.modelView(Graphics.opaque) StickMan.drawBodySurface(Graphics.idBuffer) Sensors.drawSensor(Graphics.idBuffer) """ Mouse interaction with ID buffer. Read the value of the ID buffer at mouse position, do some stuff. """ Cursor.mouseManage() """ Draw on the display buffer. The display buffer is what the user will see on his screen. """ # bind the display buffer glBindFramebuffer(GL_FRAMEBUFFER, 0) # clear the display buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #draw saturation balls Graphics.modelView(Graphics.blending) Saturations.drawSaturationBalls() # draw body Graphics.modelView(Events.style) StickMan.drawBodySurface(Events.style) StickMan.drawBodyEdge(Events.style) #draw saturation balls Graphics.modelView(Graphics.opaque) Saturations.drawSaturationLines() # draw sensors Graphics.modelView(Graphics.opaque) Sensors.drawSensor(Events.style) Sensors.drawDashed(Events.style) if Events.style != Graphics.idBuffer: """ load matrix in shader """ I = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) Definitions.modelMatrix.push() Definitions.modelMatrix.set(I) Definitions.modelMatrix.translate(0, -0.5, 0) Definitions.modelMatrix.scale(1, 0, 1) glUniformMatrix4fv(Shaders.model_loc, 1, GL_FALSE, Definitions.modelMatrix.peek()) """ choose vbo """ vboId = 0 vboDraw = Graphics.vboEdges """ bind surfaces vbo """ Graphics.indexPositions[vboId][vboDraw].bind() Graphics.vertexPositions[vboId].bind() glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, None) """ send color to shader """ r, g, b, a = [255, 255, 255, 255] color = np.array([r / 255., g / 255., b / 255., a / 255.], dtype=np.float32) glUniform4fv(Shaders.setColor_loc, 1, color) Definitions.modelMatrix.pop() """ draw vbo """ glDrawElements(Graphics.styleIndex[vboId][vboDraw], Graphics.nbIndex[vboId][vboDraw], GL_UNSIGNED_INT, None) # update screen pygame.display.flip() """ empty preprocess package """ i = len(Definitions.packagePreprocess) while i > 0: i -= 1 while len(Definitions.packagePreprocess[i]) > 0: Definitions.packagePreprocess[ i] = Definitions.packagePreprocess[i][:-1] i = len(Definitions.packageIndices) while i > 0: i -= 1 while len(Definitions.packageIndices[i]) > 0: Definitions.packageIndices[i] = Definitions.packageIndices[ i][:-1] pygame.time.wait(15)
import Button import InputBox #initialize pygame pygame.init() #initialize randomizing random.seed() #SETTINGS holes = [(140,150),(410,150),(680,150),(140,277),(410,277),(680,277),(140,394),(410,394),(680,394)] #Sprite directories background = pygame.image.load(os.path.join("data","background.png")) mole = Mole.Mole(os.path.join("data","mole.png")) moleHit = Mole.Mole(os.path.join("data","mole_hit.png")) cursors = pygame.sprite.Group() hammer = Cursor.Cursor(os.path.join("data", "hammer.png")) hammer_hit = Cursor.Cursor(os.path.join("data", "hammer_hit.png")) menuCursor = Cursor.Cursor(os.path.join("data", "cursor.png")) cursors.add(hammer,hammer_hit,menuCursor) startButton = Button.Button(os.path.join("data","start.png")) quitButton = Button.Button(os.path.join("data","quit.png")) highscoresButton = Button.Button(os.path.join("data","highscores_box.png")) livesButton = Button.Button(os.path.join("data","lives_box.png")) ScoreBoxButton = Button.Button(os.path.join("data","your_score_box.png")) #Background gameDisplay = pygame.display.set_mode((800,600)) gameDisplay.blit(background,(0,0)) #Booleans moleDrawn = False isGame = True isStart = False
class Client(object): def __init__(self): self.music = base.loader.loadSfx(GAME + '/music/24.ogg') self.music.setLoop(True) self.music.play() self.background = GUI.Background(self.loginScreen) # Display the login window def loginScreen(self): self.loginwindow = GUI.LoginWindow(self.authenticate) def processData(self, datagram): iterator = PyDatagramIterator(datagram) source = datagram.getConnection() callback = iterator.getString() getattr(globals()[callback], 'execute')(self, iterator) # This task process data sent by the server, if any def tskReaderPolling(self, taskdata): if self.cReader.dataAvailable(): datagram = NetDatagram() if self.cReader.getData(datagram): self.processData(datagram) return Task.cont # Setup connection and send the LOGIN datagram with credentials def authenticate(self): login = self.loginwindow.loginEntry.get() password = self.loginwindow.passwordEntry.get() self.cManager = QueuedConnectionManager() self.cListener = QueuedConnectionListener(self.cManager, 0) self.cReader = QueuedConnectionReader(self.cManager, 0) self.cReader.setTcpHeaderSize(4) self.myConnection = self.cManager.openTCPClientConnection( IP, PORT, 5000) if self.myConnection: self.cReader.addConnection(self.myConnection) self.send = Send(self.cManager, self.myConnection) print 'Client listening on', IP, ':', PORT taskMgr.add(self.tskReaderPolling, "Poll the connection reader") self.send.LOGIN_MESSAGE(login, password) else: print 'Can\'t connect to server on', IP, ':', PORT # The battle begins def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME + '/music/' + self.party['map']['music'] + '.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME + "/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME + "/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME + "/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME + "/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME + "/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask, 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start() def updateAllSpritesAnimations(self, animation): for i, charid in enumerate(self.matrix.sprites): Sequence( Wait(float(i) / 6.0), Func(self.updateSpriteAnimation, charid, animation), ).start() def end(self): taskMgr.remove('characterDirectionTask') for child in render.getChildren(): child.removeNode() self.camhandler.destroy() self.coords.destroy() self.sky.remove() self.background = GUI.Background(self.send.GET_PARTIES) def showMenu(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() canmove = self.party['chars'][charid]['canmove'] canact = self.party['chars'][charid]['canact'] columns = [ { 'x': -25, 'font': GUI.regularfont, 'align': TextNode.ALeft }, ] rows = [ { 'cells': ['Move'], 'enabled': canmove, 'callback': lambda: self.send.GET_WALKABLES(charid) }, { 'cells': ['Act'], 'enabled': canact, 'callback': lambda: self.onAttackClicked(charid) }, { 'cells': ['Wait'], 'enabled': True, 'callback': lambda: self.onWaitClicked(charid) }, { 'cells': ['Status'], 'enabled': False, 'callback': lambda: self.onWaitClicked(charid) }, { 'cells': ['Auto-Battle'], 'enabled': False, 'callback': lambda: self.onWaitClicked(charid) }, ] GUI.ScrollableList('shadowed', 73, -8, 62.0, 91.0, 16, columns, rows, 5, lambda: self.onCancelClicked(charid), 'Menu') def moveCheck(self, charid, orig, origdir, dest): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.MoveCheck(lambda: self.send.MOVE_TO(charid, dest), lambda: self.cancelMove(charid, orig, origdir)) def cancelMove(self, charid, orig, origdir): self.matrix.sprites[charid].node.setPos( self.battleGraphics.logic2terrain(orig)) self.matrix.sprites[charid].setRealDir(origdir) self.send.UPDATE_PARTY() # Makes a character look at another one def characterLookAt(self, charid, targetid): (x1, y1, z1) = self.matrix.getCharacterCoords(charid) (x2, y2, z2) = self.matrix.getCharacterCoords(targetid) if x1 > x2: self.matrix.sprites[charid].setRealDir(3) if x1 < x2: self.matrix.sprites[charid].setRealDir(1) if y1 > y2: self.matrix.sprites[charid].setRealDir(4) if y1 < y2: self.matrix.sprites[charid].setRealDir(2) # Update the status (animation) of a sprite after something happened def updateSpriteAnimation(self, charid, animation=False): if animation: self.matrix.sprites[charid].animation = animation else: stats = self.party['chars'][charid] if stats['hp'] >= (stats['hpmax'] / 2): self.matrix.sprites[charid].animation = 'walk' if stats['hp'] < (stats['hpmax'] / 2): self.matrix.sprites[charid].animation = 'weak' if stats['hp'] <= 0: self.matrix.sprites[charid].animation = 'dead' self.die_snd.play() h = self.camhandler.container.getH() self.matrix.sprites[charid].updateDisplayDir(h, True) def updateCursorPos(self, pos): self.camhandler.move(self.battleGraphics.logic2terrain(pos)) (x, y, z) = pos tile = self.party['map']['tiles'][x][y][z] self.cursor.move(x, y, z, tile) if self.charbars: self.charbars.hide() if self.party['map']['tiles'][x][y][z].has_key('char'): charid = self.party['map']['tiles'][x][y][z]['char'] char = self.party['chars'][charid] if self.subphase == 'attack': self.charbars = GUI.CharBarsRight(char) else: self.charbars = GUI.CharBarsLeft(char) try: self.coords.update(tile) except: self.coords = GUI.Coords(tile) ### Events # Battle func def setupWalkableTileChooser(self, charid, walkables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'move' self.matrix.setupWalkableZone(charid, walkables) if self.charcard: self.charcard.hide() # Battle func def setupAttackableTileChooser(self, charid, attackables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'attack' self.matrix.setupAttackableZone(charid, attackables) if self.charcard: self.charcard.hide() # Battle func def setupDirectionChooser(self, charid): self.inputs.ignoreAll() self.camhandler.acceptAll() self.at.hide() DirectionChooser(charid, self.matrix.sprites[charid], self.camhandler, self.send.WAIT, self.send.UPDATE_PARTY) # Attack button clicked def onAttackClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 155, 44, 'shadowed', 'Check', 'Specify the target with the cursor.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.send.GET_ATTACKABLES(charid), self.send.UPDATE_PARTY, ) # Wait menu item chosen def onWaitClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 135, 60, 'shadowed', 'Check', 'Specify the direction with\nthe Directional buttons.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.setupDirectionChooser(charid), self.send.UPDATE_PARTY, ) # Cancel menu item chosen def onCancelClicked(self, charid): self.inputs.acceptAll() self.camhandler.acceptAll() if self.charcard: self.charcard.hide() ### Tasks # Updates the displayed direction of a character according to the camera angle def characterDirectionTask(self, task): h = self.camhandler.container.getH() for charid in self.matrix.sprites: self.matrix.sprites[charid].updateDisplayDir(h) return Task.cont
pic = imageio.imread(directory) pic2 = imageio.imread(directory2) height = pic.shape[0] width = pic.shape[1] x = np.arange(0,width) if mode == 1: fig = plt.figure() line_row = pic[row,:,0] + pic[row,:,1] + pic[row,:,2] line_row = line_row / np.max(line_row) ax = fig.add_subplot(111) ax.plot(x, line_row) C.FollowDotCursor(ax, x, line_row) ax.set_xlabel('Kép szélesség [pixel]') ax.set_ylabel('Színerősségátlag [relatív egység]') ax.grid() fig.show() elif mode == 2: fig = plt.figure() line_row = pic[row,:,0] + pic[row,:,1] + pic[row,:,2] line_row2 = pic2[row,:,0] + pic2[row,:,1] + pic2[row,:,2] line_row2 = line_row2 / np.max(line_row) line_row = line_row / np.max(line_row) ax = fig.add_subplot(111) ax.plot(x, line_row, label = 'HgCd') ax.plot(x, line_row2, label = 'Na')
def main(): pygame.init() pygame.mixer.init() sonido_01 = PlayAudio("fondo.wav") pantalla = pygame.display.set_mode([900,600]) logo = pygame.image.load("./images/logo.png") pygame.display.set_icon(logo) pygame.display.set_caption("Mas Alla Del Espacio") reloj1 = pygame.time.Clock() fuente1 = pygame.font.SysFont("BadaBoom BB",42,False,False) fuente2 = pygame.font.SysFont("BadaBoom BB",300,False,False) active_on = pygame.image.load("./images/sound_on_active.png") passive_on = pygame.image.load("./images/sound_on_passive.png") active_off = pygame.image.load("./images/sound_off_active.png") passive_off = pygame.image.load("./images/sound_off_passive.png") help_on = pygame.image.load("./images/help_active.png") help_off = pygame.image.load("./images/help_passive.png") back_on = pygame.image.load("./images/back_active.png") back_off = pygame.image.load("./images/back.png") sound_button = Boton(passive_on,active_on,820,30) help = Boton(help_off,help_on,760,30) back = Boton(back_off,back_on,50,520) cursor = Cursor() contador = 0 salir = False iniciar = True advertencia = False primeraVez = True bloqueo_tecla_space = False una_opcion = False audio = None sonido_fondo = True activar_ayuda = False tmp = None global sonido_03 global instruccion global instruccion_sonando fondo = Fondo(1) while salir != True: for event in pygame.event.get(): #Cerrar ventana if event.type == pygame.QUIT: salir = True #Presionar un boton if event.type == pygame.MOUSEBUTTONDOWN: if cursor.colliderect(help.rect): tmp = fondo fondo = Fondo(6) activar_ayuda = True if cursor.colliderect(back.rect): back = Boton(back_off,back_on,50,520) activar_ayuda = False fondo = tmp if cursor.colliderect(sound_button.rect): if sonido_fondo: sound_button = Boton(passive_off,active_off,820,30) sonido_fondo = False sonido_01.stop() else: sound_button = Boton(passive_on,active_on,820,30) sonido_fondo = True sonido_01 = pygame.mixer.Sound("./sounds/fondo.wav") sonido_01.play(-1) #Presionar cualquier tecla if event.type == pygame.KEYDOWN: #Presionar la tecla espacio if event.key == pygame.K_SPACE: back = Boton(back_off,back_on,50,520) activar_ayuda = False if not bloqueo_tecla_space: if not primeraVez: advertencia = True if iniciar: fondo = Fondo(2) pantalla.blit(fondo,(0,0)) pygame.display.update() iniciar = False fondo = Fondo(3) time.sleep(3) sonido_02 = PlayAudio("advertencia.wav") if primeraVez: primeraVez = False if advertencia: sonido_02.stop() fondo = Fondo(4) pantalla.blit(fondo,(0,0)) pygame.display.update() bloqueo_tecla_space = True audio = 1 PlayAudio("pagina01.wav") global audio_disponible audio_disponible = True global instruccion_disponible instruccion_disponible = True global instruccion instruccion = "esfera_01.wav" global instruccion_sonando instruccion_sonando = False #Presionar la tecla 'Up' if event.key == pygame.K_UP: if audio_disponible: RepeatAudio() #Presionar la tecla 'O' if event.key == pygame.K_o: if instruccion_disponible: PlayInstruction(instruccion) instruccion_sonando = True #Presionar la tecla 'Down' if event.key == pygame.K_DOWN: if una_opcion: if audio is not "fin": contador = contador + 1 StopAudios() if audio == 99: una_opcion = False fondo = Fondo(4) PlayAudio("pagina01.wav") instruccion = "esfera_01.wav" audio = 1 if audio == 59: una_opcion = False fondo = Fondo(4) PlayAudio("pagina60.wav") instruccion = "esfera_60.wav" audio = 60 if audio == 67: una_opcion = False fondo = Fondo(4) PlayAudio("pagina02.wav") instruccion = "esfera_02.wav" audio = 2 if audio == 48: una_opcion = False PlayAudio("pagina02.wav") instruccion = "esfera_02.wav" fondo = Fondo(4) audio = 2 if audio == 45: una_opcion = False PlayAudio("pagina62.wav") instruccion = "esfera_62.wav" fondo = Fondo(4) audio = 62 if audio == 43: una_opcion = False PlayAudio("pagina03.wav") instruccion = "esfera_03.wav" fondo = Fondo(4) audio = 3 if audio == 39: una_opcion = False fondo = Fondo(4) PlayAudio("pagina40.wav") instruccion = "esfera_40.wav" audio = 40 if audio == 22: una_opcion = False PlayAudio("pagina03.wav") instruccion = "esfera_03.wav" fondo = Fondo(4) audio = 3 if audio == 16: una_opcion = False fondo = Fondo(4) PlayAudio("pagina17.wav") instruccion = "esfera_17.wav" audio = 17 if audio == 33: una_opcion = False fondo = Fondo(4) PlayAudio("pagina34.wav") instruccion = "esfera_34.wav" audio = 34 #Presionar la tecla 'Left' if event.key == pygame.K_LEFT: if bloqueo_tecla_space: if audio is not "fin": contador = contador + 1 StopAudios() if audio == 82: fondo = Fondo('n') PlayAudio("pagina113.wav") instruccion = "fin.wav" audio = "fin" if audio == 80: fondo = Fondo('n') PlayAudio("pagina111.wav") instruccion = "fin.wav" audio = "fin" if audio == 79: fondo = Fondo('n') PlayAudio("pagina109.wav") instruccion = "fin.wav" audio = "fin" if audio == 91: fondo = Fondo('n') PlayAudio("pagina102.wav") instruccion = "fin.wav" audio = "fin" if audio == 90: fondo = Fondo('n') PlayAudio("pagina101.wav") instruccion = "fin.wav" audio = "fin" if audio == 84: fondo = Fondo('n') PlayAudio("pagina115.wav") instruccion = "fin.wav" audio = "fin" if audio == 60: PlayAudio("pagina80.wav") instruccion = "esfera_80.wav" audio = 80 if audio == 93: fondo = Fondo('n') PlayAudio("pagina107.wav") instruccion = "fin.wav" audio = "fin" if audio == 56: fondo = Fondo('n') PlayAudio("pagina78.wav") instruccion = "fin.wav" audio = "fin" if audio == 55: fondo = Fondo('n') PlayAudio("pagina76.wav") instruccion = "fin.wav" audio = "fin" if audio == 70: fondo = Fondo(5) una_opcion = True PlayAudio("pagina99.wav") instruccion = "abajo.wav" audio = 99 if audio == 69: fondo = Fondo('n') PlayAudio("pagina97.wav") instruccion = "fin.wav" audio = "fin" if audio == 74: fondo = Fondo('n') PlayAudio("pagina92.wav") instruccion = "fin.wav" audio = "fin" if audio == 72: PlayAudio("pagina90.wav") instruccion = "esfera_90.wav" audio = 90 if audio == 64: fondo = Fondo('n') PlayAudio("pagina86.wav") instruccion = "fin.wav" audio = "fin" if audio == 61: fondo = Fondo('n') PlayAudio("pagina83.wav") instruccion = "fin.wav" audio = "fin" if audio == 40: PlayAudio("pagina55.wav") instruccion = "esfera_55.wav" audio = 55 if audio == 52: PlayAudio("pagina69.wav") instruccion = "esfera_69.wav" audio = 69 if audio == 51: fondo = Fondo(5) una_opcion = True PlayAudio("pagina67.wav") instruccion = "esfera_67.wav" audio = 67 if audio == 54: PlayAudio("pagina74.wav") instruccion = "esfera_74.wav" audio = 74 if audio == 53: PlayAudio("pagina72.wav") instruccion = "esfera_72.wav" audio = 72 if audio == 62: fondo = Fondo('n') PlayAudio("fin.wav") instruccion = "fin.wav" audio = "fin" if audio == 44: una_opcion = True fondo = Fondo(5) PlayAudio("pagina59.wav") instruccion = "abajo.wav" audio = 59 if audio == 28: PlayAudio("pagina44.wav") instruccion = "esfera_44.wav" audio = 44 if audio == 42: fondo = Fondo('n') PlayAudio("pagina57.wav") instruccion = "fin.wav" audio = "fin" if audio == 38: PlayAudio("pagina51.wav") instruccion = "esfera_51.wav" audio = 51 if audio == 36: PlayAudio("pagina53.wav") instruccion = "esfera_53.wav" audio = 53 if audio == 27: PlayAudio("pagina42.wav") instruccion = "esfera_42.wav" audio = 42 if audio == 23: una_opcion = True fondo = Fondo(5) PlayAudio("pagina39.wav") instruccion = "abajo.wav" audio = 39 if audio == 20: PlayAudio("pagina36.wav") instruccion = "esfera_36.wav" audio = 36 if audio == 14: PlayAudio("pagina28.wav") instruccion = "esfera_28.wav" audio = 28 if audio == 12: fondo = Fondo('n') PlayAudio("pagina24.wav") instruccion = "fin.wav" audio = "fin" if audio == 11: PlayAudio("pagina23.wav") instruccion = "esfera_23.wav" audio = 23 if audio == 10: PlayAudio("pagina20.wav") instruccion = "esfera_20.wav" audio = 20 if audio == 6: PlayAudio("pagina12.wav") instruccion = "esfera_12.wav" audio = 12 if audio == 4: PlayAudio("pagina10.wav") instruccion = "esfera_10.wav" audio = 10 if audio == 2: PlayAudio("pagina04.wav") instruccion = "esfera_04.wav" audio = 4 if audio == 88: fondo = Fondo('n') PlayAudio("pagina94.wav") instruccion = "fin.wav" audio = "fin" if audio == 65: PlayAudio("pagina88.wav") instruccion = "esfera_88.wav" audio = 88 if audio == 46: PlayAudio("pagina65.wav") instruccion = "esfera_65.wav" audio = 65 if audio == 32: PlayAudio("pagina46.wav") instruccion = "esfera_46.wav" audio = 46 if audio == 34: fondo = Fondo(5) una_opcion = True PlayAudio("pagina48.wav") instruccion = "abajo.wav" audio = 48 if audio == 17: fondo = Fondo(5) una_opcion = True PlayAudio("pagina33.wav") instruccion = "abajo.wav" audio = 33 if audio == 15: fondo = Fondo('n') PlayAudio("pagina30.wav") instruccion = "fin.wav" audio = "fin" if audio == 7: PlayAudio("pagina15.wav") instruccion = "esfera_15.wav" audio = 15 if audio == 8: fondo = Fondo('n') PlayAudio("pagina18.wav") instruccion = "fin.wav" audio = "fin" if audio == 3: PlayAudio("pagina07.wav") instruccion = "esfera_07.wav" audio = 7 if audio == 1: PlayAudio("pagina02.wav") instruccion = "esfera_02.wav" audio = 2 #Presionar la tecla 'Right' if event.key == pygame.K_RIGHT: if bloqueo_tecla_space: if audio is not "fin": contador = contador + 1 StopAudios() if audio == 90: fondo = Fondo('n') PlayAudio("pagina106.wav") instruccion = "fin.wav" audio = "fin" if audio == 91: fondo = Fondo('n') PlayAudio("pagina105.wav") instruccion = "fin.wav" audio = "fin" if audio == 79: fondo = Fondo('n') PlayAudio("pagina110.wav") instruccion = "fin.wav" audio = "fin" if audio == 80: fondo = Fondo('n') PlayAudio("pagina112.wav") instruccion = "fin.wav" audio = "fin" if audio == 82: fondo = Fondo('n') PlayAudio("pagina114.wav") instruccion = "fin.wav" audio = "fin" if audio == 84: fondo = Fondo('n') PlayAudio("pagina116.wav") instruccion = "fin.wav" audio = "fin" if audio == 60: PlayAudio("pagina82.wav") instruccion = "esfera_82.wav" audio = 82 if audio == 56: PlayAudio("pagina79.wav") instruccion = "esfera_79.wav" audio = 79 if audio == 55: fondo = Fondo('n') PlayAudio("pagina77.wav") instruccion = "fin.wav" audio = "fin" if audio == 70: fondo = Fondo('n') PlayAudio("pagina100.wav") instruccion = "fin.wav" audio = "fin" if audio == 69: fondo = Fondo('n') PlayAudio("pagina98.wav") instruccion = "fin.wav" audio = "fin" if audio == 93: fondo = Fondo('n') PlayAudio("pagina108.wav") instruccion = "fin.wav" audio = "fin" if audio == 74: audio = 93 PlayAudio("pagina93.wav") instruccion = "esfera_93.wav" if audio == 72: PlayAudio("pagina91.wav") instruccion = "esfera_91.wav" audio = 91 if audio == 64: fondo = Fondo('n') PlayAudio("pagina87.wav") instruccion = "esfera_87.wav" audio = "fin" if audio == 61: PlayAudio("pagina84.wav") instruccion = "esfera_84.wav" audio = 84 if audio == 40: PlayAudio("pagina56.wav") instruccion = "esfera_56.wav" audio = 56 if audio == 52: PlayAudio("pagina70.wav") instruccion = "esfera_70.wav" audio = 70 if audio == 51: fondo = Fondo('n') PlayAudio("pagina68.wav") instruccion = "fin.wav" audio = "fin" if audio == 54: fondo = Fondo('n') PlayAudio("pagina75.wav") instruccion = "fin.wav" audio = "fin" if audio == 53: fondo = Fondo('n') PlayAudio("pagina73.wav") instruccion = "fin.wav" audio = "fin" if audio == 62: PlayAudio("pagina64.wav") instruccion = "esfera_64.wav" audio = 64 if audio == 44: PlayAudio("pagina61.wav") instruccion = "esfera_61.wav" audio = 61 if audio == 28: fondo = Fondo(5) una_opcion = True PlayAudio("pagina45.wav") instruccion = "abajo.wav" audio = 45 if audio == 42: fondo = Fondo('n') PlayAudio("pagina58.wav") instruccion = "fin.wav" audio = "fin" if audio == 38: PlayAudio("pagina52.wav") instruccion = "esfera_52.wav" audio = 52 if audio == 36: PlayAudio("pagina54.wav") instruccion = "esfera_54.wav" audio = 54 if audio == 27: fondo = Fondo(5) una_opcion = True PlayAudio("pagina43.wav") instruccion = "abajo.wav" audio = 43 if audio == 23: fondo = Fondo('n') PlayAudio("pagina41.wav") instruccion = "esfera_41.wav" audio = 41 if audio == 20: PlayAudio("pagina38.wav") instruccion = "esfera_38.wav" audio = 38 if audio == 14: fondo = Fondo('n') PlayAudio("pagina29.wav") instruccion = "fin.wav" audio = "fin" if audio == 12: PlayAudio("pagina27.wav") instruccion = "esfera_27.wav" audio = 27 if audio == 11: fondo = Fondo('n') PlayAudio("pagina26.wav") instruccion = "fin.wav" audio = "fin" if audio == 10: fondo = Fondo(5) una_opcion = True PlayAudio("pagina22.wav") instruccion = "abajo.wav" audio = 22 if audio == 6: PlayAudio("pagina14.wav") instruccion = "esfera_14.wav" audio = 14 if audio == 4: PlayAudio("pagina11.wav") instruccion = "esfera_11.wav" audio = 11 if audio == 2: PlayAudio("pagina06.wav") instruccion = "esfera_06.wav" audio = 6 if audio == 88: fondo = Fondo('n') PlayAudio("pagina96.wav") instruccion = "fin.wav" audio = "fin" if audio == 65: fondo = Fondo('n') PlayAudio("pagina89.wav") instruccion = "fin.wav" audio = "fin" if audio == 46: fondo = Fondo('n') PlayAudio("pagina66.wav") instruccion = "fin.wav" audio = "fin" if audio == 32: fondo = Fondo('n') PlayAudio("pagina49.wav") instruccion = "fin.wav" audio = "fin" if audio == 34: fondo = Fondo('n') PlayAudio("pagina50.wav") instruccion = "fin.wav" audio = "fin" if audio == 17: fondo = Fondo('n') PlayAudio("pagina35.wav") instruccion = "fin.wav" audio = "fin" if audio == 15: PlayAudio("pagina32.wav") instruccion = "esfera_32.wav" audio = 32 if audio == 7: fondo = Fondo(5) una_opcion = True PlayAudio("pagina16.wav") instruccion = "abajo.wav" audio = 16 if audio == 8: fondo = Fondo('n') PlayAudio("pagina19.wav") instruccion = "fin.wav" audio = "fin" if audio == 3: PlayAudio("pagina08.wav") instruccion = "esfera_08.wav" audio = 8 if audio == 1: PlayAudio("pagina03.wav") instruccion = "esfera_03.wav" audio = 3 reloj1.tick(20) pantalla.blit(fondo,(0,0)) if advertencia and audio is not "fin": texto1 = fuente1.render("Pasos dados:",0,(255,255,255)) texto2 = fuente2.render(str(contador),0,(255,255,255)) if not activar_ayuda: pantalla.blit(texto1,(100,80)) pantalla.blit(texto2,(370,165)) if audio is "fin": texto1 = fuente1.render("Score: " + str(contador) + " pasos dados!",0,(255,255,255)) if not activar_ayuda: pantalla.blit(texto1,(80,530)) cursor.update() sound_button.update(pantalla,cursor) help.update(pantalla,cursor) if activar_ayuda: back.update(pantalla,cursor) pygame.display.update() pygame.quit()