Ejemplo n.º 1
0
 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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
    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()
Ejemplo n.º 4
0
	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)
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
    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
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
 # 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"
Ejemplo n.º 9
0
    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
        }
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
    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))
Ejemplo n.º 12
0
def initEnvironment():
    global curs

    initPlayers()
    initZombies(ZOMBS)
    curs = Cursor.Cursor()
Ejemplo n.º 13
0
    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()
Ejemplo n.º 14
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