Пример #1
0
 def mdx_level(self):
     """
         Return a parser that parse the level part of the MDX query and
         return a level object
         Examples:
             [prod].[all prod].children
             [prod].[all prod].join(...)
     """
     leftSqBr = Literal("[").suppress()
     rightSqBr = Literal("]").suppress()
     dotToken = Literal(".").suppress()
     measuresToken = Literal("measures").suppress()
     scalar = Word(alphanums + alphas8bit.encode("utf-8") + "_" + " " + "-")
     level_filter = leftSqBr + scalar + rightSqBr
     level_function = Keyword("children", caseless=True)
     level_filter.setParseAction(
         lambda s, a, toks: level.level_filter(toks[0]))
     level_function.setParseAction(
         lambda s, a, toks: level.level_function(toks[0]))
     level_item = level_filter | level_function
     level_parse = leftSqBr + scalar + rightSqBr + Optional(
         dotToken + delimitedList(level_item, ".", combine=False))
     level_parse.setParseAction(
         lambda s, a, toks: level.level(toks[0], toks[1:]))
     measure_parse = leftSqBr + measuresToken + rightSqBr + dotToken + leftSqBr + scalar + rightSqBr
     measure_parse.setParseAction(
         lambda s, a, toks: measure.measure(toks[0]))
     lev = measure_parse | level_parse
     return lev
Пример #2
0
 def __init__(self, player):
     self.player = player
     self.level = lv.level()
     self.running = False
     self.clock = pygame.time.Clock()
     self.win_width = 860
     self.win_height = 700
     self.enemy_move_time = 300
     self.enemy_attack_time = 700
     self.running = False
     self.win = None
     self.stat = stats.statistics()
Пример #3
0
    def update(self, elapsedTime):
        self.currentLevel.update(elapsedTime)
        
        if self.currentLevel.pauseGame:
            self.currentLevel.pauseGame = False
            self.systemState.changeState("pauseState")

        if self.currentLevel.gameOver:
            self.systemState.changeState("gameOverState")
            self.currentLevel = level(self.joystickList, self.screenSize, self.actualPath)

        if self.currentLevel.background.endOfStageReached:
            score1 = self.currentLevel.player1.score
            score2 = self.currentLevel.player2.score
            time = self.currentLevel.totalElapsedTime
            self.systemState.changeState("levelEndingState")
            self.systemState.currentState.setParams(time, score1, score2) 
Пример #4
0
    def levelInit(self):
        print 'Level Init'
        # should have some sort of parameter
        self.level = level.level(1, self.width, self.height)

        self.screen.blit(self.level.background, [0,0])
        self.playerSprite.setLocation(self.level.playerStart)

        self.playerSprite.speedMultiplier = 1.0
        self.playerSprite.gravMultiplier = 1.0

        for baddie in self.level.enemies:
            self.enemies.add(baddie)
            self.actorsprites.add(baddie)

        for actor in self.actorsprites:
            actor.velDamp = self.level.velDamp
            actor.accDamp = self.level.accDamp
            actor.grav = self.level.grav
Пример #5
0
 def mdx_level(self):
     """
         Return a parser that parse the level part of the MDX query and
         return a level object
         Examples:
             [prod].[all prod].children
             [prod].[all prod].join(...)
     """
     leftSqBr = Literal("[").suppress()
     rightSqBr = Literal("]").suppress()
     dotToken = Literal(".").suppress()
     measuresToken = Literal("measures").suppress()
     scalar = Word(alphanums+alphas8bit.encode("utf-8") +"_"+" "+"-" )
     level_filter = leftSqBr + scalar + rightSqBr
     level_function = Keyword("children", caseless=True)
     level_filter.setParseAction(lambda s,a,toks: level.level_filter(toks[0]))
     level_function.setParseAction(lambda s,a,toks: level.level_function(toks[0]))
     level_item = level_filter | level_function
     level_parse = leftSqBr + scalar + rightSqBr + Optional(dotToken + delimitedList(level_item, ".", combine=False))
     level_parse.setParseAction(lambda s,a,toks: level.level(toks[0], toks[1:]))
     measure_parse = leftSqBr + measuresToken + rightSqBr + dotToken + leftSqBr + scalar + rightSqBr
     measure_parse.setParseAction(lambda s,a,toks: measure.measure(toks[0]))
     lev = measure_parse | level_parse
     return lev
Пример #6
0
import VRScript
import stupidDungeon, level, random
from gameController import gameController
#import Weapon

CAVE = 3
WIDTH = 32
HEIGHT = 32
DEVELOP = True

random.seed(545657451)
LEVEL = level.level()
dungeon = LEVEL.getFloor(0).dungeon

# Floor
# floor = VRScript.Core.Entity('Floor')
# fbox = VRScript.Resources.Box(VRScript.Math.Vector(HEIGHT*CAVE/2,WIDTH*CAVE/2,CAVE/2),
# VRScript.Math.Point(0,0,CAVE/2))

# floor.attach(VRScript.Core.Renderable('Floor',fbox))
# floor.renderable('').show()

# phys = VRScript.Core.Physical('Floor', fbox)
# phys.setPhysicsProperties(VRScript.Core.PhysicsProperties(0,.1,.1,.1,.2))
# phys.setCollisionType(VRScript.Core.CollisionType.Static)
# floor.attach(phys)

# insert floor
VRScript.Core.Entity('e_ground').attach(
    VRScript.Core.Physical('p_ground', VRScript.Resources.Plane()))
VRScript.Interaction.enableNavigation(False, 0)
Пример #7
0
        if '.' in cmd:
            obj, cmd = cmd.split('.')
        else:
            obj = "player"
        for n in range(num):
            m = getattr(locals()[obj], cmd)
            m()

    def main_loop(self):
        t = Term()
        while True:
            self.board.display()
            if self.player.message:
                for line in self.player.message:
                    print(line)
                # pause for reading a message
                t.getch()
                self.player.message = False
                self.board.display()
            if self.player.go_mode:
                self.player.go()    # continue with go mode..
                continue
            c = ''
            while not c or c[-1].isdigit() or c[-1]=='g':
                c += t.getch().decode("utf-8")
            self.run_cmd(c)


explore = Explore(level.level(Board, Loc))
explore.main_loop()
Пример #8
0
    def level_0(self):

        CLOCK_0 = pygame.time.Clock()

        LEVEL_0_DONE = False

        #x,y,width,height
        plat1 = plat(0,450,310,10)
        plat2 = plat(310,519,155,10)
        #plat3 = plat(300,450,10,80)
        plat5 = plat(460,595,280,10)
        #plat6 = plat(730,595,10,50)
        plat7 = plat(740,645,120,10)
        plat8 = plat(860,680,200,10)
        plat9 = plat(0,0,10,720)

        end1 = end(990,500, 200, 200, 20, 300)
        enndGroup = pygame.sprite.Group()
        enndGroup.add(end1)

        check1 = rrr(0,0)
        checkGroup = pygame.sprite.Group()
        checkGroup.add(check1)

        deathGroup = pygame.sprite.Group()

        text1 = textZone(30, 400, "They push,we run. Where are they pushing me? What do I do now?")
        tGroup = pygame.sprite.Group(text1)

        currentLevel = level.level(["images/Backgrounds/Intro_1.png", "images/Animations/Run/ScarlettRun1.png"],[],[plat1,plat2,plat5,plat7,plat8,plat9],True)


        R_DOWN = False
        L_DOWN = False


        while not LEVEL_0_DONE:


            self.D_SURF.fill((0,0,0,0))

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    quit()

                #Keydown

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = True
                        self.character.right = True

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = True
                        self.character.left = True

                    if event.key == pygame.K_UP:
                        if self.character.onGround == True:
                            self.character.onGround = False
                            self.character.changey = -15

                    if event.key == pygame.K_r:
                        self.character.restart()
                        self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)

                    if event.key == pygame.K_SPACE:
                        if self.character.happy:
                            self.character.happy = False
                            currentLevel.toggleState()
                        elif not self.character.happy:
                            self.character.happy = True
                            currentLevel.toggleState()

                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = False
                        self.character.right = False

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = False
                        self.character.left = False


            if not self.character.right == self.character.left:
                if self.character.right:
                    self.character.changex = 8
                elif self.character.left:
                    self.character.changex = -8
            else:
                self.character.changex = 0

            #ANIMATIONs
            if R_DOWN and not L_DOWN:
                self.character.setAnim('runRight')
                self.character.getAnim().play()

            elif L_DOWN and not R_DOWN:
                self.character.setAnim('runLeft')
                self.character.getAnim().play()


            if R_DOWN == False and L_DOWN == False:
                self.character.setAnim('idle')
                self.character.getAnim().play()




            self.character.bg = currentLevel.currentBackground
            self.character.walls = currentLevel.platGroup
            self.character.end = enndGroup
            self.character.resetgroup = checkGroup
            self.character.textgroup = tGroup
            self.character.deathgroup = deathGroup
            self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)

            if self.character.checkDeath():
                self.character.restart()
                self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)


            #BG
            self.D_SURF.blit(currentLevel.currentBackground,(0,0))
            #Platbox
            #currentLevel.drawPlats(self.D_SURF)

            #Animation Blit
            self.character.getAnim().blit(self.D_SURF, (self.character.rect.x-17,self.character.rect.y))

            #Text Blit
            self.character.text.drawTo(self.D_SURF)

            #end Box
            #enndGroup.draw(self.D_SURF)
            #Collision Box
            #self.D_SURF.blit(self.character.image, (self.character.rect.x, self.character.rect.y))
            ##Ghost on and off
            if self.character.rect.x > self.ghost.trueX:
                ghostright=False
            else:
                ghostright=True
            if self.character.happy is False:

                #self.ghost.location=(randrange(-50,1010),self.ghost.randomY())
                self.ghost.speed=4
                self.ghost.on=True

                if ghostright==True:
                    self.ghost.right.blit(self.D_SURF, self.ghost.rect.topleft)

                else:
                    self.ghost.left.blit(self.D_SURF,self.ghost.rect.topleft)
                    self.ghost.draw(self.D_SURF)


            if self.character.happy is True:
                self.ghost.on=False
                self.ghost.speed=0
                self.ghost.location=(randrange(-50,1010),self.ghost.randomY())
            self.ghost.update()
           # self.character.textgroup.draw(self.D_SURF)
            deathGroup.draw(self.D_SURF)

            print(self.character.resetx, self.character.resety)


            if self.character.level == 1:
                LEVEL_0_DONE = True
                currentLevel.platGroup.empty()





            pygame.display.update()
            CLOCK_0.tick(30)
Пример #9
0
        if '.' in cmd:
            obj, cmd = cmd.split('.')
        else:
            obj = "player"
        for n in range(num):
            m = getattr(locals()[obj], cmd)
            m()

    def main_loop(self):
        t = Term()
        while True:
            self.board.display()
            if self.player.message:
                for line in self.player.message:
                    print(line)
                # pause for reading a message
                t.getch()
                self.player.message = False
                self.board.display()
            if self.player.go_mode:
                self.player.go()  # continue with go mode..
                continue
            c = ''
            while not c or c[-1].isdigit() or c[-1] == 'g':
                c += t.getch().decode("utf-8")
            self.run_cmd(c)


explore = Explore(level.level(Board, Loc))
explore.main_loop()
Пример #10
0
  
## -- -- ## -- -- ## -- -- ## -- -- Initializations -- -- ## -- -- ## -- -- ## -- -- ##
   

##Title of Window
title = "BATTLESNAKES"

dimensions = [800, 600]
        
##Player Attribute Dimensions
spawnPoint = [80, 320]
playerFrame = [60, 80, 100]

window = window.window(dimensions[0], dimensions[1])
menu = menu.menu()
level = level.level(window, player)
player = player.player(spawnPoint[0], spawnPoint[1],playerFrame[1], playerFrame[1])


## -- -- ## -- -- ## -- -- ## -- -- Main loop -- -- ## -- -- ## -- -- ## -- -- ##


##Initialization
pygame.init()
pygame.font.init()

##SFX Start
#Music 
pygame.mixer.music.load('sfx/Pulsar.wav')
pygame.mixer.music.play(-1)
#Sounds
Пример #11
0
    def level_2(self):

        self.character.resetx = 50
        self.character.resety = 100

        CLOCK_2 = pygame.time.Clock()

        LEVEL_2_DONE = False

        plat18 = plat(0, 0, 35, 501)
        plat19 = plat(35, 501, 118, 16)
        plat20 = plat(153, 432, 113, 204)
        plat21 = plat(266, 636, 90, 81)
        plat22 = plat(356, 717, 215, 10)
        plat23 = plat(444, 636, 29, 70)
        plat24 = plat(561, 636, 144, 83)
        plat25 = plat(705, 582, 77, 66)
        plat26 = plat(774, 526, 225, 176)
        plat27 = plat(899, 702, 248, 17)
        plat28 = plat(1146, 636, 125, 66)
        plat29 = plat(1271, 702, 82, 10)
        plat30 = plat(1353, 594, 267, 100)
        plat31 = plat(1890, 299, 29, 171)
        plat32 = plat(1575, 300, 59, 170)
        plat33 = plat(1110, 227, 750, 72)
        plat34 = plat(174, 0, 936, 227)
        plat35 = plat(174, 219, 56, 41)
        plat36 = plat(984, 528, 89, 8)
        plat37 = plat(1002, 537, 53, 164)

        end3 = end(1970, 470, 200, 200, 10, 124)




        checkGroup = pygame.sprite.Group()

        enndGroup = pygame.sprite.Group()
        enndGroup.add(end3)

        deathGroup = pygame.sprite.Group()

        death1 = death(358,709,200,10)
        death2 = death(900,645,150,10)
        death3 = death(1221,640,100,10)

        deathGroup.add(death1,death2,death3)


        currentLevel = level.level(["images/Backgrounds/Level_2_Final.png", "images/Backgrounds/Level_2_Final.png"],[],[plat18,plat19,plat20,plat21,plat22,
                                                                                                                   plat23,plat24,plat25,plat26,plat27,plat28,plat29
                                                                                                                   ,plat30,plat31,plat32,plat33,plat34,plat35,plat36,plat37],True)


        R_DOWN = False
        L_DOWN = False



        while not LEVEL_2_DONE:

            print(self.character.resetx, self.character.resety)

            self.D_SURF.fill((0,0,0,0))




            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    quit()

                #Keydown

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = True
                        self.character.right = True

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = True
                        self.character.left = True

                    if event.key == pygame.K_UP:
                        if self.character.onGround == True:
                            self.character.onGround = False
                            self.character.changey = -15

                    if event.key == pygame.K_r:
                        self.character.restart()
                        self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)

                    if event.key == pygame.K_SPACE:
                        if self.character.happy:
                            self.character.happy = False
                            currentLevel.toggleState()
                        elif not self.character.happy:
                            self.character.happy = True
                            currentLevel.toggleState()

                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = False
                        self.character.right = False

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = False
                        self.character.left = False






            ##NOT ANY OF THIS

            if not self.character.right == self.character.left:
                if self.character.right:
                    self.character.changex = 8
                elif self.character.left:
                    self.character.changex = -8
            else:
                self.character.changex = 0

            if not self.character.level == 0:
                bgw = self.character.bg.get_width()
                bgh = self.character.bg.get_height()
                dz_offset = 200
                if self.character.Wx == 0:
                    xlimitL = 0
                else:
                    xlimitL = dz_offset
                if self.character.Wx >= -self.character.bg.get_width() + self.D_SURF.get_width():
                    xlimitR = self.D_SURF.get_width() - dz_offset - self.character.image.get_width()
                else:
                    xlimitR = self.D_SURF.get_width() - self.character.image.get_width()

                if self.character.Wy >= 0:
                    xlimitU = 0
                else:
                    xlimitU = dz_offset
                if self.character.Wy >= -self.character.bg.get_height() + self.D_SURF.get_height():
                    xlimitD = 525 - 105
                else:
                    xlimitD = 720 - 105


                if self.character.rect.x < xlimitL:
                    self.character.rect.x = xlimitL
                if self.character.rect.x > xlimitR:
                    self.character.rect.x = xlimitR

                if self.character.rect.y < xlimitU:
                    self.character.rect.y = xlimitU
                if self.character.rect.y > xlimitD:
                    self.character.rect.y = xlimitD

                if self.character.rect.y < 0:
                    self.character.rect.y = 0
                if self.character.rect.y > 720 - 105:
                    self.character.rect.y = 720 - 105

                if self.character.rect.x == xlimitR:
                    self.character.rect.x = xlimitR - 1
                    if self.character.changex == 8:
                        self.character.Wx -= 8

                if self.character.rect.x == xlimitL:
                    self.character.rect.x = xlimitL + 1
                    if self.character.changex == -8:
                        self.character.Wx += 8

                if self.character.rect.y == xlimitD:
                    self.character.rect.y = xlimitD - 1
                    self.character.Wy -= self.character.changey

                if self.character.rect.y == xlimitU:
                    self.character.rect.y = xlimitU - 1
                    self.character.Wy -= self.character.changey


                if self.character.Wx <= (-bgw - 960 - 40):
                    self.character.Wx = (-bgw - 960 - 40)
                if self.character.Wx >= 0:
                    self.character.Wx = 0
                if self.character.Wy <= (-bgh - 720 - 105):
                    self.character.Wy = (-bgh - 720 - 105)
                if self.character.Wy >= 0:
                    self.character.Wy = 0

            #ANIMATIONs
            if R_DOWN and not L_DOWN:
                self.character.setAnim('runRight')
                self.character.getAnim().play()

            elif L_DOWN and not R_DOWN:
                self.character.setAnim('runLeft')
                self.character.getAnim().play()


            if R_DOWN == False and L_DOWN == False:
                self.character.setAnim('idle')
                self.character.getAnim().play()


            if self.character.checkDeath():
                self.character.restart()
                self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)


            #PUT IN GROUP FOR TEXT FOR CHARACTERS


            self.character.bg = currentLevel.currentBackground
            self.character.walls = currentLevel.platGroup
            self.character.end = enndGroup
            self.character.resetgroup = checkGroup
            self.character.deathgroup = deathGroup
            self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)


            #BG
            self.D_SURF.blit(currentLevel.currentBackground,(self.character.Wx,self.character.Wy))
            #Platbox
            #currentLevel.drawPlats(self.D_SURF)

            #Animation Blit
            self.character.getAnim().blit(self.D_SURF, (self.character.rect.x-17,self.character.rect.y))

            #Text Blit
            self.character.text.drawTo(self.D_SURF)


            if self.character.rect.x > self.ghost.trueX:
                ghostright=False
            else:
                ghostright=True
            if self.character.happy is False:


                self.ghost.speed=4
                self.ghost.on=True

                if ghostright==True:
                    self.ghost.right.blit(self.D_SURF, self.ghost.rect.topleft)

                else:
                    self.ghost.left.blit(self.D_SURF,self.ghost.rect.topleft)
                    self.ghost.draw(self.D_SURF)


            if self.character.happy is True:
                self.ghost.on=False
                self.ghost.speed=0
                self.ghost.location=(randrange(-50,1010),self.ghost.randomY())
            self.ghost.update()

            if self.character.level == 1:
                self.LEVEL_1_DONE = True


            pygame.display.update()
            CLOCK_2.tick(30)
Пример #12
0
def main():

    global stats_array, count_array, time_array, n_rcvd
    global n_right, sync_status, mode, ch, data_packet_delivery_count
    global n_attempts
    data_packet_delivery_count_previous = 0
    n_rcvd = 0
    n_right = 0
    n_attempts = 5
    threshold = 0.01

    count_array = [ 0, 0, 0, 0, 0]
    time_array = [ 0, 0, 0, 0, 0]
    stats_array = [ 0, 0, 0, 0, 0,0,0,0,0,0,0,0,0,0,0]


    def send_pkt(self, payload='', eof=False):
        return self.txpath.send_pkt(payload, eof)

    def get_freq_rx():

        return 2.44*1e9

    def get_freq_tx():
#        return 8,900e6
        # Convert hop_freq to our unique channel list
        channel = int(random.choice([1,7]))
            

        hop_freq = float(1e6 * (850+(channel-1)*5))#setting the centre freq frequency for sending packets

        
        stats_array[channel] = stats_array[channel] + 1
        print "\nChannel DSA Selection Statistics (Channel #: Number times selected)"
        print "1: ", stats_array[1], " 7: ",stats_array[7]
        return channel,hop_freq #returning the channel number and hop frequency
    

    def rx_callback(ok, payload):
        
        global n_rcvd, n_right,sync_status,mode,ch,data_packet_delivery_count
        ########################## sync ####################################
        if mode == "sync":
            if ok:
                print "SYNC:GOT CHANNEL PACKET"
                (pktno,) = struct.unpack('!H', payload[0:2])
                (sync_signal,) = struct.unpack('!s', payload[2]) 
                (data_channel,) = struct.unpack('!H', payload[3:5])
                                  
                if str(sync_signal) == 'o' and str(data_channel) == str(ch):
                    sync_status = True
                    #tb.stop()
                    print "SYNC:RECEIVE CONFIRM PACKET...LINK ESTABLISHED"                           
                if str(sync_signal) == 's' and str(data_channel) == str(ch): 
                    print "SYNC:SEND CONFIRM PACKET"
                    sync_status = True
                    data = 'o'
                    pktno=0
                    ack_payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
                    send_pkt(tb,ack_payload) #sending back the acknowledgement
        ###################################################################
            
        ######################### traffic #################################
        if mode == "traffic":
            if ok: 
                (data_header,) = struct.unpack('!s', payload[0])
                if data_header == 'd':
		    #print "TRAFFIC:SEND ACK"
                    data_packet_delivery_count = data_packet_delivery_count +1
                    comm = struct.unpack('!14s', payload[1:15])
                    data = 'dI am fine.....' #Sending this message
                    payload = struct.pack('!15s', data)
                    send_pkt(tb,payload)
                
        ##############################################################

        n_rcvd += 1
        if ok:
            n_right += 1

    mods = digital.modulation_utils.type_1_mods()
    demods = digital.modulation_utils.type_1_demods()


    #setting up the tx options parser

    parser_tx = OptionParser(option_class=eng_option, conflict_handler="resolve")
    
    parser_tx.add_option("-m", "--modulation", type="choice", choices=mods.keys(),
            default='gmsk',help="Select modulation from: %s [default=%%default]" 
            % (', '.join(mods.keys()),))
    parser_tx.add_option("-s", "--size", type="eng_float", default=1500,
                      help="set packet size [default=%default]")
    parser_tx.add_option("-M", "--megabytes", type="eng_float", default=1.0,
                      help="set megabytes to transmit [default=%default]")
    parser_tx.add_option("","--discontinuous", action="store_true", default=False,
                      help="enable discontinous transmission (bursts of 5 packets)") 
    parser_tx.add_option("","--from-file", default=None,
                          help="use file for packet contents")

 
    expert_grp_tx = parser_tx.add_option_group("Expert_tx")
    dsa_grp = parser_tx.add_option_group("DSA Options")

        
    dsa_grp.add_option("-T", "--threshold", type="eng_float", default=0.01,
                          help="set primary user sensing energy threshold [default=%default]")
  
    usrp_transmit_path.add_options(parser_tx, expert_grp_tx)
    parser_tx.remove_option('-f');
    #parser_tx.remove_option('--tx-freq');

    for mod in mods.values():
        mod.add_options(expert_grp_tx)


    (options_tx, args_tx) = parser_tx.parse_args ()

    if len(args_tx) != 0:
        parser_tx.print_help()
        sys.exit(1)
    
    ############# Setting some default values for tx side of the block
    options_tx.tx_freq = 900e6
    options_tx.samples_per_symbol =  2
    options_tx.modulation = 'gmsk'
    options_tx.fusb_block_size = 4096
    options_tx.fusb_nblocks = 16
    options_tx.bitrate = 0.0125e6
    #############

    parser_rx = OptionParser (option_class=eng_option, conflict_handler="resolve")
    expert_grp_rx = parser_rx.add_option_group("Expert_rx")
    usrp_receive_path.add_options(parser_rx, expert_grp_rx)
    
    parser_rx.remove_option('-f');
 
    (options_rx, args_rx) = parser_rx.parse_args ()

    ############# Setting some default values for rx side of the block
    options_rx.rx_freq = 2.44e9 #setting default rx_freq value
    options_rx.samples_per_symbol =  2
    options_rx.modulation = 'gmsk'
    options_rx.fusb_block_size = 4096
    options_rx.fusb_nblocks = 16
    options_rx.bitrate = 0.0125e6
    #############


    print "[[ Using the RANDOM channel selection algorithm ]]\n\n"
        
    # build the graph

    tb = my_top_block(mods[options_tx.modulation],
                      demods[options_rx.modulation],
                      rx_callback,options_tx,
                      options_rx)
    r = gr.enable_realtime_scheduling()
    if r != gr.RT_OK:
        print "Warning: failed to enable realtime scheduling"
    
    tb.start()

    #listening to random frequencies untill a match is found
    running = True

    # Scan all channels first for inital data
    #time.sleep(0.1)

    print "\n[[ Scanning channels for network nodes ]]\n"
    timeout = time.time() + timer
    while running:
	if time.time() > timeout:
	    break
        ################################################sync mode####################################
        if mode == "sync":
			if sync_status != True:
                    

                ch,hop_freq = get_freq_tx()
                hop_freq_rx = get_freq_rx()

                tb.txpath.sink.set_freq(hop_freq)
                tb.rxpath.source.set_freq(hop_freq_rx)
                print "RX_FREQ:",hop_freq_rx,"  TX_FREQ:",hop_freq
                ch_energy = level(ch) #check if primary user is present
                #print ch_energy,"*"*30
                if int(ch_energy) > threshold: #if primary user is there then dont transmit on this channel
		    time.sleep(1)
                    continue
                
                nbytes = 5 #int(1e6 * .0003)
                pkt_size = 5
                n = 0
                pktno = 0
                while n < nbytes:
                    if options_tx.from_file is None:
                        data = 's'
                    else:
                        data = source_file.read(pkt_size - 2)
                        if data == '':
                            break;

                    payload = struct.pack('!HsH', pktno & 0xffff,data,ch & 0xffff) #+ data
                            
                    send_pkt(tb,payload)
                    n += len(payload)
                    sys.stderr.write("SEND SYNC PACKET\n")
                    if options_tx.discontinuous and pktno % 5 == 4:
                        time.sleep(1)
                        pktno += 1
                time.sleep(1)
                    
            else:
                print "\n\n[[ Network Node Found: Commencing communications on CHANNEL ", ch, " ]]\n";
                n_attempts_counter = 0
                mode = "traffic"
                data_packet_delivery_count = 0
                sync_status="False"
                start_time = datetime.now() #measuring the time for which the primary user is away
    
        ################################################end of sync mode####################################

        ################################################Communications mode#################################
        if mode == "traffic":
            nbytes = 15
            pkt_size = 15
            data_pktno = 0
            n = 0
            while n < nbytes:
                if options_tx.from_file is None:
                    data = 'dHi how are you' #Sending this message
                else:
                    data = source_file.read(pkt_size - 2)
                    if data == '':
                        break;
    
            
                payload = struct.pack('!15s', data)
                                       
                send_pkt(tb,payload)
                n += len(payload)
                sys.stderr.write("SEND TRAFFIC PACKET\n")
                if options_tx.discontinuous and data_pktno % 5 == 4:
                    time.sleep(1)
                data_pktno += 1
                time.sleep(0.2 + 0.05*int(random.choice([0,1,2,3])))

                if data_packet_delivery_count == data_packet_delivery_count_previous: #checking if the data packet delivery has stagnated
                    n_attempts_counter += 1
                    if n_attempts_counter > n_attempts: #get out of the data channel as it seems that the other node is still trying to rendezvous
                        mode = "sync"
                        continue
		else:
		    data_packet_delivery_count_previous = 0
		    data_packet_delivery_count = 0

		data_packet_delivery_count_previous = data_packet_delivery_count
		ch_energy = level(ch) #check if primary user is present
		print "CHANNEL ENERGY:",ch_energy,"\n"
		if int(ch_energy) > threshold: #if primary user is there then dont transmit on this channel
		    stop_time = datetime.now()    
		    _elapsed_time  = start_time - stop_time
		    print "\n[[ Primary User Detected:  Evacuating Current Channel ]]\n"
		    print "\n[[ Scanning channels for network nodes ]]\n"
		    print "\nAbsent time:",_elapsed_time,"\n"
		    mode = "sync"
Пример #13
0
    ], ['-', '-', '#', '-', 'X', '-', '-', '-', '-', 'X', '-', '#', '-'],
          ['-', '-', '¡', '-', '#', '-', '-', '-', '-', '#', '-', '¡', '-'],
          ['-', '-', '-', '-', '¡', '-', '-', '-', '-', '¡', '-', '-', '-'],
          ['-', '-', '#', '-', '#', '-', '-', '-', '-', '#', '-', '#', '-'],
          ['-', '-', '¡', '-', '-', '-', '-', '-', '-', '-', '-', '¡', '-'],
          ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
          ['-', '-', '-', '-', '¡', '-', '-', '-', '-', '¡', '-', '-', '-']]

    #--------------Create some sprite variables--------------
    allSprites = pygame.sprite.Group()
    enemies = []
    por = []
    chest1 = []
    chest2 = []
    chest3 = []
    level1 = level.level(L1, enemies, chest1, chest2, chest3, por, screen)
    level1.makeLevel()
    element = [
        'projectiles/fireProj.png', 'projectiles/iceProj.png',
        'projectiles/lightProj.png'
    ]
    magic = pygame.sprite.Group()
    obstacles = level1.boxes
    obstacleGroup = pygame.sprite.Group()
    for spr in level1.boxes:
        allSprites.add(spr)
        obstacleGroup.add(spr)
    player = player.player('Character/DownAnim/Down2.png', obstacles,
                           (width / 2, height - 50))
    allSprites.add(player)
    heroGroup = pygame.sprite.Group(player)
Пример #14
0
        xratio = int(sys.argv[3])
    except ValueError:
        xratio = 100
    try:
        yratio = int(sys.argv[4])
    except ValueError:
        yratio = 100
    except IndexError:
        pass
    if (
            xratio == 100 and yratio == 100
    ):  # this may happen if user sets this, not only if user sends erroneous data
        xratio = int(50 + random.random() * 100)  # a number between 50 and 150
        yratio = int(50 + random.random() * 100)  # a number between 50 and 150

    lev = level.level()
    lev.filename = sys.argv[2]
    lev.polys = []
    lev.objs = []
    lev.name = "rsz " + sys.argv[2] + ", x%: " + str(xratio) + " y%: " + str(
        yratio)

    f = open(os.path.join('levels', sys.argv[1]), 'rb')
    f.read(7)
    reclink = 'Reclink: ' + str(struct.unpack('i', f.read(4))[0])
    integrity1 = 'Integrity 1: ' + str(struct.unpack('d', f.read(8))[0])
    integrity2 = 'Integrity 2: ' + str(struct.unpack('d', f.read(8))[0])
    integrity3 = 'Integrity 3: ' + str(struct.unpack('d', f.read(8))[0])
    integrity4 = 'Integrity 4: ' + str(struct.unpack('d', f.read(8))[0])
    levname = 'Level name: "' + str(''.join(struct.unpack('51c',
                                                          f.read(51)))) + '"'
Пример #15
0
L5 = [['-', '-', '-', 'X', 'X', 'X', 'X', 'X', 'X', 'X', '-', '-', '-'],
      ['-', '-', '-', '#', 'X', 'X', 'X', 'X', 'X', '#', '-', '-', '-'],
      ['-', '-', '-', '-', 'X', 'X', 'X', 'X', 'X', '-', '-', '-', '-'],
      ['-', '-', '-', '-', '#', '-', '-', '-', '#', '-', '-', '-', '-'],
      ['-', '-', '-', '-', '-', 'X', 'X', 'X', '-', '-', '-', '-', '-'],
      ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
      ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
      ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']]

#--------------Create some sprite variables--------------
allSprites = pygame.sprite.Group()
enemies = []
bosses = []
bossGroup = pygame.sprite.Group()
level1 = level.level(L1, enemies)
level1.makeLevel()
element = [
    'projectiles/fireProj.png', 'projectiles/iceProj.png',
    'projectiles/lightProj.png'
]
magic = pygame.sprite.Group()
obstacles = level1.boxes
obstacleGroup = pygame.sprite.Group()
for spr in level1.boxes:
    allSprites.add(spr)
    obstacleGroup.add(spr)
player = player.player('Character/DownAnim/Down2.png', obstacles,
                       (width / 2, height - 50))
#allSprites.add(player)   =>  removed to implement flashing invincibility => created by Steven Goodchild
heroGroup = pygame.sprite.Group(player)
 def __init__( self ):
   self._levels  = [ level( )  ] * 9
   self._players = []
   for i in range(4):
     self._players.append(Player( 0, (2000 if i < 2 else 2100, 2000 if i%2==0 else 2100) ) )
   self._screens = [ pygame.Surface((512,512)) ] * 4
Пример #17
0
import VRScript
import stupidDungeon, level, random
from gameController import gameController

# import Weapon

CAVE = 3
WIDTH = 32
HEIGHT = 32
DEVELOP = True

random.seed(545657451)
LEVEL = level.level()
dungeon = LEVEL.getFloor(0).dungeon


# Floor
# floor = VRScript.Core.Entity('Floor')
# fbox = VRScript.Resources.Box(VRScript.Math.Vector(HEIGHT*CAVE/2,WIDTH*CAVE/2,CAVE/2),
# VRScript.Math.Point(0,0,CAVE/2))

# floor.attach(VRScript.Core.Renderable('Floor',fbox))
# floor.renderable('').show()

# phys = VRScript.Core.Physical('Floor', fbox)
# phys.setPhysicsProperties(VRScript.Core.PhysicsProperties(0,.1,.1,.1,.2))
# phys.setCollisionType(VRScript.Core.CollisionType.Static)
# floor.attach(phys)

# insert floor
VRScript.Core.Entity("e_ground").attach(VRScript.Core.Physical("p_ground", VRScript.Resources.Plane()))
Пример #18
0
    def toHtml( self ):
        filename = filedialog.askopenfilename()
        if not filename: return
        path = os.path.dirname(filename)
        os.chdir(path)
        
        out = filedialog.asksaveasfilename()
        #out = f.name + '.txt'
        if not out: return

        try:
            fo = open( out, 'w' )
        except IOError:
            print ( 'Cannot open file ', fo.name, ' for writing: ', sys.exc_info() )
        else:
            lev = level.level()
            lev.filename = out
            print ( 'will write to: ' + out ) 
            lev.polys = []
            lev.objs = []
            

            f = open( filename, 'rb' )
            print ( 'reading ' + filename )
            f.read(7)
            lev.reclink = 'Reclink: ' + str(struct.unpack('i',f.read(4))[0])
            lev.integrity1 = 'Integrity 1: ' + str(struct.unpack('d',f.read(8))[0])
            lev.integrity2 = 'Integrity 2: ' + str(struct.unpack('d',f.read(8))[0])
            lev.integrity3 = 'Integrity 3: ' + str(struct.unpack('d',f.read(8))[0])
            lev.integrity4 = 'Integrity 4: ' + str(struct.unpack('d',f.read(8))[0])
            levname = str(''.join(struct.unpack('51c',f.read(51))))
            lev.lgr = 'LGR: "' + str(''.join(struct.unpack('16c',f.read(16)))) + '"'
            lev.ground = 'Ground: "' + str(''.join(struct.unpack('10c',f.read(10)))) + '"'
            lev.sky = 'Sky: "' + str(''.join(struct.unpack('10c',f.read(10)))) + '"'

            lev.name = "disturbized: " + levname
            polys = int(struct.unpack('d',f.read(8))[0])
            #print ( 'Polygons: ' + str(polys) )
            for p in range(polys):
                #print ( 'Polygon ' + str(p) + ':' )
                if struct.unpack('i',f.read(4))[0] == 1:
                    grass = 1 # grass poly
                else:
                    grass = 0
                #print ( 'Grass: ' + str(grass) )
                vs = int(struct.unpack('i',f.read(4))[0])
                vcs = []
                #print ( 'Verteces: ' + str(vs) )
                for v in range(vs):
                    #print ( 'Vertex ' + str(v) + ':' )
                    vxx = struct.unpack('d',f.read(8))[0]
                    vxy = struct.unpack('d',f.read(8))[0]
                    # if not first vertex, a line can be calculated
                    # only do lines that are not vertical
                    if v and abs(vxx-vxx0) > 0.001 and not grass:
                        # d:\programs\games\eol\lev
                        # haircut 5.0;0.03 makes you look at level high
                        # haircut 50;0.7 wild f-up
                        steps = float( self.step.get() )
                        # maximum 1000 vertices
                        if vs * steps > 999: steps = 999.0/vs
                        disturbized = float( self.disturb.get() )
                        xstep = (vxx-vxx0)/steps
                        k = (vxy-vxy0)/(vxx-vxx0) # k = y1-y2/x1-x2
                        m = vxy - k*vxx# y = kx + m, m = y-kx
                        for step in range(1,int(steps)):
                            x = vxx0+xstep*step
                            y = k*x+m + random.random()*disturbized - random.random()*disturbized
                            vcs.append( x )
                            vcs.append( y )
                    elif not grass:
                        vcs.append( vxx )
                        vcs.append( vxy )
                    vxx0 = vxx
                    vxy0 = vxy
                if not grass: lev.polys.append( vcs )
                    
            obs = int(struct.unpack('d',f.read(8))[0])
            # print ( 'Objects: ' + str(obs) )
            for o in range(obs):
                obj = []
                obj.append( struct.unpack('d',f.read(8))[0] ) #x
                obj.append( struct.unpack('d',f.read(8))[0] ) #y
                obj.append( struct.unpack('i',f.read(4))[0] ) #type
                obj.append( struct.unpack('i',f.read(4))[0] ) #gravity
                obj.append( struct.unpack('i',f.read(4))[0] ) #animation
                lev.objs.append( obj )
            lev.write()
        f.close()
        messagebox.showinfo( 'Success', 'Wrote ' + out + ' successfully!' )
Пример #19
0
from level import level

levels = [level(1, 8, 8, 10), level(2, 16, 16, 40), level(3, 24, 24, 99)]
Пример #20
0
def openLoop(window, mainRenderer):
    global motobugTex, triedArgs
    SDL_RestoreWindow(window)
    SDL_SetWindowResizable(window, SDL_FALSE)
    SDL_SetWindowSize(window, 640, 480)
    SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED,
                          SDL_WINDOWPOS_CENTERED)
    SDL_SetWindowBordered(window, SDL_FALSE)

    inOpenLoop = True
    ft_Mono24 = TTF_OpenFont(b"fonts/RobotoMono-Regular.ttf", 24)
    ft_Mono18 = TTF_OpenFont(b"fonts/RobotoMono-Regular.ttf", 18)

    # pre-render the text
    SDL_SetRenderDrawColor(mainRenderer, 255, 255, 255, 255)

    texts = [
        preRenderTextCenter(mainRenderer, ft_Mono24,
                            "Welcome to Motobug Studio (beta 0.2)!", 320, 20),
        preRenderTextCenter(mainRenderer, ft_Mono18, "New Project", 320, 210),
        preRenderTextCenter(mainRenderer, ft_Mono18, "Load Project", 320, 240),
        preRenderTextCenter(mainRenderer, ft_Mono18, "Quit", 320, 270)
    ]

    mainProject = project()
    tiles = tileSet(mainRenderer, mainProject)
    #tiles.loadTexFromFile("projects/CrystalGeyser/tiles.txt")
    mainProject.levels = [level(mainRenderer, tiles)]
    mainProject.tilesets = [tiles]

    mousex, mousey = 0, 0
    windowdrag = False
    windowdragstart = [0, 0]
    currentTicks = SDL_GetTicks()

    while inOpenLoop:
        currentTicks = SDL_GetTicks()
        event = SDL_Event()
        while (SDL_PollEvent(ctypes.byref(event))):
            if (event.type == SDL_QUIT
                    or (event.type == SDL_KEYUP
                        and event.key.keysym.sym == SDLK_ESCAPE)):
                # close the program
                SDL_DestroyWindow(window)
                SDL_Quit()
                exit()
            if event.type == SDL_MOUSEBUTTONDOWN and event.button.button == SDL_BUTTON_LEFT:
                if mousey > 200 and mousey < 280 and (mousey - 200) % 30 < 20:
                    index = floor((mousey - 200) / 30)
                    if index == 0:
                        success = mainProject.newWithDialog(mainRenderer)
                        if success == 0:
                            inOpenLoop = False
                    elif index == 1:
                        success = mainProject.openWithDialog(mainRenderer)
                        if success == 0:
                            inOpenLoop = False
                    elif index == 2:
                        SDL_DestroyWindow(window)
                        SDL_Quit()
                        exit()
                else:
                    windowdrag = True
                    windowdragstart = [mousex, mousey]
            if event.type == SDL_MOUSEBUTTONUP and event.button.button == SDL_BUTTON_LEFT:
                windowdrag = False
            if event.type == SDL_MOUSEMOTION:
                # record the newest mouse position
                mousex, mousey = event.motion.x, event.motion.y
                if windowdrag:
                    winPosx, winPosy = ctypes.c_int(), ctypes.c_int()
                    SDL_GetWindowPosition(window, winPosx, winPosy)
                    SDL_SetWindowPosition(
                        window, winPosx.value + (mousex - windowdragstart[0]),
                        winPosy.value + (mousey - windowdragstart[1]))

        if mousey > 200 and mousey < 280 and (mousey - 200) % 30 < 20:

            SDL_SetRenderDrawColor(mainRenderer, 255, 255, 255, 100)
            uiRect = SDL_Rect()
            uiRect.x, uiRect.y, uiRect.w, uiRect.h = 0, floor(
                (mousey - 200) / 30) * 30 + 200, 640, 20
            SDL_RenderFillRect(mainRenderer, uiRect)

        if len(argv) > 1 and argv[1].endswith(".mbproj") and not triedArgs:
            success = mainProject.openWithDialog(mainRenderer, argv[1])
            if success == 0:
                inOpenLoop = False
            triedArgs = True

        renderTextCenter(mainRenderer, ft_Mono24,
                         "Welcome to Motobug Studio (beta 0.2)!", 320, 150,
                         texts[0])
        renderTextCenter(mainRenderer, ft_Mono18, "New Project", 320, 210,
                         texts[1])
        renderTextCenter(mainRenderer, ft_Mono18, "Load Project", 320, 240,
                         texts[2])
        renderTextCenter(mainRenderer, ft_Mono18, "Quit", 320, 270, texts[3])

        rt = SDL_Rect()
        rt.x, rt.y, rt.w, rt.h = 320 - 64, 0, 128, 128
        SDL_RenderCopy(mainRenderer, motobugTex, None, rt)

        # draw the renderer to screen, and clear the buffer for the next frame
        SDL_RenderPresent(mainRenderer)

        # set the render color to black for the background
        SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0)
        SDL_RenderClear(mainRenderer)

        # wait 10ms before the next frame
        SDL_Delay(10 - min(9, max(round(SDL_GetTicks() - currentTicks), 0)))

    SDL_SetWindowResizable(window, SDL_TRUE)
    SDL_SetWindowSize(window, 1280, 720)
    SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED,
                          SDL_WINDOWPOS_CENTERED)
    SDL_SetWindowBordered(window, SDL_TRUE)

    editor(window, mainRenderer, mainProject)
Пример #21
0
          ['-', '-', '#', '-', '#', '-', '-', '-', '-', '#','-', '#', '-'],
          ['-', '-', '¡', '1', '-', '-', '-', '-', '-', '-','-', '¡', '-'],
          ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-','-', '-', '-'],
          ['-', '-', '-', '-', '¡', '-', '-', '-', '-', '¡','-', '-', '-']]



    #--------------Create some sprite variables--------------
    allSprites = pygame.sprite.Group()
    enemies = []
    por = []
    chests = []
    chest1 = []
    chest2 = []
    chest3 = []
    level1 = level.level(L1, enemies,chests,por,screen)
    level1.makeLevel()
    element = ['projectiles/fireProj.png', 'projectiles/iceProj.png', 'projectiles/lightProj.png']
    elements = ['red','blue','light']
    magic = pygame.sprite.Group()
    obstacles = level1.boxes
    obstacleGroup = pygame.sprite.Group()
    for spr in level1.boxes:
        allSprites.add(spr)
        obstacleGroup.add(spr)
    player = player.player('Character/DownAnim/Down2.png', obstacles, (width/2, height-50))
    #allSprites.add(player) Removed -- already updates
    heroGroup = pygame.sprite.Group(player)
    for sp in por:
        sp.target = player
        allSprites.add(sp)
Пример #22
0
def main():

    esize = 16
    lvl = level("level0.lvl", esize)

    l = glob.glob("data/*.lvl")
    lvl_anz = len(l)

    try:
        pygame.mixer.init()
        music = pygame.mixer.Sound(os.path.join("data", "music.ogg"))
    except:
        print "No Sound avaiable"
    pygame.init()
    screen = pygame.display.set_mode((lvl.esize * len(lvl.lvl[0]), lvl.esize * len(lvl.lvl)))

    img = image(str(esize))

    try:
        music.play(1)
    except:
        pass

    pygame.key.set_repeat(80, 50)
    for i in range(lvl_anz):
        play = player()
        lvl = level("level" + str(i) + ".lvl", esize)
        objects = []
        screen = pygame.display.set_mode((lvl.esize * len(lvl.lvl[0]), lvl.esize * len(lvl.lvl)))
        for y in range(len(lvl.lvl)):
            objects.append([])
            for x in range(len(lvl.lvl[0])):
                o = GameObject(img[lvl.lvl[y][x]], x * lvl.esize, y * lvl.esize, screen)
                objects[y].append(o)
                if lvl.lvl[y][x] == "S":
                    pl = GameObject(img["player"], x * lvl.esize, y * lvl.esize, screen)

        btime = time.time()

        while not play.finish:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        txt = "Closing ..."
                        centered_txt(screen, lvl, txt, 50)
                        music.fadeout(2100)
                        time.sleep(2)
                        return
                    if event.key == pygame.K_DOWN:
                        pl.move(0, 1, lvl, img, objects, play)
                    if event.key == pygame.K_UP:
                        pl.move(0, -1, lvl, img, objects, play)
                    if event.key == pygame.K_RIGHT:
                        pl.move(1, 0, lvl, img, objects, play)
                    if event.key == pygame.K_LEFT:
                        pl.move(-1, 0, lvl, img, objects, play)
                    if event.key == pygame.K_n:
                        pass
                        play.finish = 1

            for j in range(len(objects)):
                for o in objects[j]:
                    o.draw()
                pl.draw()
            time.sleep(0.08)
            pygame.display.update()

        dtime = time.time() - btime
        sav = save("User")
        sav.write(play.points, pl.moves, dtime)
        print "Ziel erreicht:", play.points, "gesammelt"
        print "Moves:", pl.moves
        print dtime

        won = 1

        try:
            if lvl.conf["moves"] > 0:
                if pl.moves < lvl.conf["moves"]:
                    print "moves OK"
                else:
                    print "too many steps"
                    won = 0
        except:
            print "Maximal moves not given"

        try:
            if lvl.conf["time"] > 0:
                if dtime < lvl.conf["time"]:
                    print "time OK"
                else:
                    print "too slow"
                    won = 0
        except:
            print "Maximal time not given"

        try:
            if lvl.conf["points"] > 0:
                if play.points > lvl.conf["points"]:
                    print "points OK"
                else:
                    print "not enought points"
                    won = 0
        except:
            print "Minimal points not given"

        if won == 1:
            print "You finished this level"

        if i < lvl_anz - 1:
            txt = "Next level ..."
            centered_txt(screen, lvl, txt, 50)
            time.sleep(1)

    txt = "Finished ..."
    centered_txt(screen, lvl, txt, 50)
    music.fadeout(2100)
    time.sleep(2)
Пример #23
0
def levelgen(screen,layout,title,sub_title,conditions,L):
    ### RoomS Design
    L2 = layout
    bulletLoops = 0
    skip = 0
    bossBulletTarget = [player]
        #--------------Create some sprite variables--------------
    allSprites = pygame.sprite.Group()
    enemies = []
    gems = []
    chests = []
    chest1 = []
    chest2 = []
    chest3 = []
    hp = player.health
    por = []
    levelgen = level.level(L2, enemies,chests,por,screen)
    levelgen.makeLevel()
    element = ['projectiles/fireProj.png', 'projectiles/iceProj.png', 'projectiles/lightProj.png']
    magic = pygame.sprite.Group()
    obstacles = levelgen.boxes
    obstacleGroup = pygame.sprite.Group()
    for spr in levelgen.boxes:
        allSprites.add(spr)
        obstacleGroup.add(spr)
        player.obstacles.append(spr)
    #allSprites.add(player) Removed -- already updates
    heroGroup = pygame.sprite.Group(player)
    for chest in chests:
        if (chest.type != 'red' and chest.type != 'blue'):
            chest.target = player
        if (chest.type=='portal'):
            chest1.append(chest)
        if (chest.type=='item'):
            chest2.append(chest)
        if (chest.type=='dmg'):
            chest3.append(chest)
        if (chest.type=='red'):
            gems.append(chest)
        if (chest.type=='blue'):
            gems.append(chest)
        allSprites.add(chest)
    for sp in por:
        sp.target = player
        allSprites.add(sp)
    for enemy in enemies:
        enemy.target = player
        enemy.enemies = enemies #For them to check collision with one another.
        allSprites.add(enemy)
    exitGroup = pygame.sprite.Group(por)
    chest1Group = pygame.sprite.Group(chest1)
    chest2Group = pygame.sprite.Group(chest2)
    chest3Group = pygame.sprite.Group(chest3)
    enemyGroup = pygame.sprite.Group(enemies)
    gemsGroup = pygame.sprite.Group(gems)

    tabCount = 0
    chosenElement = element[0]      #defualt to fire
    gemtype = 'red'
    ### Room Loop
    while not levelgen.isComplete(exitGroup):
        pygame.event.pump()
        xCounter = yCounter = 0
        for event in pygame.event.get():    #event handler, checks for key presses (not holds)
            if levelgen.isComplete(heroGroup):
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_TAB:
                        lifeAfterdeath()

            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.K_0:
                skip = 1
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_TAB:
                    tabCount+=1
                    if tabCount >= len(element):
                        tabCount = 0
                    gemtype = elements[tabCount]
                    chosenElement = element[tabCount]
                elif event.key == pygame.K_SPACE and player.alive():
                    allSprites.add(projectiles.projectiles(player, chosenElement, enemies,chests, player.rect.center,gemtype))
                    magic.add(projectiles.projectiles(player, chosenElement, enemies,chests, player.rect.center,gemtype))
        screen.fill((0,0,0))                #reset screen, for clean animation
        background.makeBackground(screen, img, wallDown, sFloor, floor, tFloor, cFloor)
        if skip == 1:
            for sp in por:
                sp.target = player
                sp.rect.center = (300,350)
                allSprites.add(sp)
                sp.kill()
        ### Exit Portal
        if conditions == 'chest':
            if levelgen.isComplete(chest1Group):
                for sp in por:
                    sp.target = player
                    sp.rect.center = (300,350)
                    allSprites.add(sp)
                    myfont = pygame.font.SysFont('Comic Sans MS', 50)
                    textsurface = myfont.render('Exit has appeared!', False, (255, 255, 255))
                    screen.blit(textsurface,(150,50))

        if conditions == 'kill-all':
            if levelgen.isComplete(enemyGroup):
                for sp in por:
                    sp.target = player
                    if (L==9):
                        sp.rect.center = (150,400)
                        allSprites.add(sp)
                        myfont = pygame.font.SysFont('Comic Sans MS', 25)
                        textsurface = myfont.render('C Ya!', False, (255, 255, 255))
                        screen.blit(textsurface,(30,400))
                    elif (L==5):
                        sp.rect.center = (150,350)
                        allSprites.add(sp)
                        myfont = pygame.font.SysFont('Comic Sans MS', 25)
                        textsurface = myfont.render('Did you order an exit?', False, (255, 255, 255))
                        screen.blit(textsurface,(30,300))
                    elif (L==3):
                        sp.rect.center = (200,350)
                        allSprites.add(sp)
                        myfont = pygame.font.SysFont('Comic Sans MS', 25)
                        textsurface = myfont.render('Not an exit', False, (255, 255, 255))
                        screen.blit(textsurface,(50,400))
                    else :
                        sp.rect.center = (300,350)
                        allSprites.add(sp)
                        myfont = pygame.font.SysFont('Comic Sans MS', 50)
                        textsurface = myfont.render('Exit has appeared!', False, (255, 255, 255))
                        screen.blit(textsurface,(100,300))

        if conditions == 'gems':
            if levelgen.isComplete(gemsGroup):
                for sp in por:
                    sp.target = player
                    sp.rect.center = (300,350)
                    allSprites.add(sp)
                    myfont = pygame.font.SysFont('Comic Sans MS', 50)
                    textsurface = myfont.render('The gods have been honored', False, (255, 255, 255))
                    screen.blit(textsurface,(100,300))
        for enemy in enemies:
            if hasattr(enemy, "boss_health"):
                if enemy.boss_health > 0:
                    bar = pygame.draw.rect(screen, (255, 0, 0), (220, 440, enemy.boss_health*10, 15))
                    if enemy.isType == "Orc":
                        if bulletLoops % 80 == 0:
                            allSprites.add(projectiles.projectiles(enemy, 'projectiles/boss_bullet.png', bossBulletTarget,chests, enemy.rect.center,'orc'))
                            enemy.direction = 'up'
                            allSprites.add(projectiles.projectiles(enemy, 'projectiles/boss_bullet.png', bossBulletTarget,chests, enemy.rect.center,'orc'))
                            enemy.direction = 'left'
                            allSprites.add(projectiles.projectiles(enemy, 'projectiles/boss_bullet.png', bossBulletTarget,chests, enemy.rect.center,'orc'))
                            enemy.direction = 'right'
                            allSprites.add(projectiles.projectiles(enemy, 'projectiles/boss_bullet.png', bossBulletTarget,chests, enemy.rect.center,'orc'))
                            enemy.direction = 'down'
                            bulletLoops = 0
                    elif enemy.isType == "Tenta":
                        if bulletLoops % 40 == 0:
                            enemy.direction = 'right'
                            allSprites.add(projectiles.projectiles(enemy, 'projectiles/flame_projectile.png', bossBulletTarget, chests, enemy.rect.center, 'orc'))
                            enemy.direction = 'left'
                            allSprites.add(projectiles.projectiles(enemy, 'projectiles/flame_projectile.png', bossBulletTarget, chests, enemy.rect.center, 'orc'))
                            enemy.direction = 'right'
                    elif enemy.isType == "Cat_Staff":
                        cloop = 0
                        if bulletLoops % 180 == 0:
                            enemy.currentAnim = enemy.catThrow
                        if enemy.currentAnim == enemy.catThrow:
                            enemy.catloop += 1
                            if enemy.catloop % 24 == 0:
                                enemy.direction = "targeting"
                                allSprites.add(projectiles.projectiles(enemy, 'projectiles/cat_projectile.png', bossBulletTarget, chests, enemy.rect.center, 'cat_staff'))
                            if enemy.catloop % 48 == 0:
                                enemy.currentAnim = enemy.catIdle
                                enemy.catloop = 0
                else:
                    bar = ""
        ### On-Screen Text
        if levelgen.isComplete(heroGroup):
            myfont = pygame.font.SysFont('Comic Sans MS', 25)
            textsurface = myfont.render('Dead already?! Press TAB to continue...', False, (255, 255, 255))
            screen.blit(textsurface,(100,400))

        if conditions == 'chest' and levelgen.isComplete(chest3Group):
            myfont = pygame.font.SysFont('Comic Sans MS', 20)
            textsurface = myfont.render('Radiation Effects : -2 HP', False, (255, 255, 255))
            screen.blit(textsurface,(50,30))
        if conditions != 'gems' and L != 5 and levelgen.isComplete(chest2Group):
            myfont = pygame.font.SysFont('Comic Sans MS', 20)
            textsurface = myfont.render('Health Bonus : +1 HP', False, (255, 255, 255))
            screen.blit(textsurface,(50,40))
        myfont = pygame.font.SysFont('Comic Sans MS', 50)
        for x in range(0,player.health):
            screen.blit(heart, (0+(16*x), 0)) #Display HP.
        screen.blit(pygame.image.load(element[tabCount]).convert(), (0,16)) #Display element.
        #Now service player after everything else.
        player.update(pygame.key.get_pressed()) #Update player
        if (player.health>0 and player.invinc%2==0):
            screen.blit(player.image, player.rect) #Draw them if necessary
        myfont = pygame.font.SysFont('Comic Sans MS', 35)
        textsurface = myfont.render(title, False, (255, 255, 255))
        screen.blit(textsurface,(425,0))
        myfont = pygame.font.SysFont('Comic Sans MS', 25)
        textsurface = myfont.render(sub_title, False, (255, 255, 255))
        screen.blit(textsurface,(405,25))

        for spr in levelgen.boxes:
            threading.Timer(0.1 , spr.torchup).start()

        ### Loop Stuff
        allSprites.update(pygame.key.get_pressed())
        allSprites.draw(screen)
        pygame.display.flip()   #ACTUALLY display all the images
        bulletLoops = bulletLoops + 1
        clock.tick(60)      #all animation and timing is based on this 60fps counter
    for x in obstacleGroup.sprites():
        x.kill()
        x.rect.center = (-55,-55) #Put self out-of-bounds -- but not (-5,-5)
Пример #24
0
def level2(screen):
    ### RoomS Design
    L2 = [[
        '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-',
        '-', '!'
    ], ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
          ['-', '-', '-', '$', '-', '-', '*', '-', '-', '%', '-', '-', '-'],
          ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
          ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
          ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
          ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
          ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']]

    #--------------Create some sprite variables--------------
    allSprites2 = pygame.sprite.Group()
    enemies = []
    chest1 = []
    chest2 = []
    chest3 = []
    hp = player.health
    por = []
    level2 = level.level(L2, enemies, chest1, chest2, chest3, por, screen)
    level2.makeLevel()
    element = [
        'projectiles/fireProj.png', 'projectiles/iceProj.png',
        'projectiles/lightProj.png'
    ]
    magic = pygame.sprite.Group()
    obstacles = level2.boxes
    obstacleGroup = pygame.sprite.Group()
    for spr in level2.boxes:
        allSprites2.add(spr)
        obstacleGroup.add(spr)
    allSprites2.add(player)
    heroGroup = pygame.sprite.Group(player)
    for chest in chest1:
        chest.target = player
        allSprites2.add(chest)
    for chest in chest2:
        chest.target = player
        allSprites2.add(chest)
    for chest in chest3:
        chest.target = player
        allSprites2.add(chest)
    for sp in por:
        sp.target = player
        allSprites2.add(sp)
    for enemy in enemies:
        enemy.target = player
        allSprites2.add(enemy)
    exitGroup = pygame.sprite.Group(por)
    chest1Group = pygame.sprite.Group(chest1)
    chest2Group = pygame.sprite.Group(chest2)
    chest3Group = pygame.sprite.Group(chest3)

    tabCount = 0
    chosenElement = element[0]  #defualt to fire

    ### Room Loop
    while not level2.isComplete(exitGroup):

        pygame.event.pump()
        xCounter = yCounter = 0
        for event in pygame.event.get(
        ):  #event handler, checks for key presses (not holds)
            if event.type == pygame.QUIT:
                exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_TAB:
                    tabCount += 1
                    if tabCount >= len(element):
                        tabCount = 0
                    chosenElement = element[tabCount]
                    print(tabCount)
                elif event.key == pygame.K_SPACE and player.alive():
                    allSprites2.add(
                        projectiles.projectiles(player, chosenElement, enemies,
                                                player.rect.center))
                    magic.add(
                        projectiles.projectiles(player, chosenElement, enemies,
                                                player.rect.center))
        screen.fill((0, 0, 0))  #reset screen, for clean animation
        background.makeBackground(screen, img, wallDown, sFloor, floor, tFloor,
                                  cFloor)
        ### Exit Portal
        if level2.isComplete(chest1Group):
            for sp in por:
                sp.target = player
                sp.rect.center = (300, 350)
                allSprites2.add(sp)
                textsurface = myfont.render('"Exit has appeared!"', False,
                                            (255, 255, 255))
                screen.blit(textsurface, (100, 300))

        ### On-Screen Text
        if level2.isComplete(heroGroup):
            myfont = pygame.font.SysFont('Comic Sans MS', 50)
            textsurface = myfont.render('"Mr.Stark I dont feel so good..."',
                                        False, (255, 255, 255))
            screen.blit(textsurface, (100, 400))
        if level2.isComplete(chest3Group):
            myfont = pygame.font.SysFont('Comic Sans MS', 20)
            textsurface = myfont.render('Radiation Effects : -2 HP', False,
                                        (255, 255, 255))
            screen.blit(textsurface, (50, 30))
        if level2.isComplete(chest2Group):
            myfont = pygame.font.SysFont('Comic Sans MS', 20)
            textsurface = myfont.render('Health Bonus : +1 HP', False,
                                        (255, 255, 255))
            screen.blit(textsurface, (50, 40))
        myfont = pygame.font.SysFont('Comic Sans MS', 50)
        hp = player.health
        textsurface = myfont.render('Health: %d' % (hp), False,
                                    (255, 255, 255))
        screen.blit(textsurface, (0, 0))
        myfont = pygame.font.SysFont('Comic Sans MS', 35)
        textsurface = myfont.render('Level 1 - Room 2', False, (255, 255, 255))
        screen.blit(textsurface, (425, 0))
        myfont = pygame.font.SysFont('Comic Sans MS', 25)
        textsurface = myfont.render('Get some hair on your chest', False,
                                    (255, 255, 255))
        screen.blit(textsurface, (405, 25))

        ### Loop Stuff
        allSprites2.update(pygame.key.get_pressed())
        allSprites2.draw(screen)
        pygame.display.flip()  #ACTUALLY display all the images
        clock.tick(
            60)  #all animation and timing is based on this 60fps counter
Пример #25
0
    def update(self, elapsedTime):

        self.joystickButtonManager(0)
        self.joystickButtonManager(1)
        
        # Parametros de iteracion
        playerInNode = self.playerInNode()
        temporalXDirection = 0
        temporalYDirection = 0
        
        # Botones de eleccion
        if len(self.joystickList) == 2:
            levelSelectionButton = self.joystickList[1].get_button(0) or self.joystickList[0].get_button(0)
            goBackButton = self.joystickList[1].get_button(1) or self.joystickList[0].get_button(1)
        else:
            levelSelectionButton = self.joystickList[0].get_button(0)
            goBackButton = self.joystickList[0].get_button(1)

        if self.playerPos == self.gameNodesList[0]:
            actualPath = "levels//level11.txt"
            self.stageName = "Level 1"
        if self.playerPos == self.gameNodesList[1]:
            actualPath = "levels//level21.txt"
            self.stageName = "Level 2"
        if self.playerPos == self.gameNodesList[2]:
            actualPath = "levels//level31.txt"
            self.stageName = "Level 3"
        if self.playerPos == self.gameNodesList[3]:
            actualPath = "levels//level41.txt"
            self.stageName = "Level 4"
        if self.playerPos == self.gameNodesList[4]:
            actualPath = "levels//level51.txt"
            self.stageName = "Level 5"
        if self.playerPos == self.gameNodesList[5]:  
            actualPath = "levels//level61.txt"
            self.stageName = "Level 6"

        if self.buttonPressed and not self.moving:
            self.selectSound.play()
            self.changeState("playState")
            pygame.mixer.music.stop()
            pygame.mixer.music.load('sounds//mainTheme.mp3')
            pygame.mixer.music.play(2)
            
            self.systemState.currentState.currentLevel = level(self.joystickList,  self.screenSize, actualPath, self.container)
            self.systemState.currentState.actualPath = actualPath

        elif self.button2Pressed:
            self.goBackSound.play()
            self.changeState("titleState")

        # Obtiene si player apreto boton para desplazarse
        if abs(self.joystickList[0].get_axis(0)) > 0.3 and not self.moving and playerInNode:##
            temporalXDirection = self.joystickList[0].get_axis(0)##
        elif abs(self.joystickList[0].get_axis(1)) > 0.3 and not self.moving and playerInNode:##
            temporalYDirection = self.joystickList[0].get_axis(1)##

        # Se encarga de los desplazamientos
        if temporalXDirection > 0 and self.playerPos[0] != self.gameNodesList[2][0]:
            self.startMoving(self.playerPos, (self.playerPos[0] + 300, self.playerPos[1]))
        elif temporalXDirection < 0 and self.playerPos[0] != self.gameNodesList[0][0]:
            self.startMoving(self.playerPos, (self.playerPos[0] - 300, self.playerPos[1] + 1))

        if temporalYDirection < 0 and self.playerPos[1] != self.gameNodesList[0][1]:
            self.startMoving(self.playerPos, (self.playerPos[0], self.playerPos[1] - 200))
        elif temporalYDirection > 0 and self.playerPos[1] != self.gameNodesList[5][1]:
            self.startMoving(self.playerPos, (self.playerPos[0], self.playerPos[1] + 200))

        # Si se esta moviendo de un nodo a otro
        if self.moving:
            self.updateMovement()
Пример #26
0
    def playCurrentLevel(self,i_level):



        if i_level == 0:

            self.LEVEL_0_DONE = False
            print("0")

            #x,y,width,height
            plat1 = plat(0,450,310,10)
            plat2 = plat(310,519,155,10)
            #plat3 = plat(300,450,10,80)
            plat5 = plat(460,595,280,10)
            #plat6 = plat(730,595,10,50)
            plat7 = plat(740,645,120,10)
            plat8 = plat(860,680,200,10)
            plat9 = plat(0,0,10,720)

            end1 = end(990,500, 200,200, 20, 300)
            enndGroup = pygame.sprite.Group()
            enndGroup.add(end1)

            check1 = rrr(0,0)
            checkGroup = pygame.sprite.Group()
            checkGroup.add(check1)
            self.currentLevel = level.level(["images/Backgrounds/Intro_1.png", "images/Animations/Run/ScarlettRun1.png"],[],[plat1,plat2,plat5,plat7,plat8,plat9],True)
            self.currentLevel = self.currentLevel

        R_DOWN = False
        L_DOWN = False


        while not self.LEVEL_0_DONE:

            #self.D_SURF.fill((0,0,0,0))

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    quit()

                #Keydown

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = True
                        self.character.right = True

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = True
                        self.character.left = True

                    if event.key == pygame.K_UP:
                        if self.character.onGround == True:
                            self.character.onGround = False
                            self.character.changey = -15

                    if event.key == pygame.K_r:
                        self.character.restart()
                        self.spritemove(self.currentLevel.platGroup,checkGroup,enndGroup,self.currentLevel.platGroup,self.currentLevel.platGroup)

                    if event.key == pygame.K_SPACE:
                        if self.character.happy:
                            self.character.happy = False
                            self.currentLevel.toggleState()
                        elif not self.character.happy:
                            self.character.happy = True
                            self.currentLevel.toggleState()

                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = False
                        self.character.right = False

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = False
                        self.character.left = False


            if not self.character.right == self.character.left:
                if self.character.right:
                    self.character.changex = 8
                elif self.character.left:
                    self.character.changex = -8
            else:
                self.character.changex = 0

            #ANIMATIONs
            if R_DOWN and not L_DOWN:
                self.character.setAnim('runRight')
                self.character.getAnim().play()

            elif L_DOWN and not R_DOWN:
                self.character.setAnim('runLeft')
                self.character.getAnim().play()


            if R_DOWN == False and L_DOWN == False:
                self.character.setAnim('idle')
                self.character.getAnim().play()




            self.character.bg = self.currentLevel.currentBackground
            self.character.walls = self.currentLevel.platGroup
            self.character.end = enndGroup
            self.character.resetgroup = checkGroup
            self.spritemove(self.currentLevel.platGroup,checkGroup,enndGroup,self.currentLevel.platGroup,self.currentLevel.platGroup)


            #BG
            self.D_SURF.blit(self.currentLevel.currentBackground,(0,0))
            #Platbox
            #self.currentLevel.drawPlats(self.D_SURF)

            #Animation Blit
            self.character.getAnim().blit(self.D_SURF, (self.character.rect.x-17,self.character.rect.y))

            #end Box
            #enndGroup.draw(self.D_SURF)
            #Collision Box
            #self.D_SURF.blit(self.character.image, (self.character.rect.x, self.character.rect.y))


            pygame.display.update()
            self.CLOCK.tick(30)
Пример #27
0
    def level_1(self):



        CLOCK_1 = pygame.time.Clock()

        LEVEL_1_DONE = False

        plat01 = plat(0, 57, 1020, 30)
        plat02 = plat(0, 309, 324, 99)
        plat03 = plat(324, 408, 253, 94)
        plat04 = plat(577, 502, 130, 776)
        plat05 = plat(707, 1278, 1052, 566)
        plat06 = plat(1860, 1278, 471, 103)
        plat07 = plat(2395, 1312, 47, 67)
        plat08 = plat(2526, 1312, 47, 64)
        plat09 = plat(2646, 1312, 47, 127)
        plat10 = plat(2782, 997, 48, 442)
        plat11 = plat(2310, 945, 472, 52)
        plat12 = plat(2263, 945, 50, 133)
        plat13 = plat(1020, 87, 1093, 995)

        plat14 = plat(708, 606, 93, 49)
        plat15 = plat(708, 883, 93, 49)
        plat16 = plat(926, 1028, 93, 49)
        plat17 = plat(926, 719, 93, 49)

        end2 = end(2694, 1398, 100, 100, 87, 41)

        checkGroup = pygame.sprite.Group()

        enndGroup = pygame.sprite.Group()
        enndGroup.add(end2)

        death1 = death(1760,1356,100,10)
        death2 = death(2331,1393,300,10)
        deathGroup = pygame.sprite.Group()
        deathGroup.add(death1,death2)


        currentLevel = level.level(["images/Backgrounds/Level_1-2 FINAL.png", "images/Backgrounds/Level_1-2 FINAL.png"],[],[plat01,plat02,plat03,plat04,plat05,
                                                                                                                   plat06,plat07,plat08,plat09,plat10,plat11,plat12
                                                                                                                   ,plat13,plat14,plat15,plat16,plat17],True)


        R_DOWN = False
        L_DOWN = False



        while not LEVEL_1_DONE:



            print(self.character.resetx, self.character.resety)

            print(self.character.level)

            self.D_SURF.fill((0,0,0,0))


            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    quit()

                #Keydown

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = True
                        self.character.right = True

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = True
                        self.character.left = True

                    if event.key == pygame.K_UP:
                        if self.character.onGround == True:
                            self.character.onGround = False
                            self.character.changey = -15

                    if event.key == pygame.K_r:
                        self.character.restart()
                        self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)

                    if event.key == pygame.K_SPACE:
                        if self.character.happy:
                            self.character.happy = False
                            currentLevel.toggleState()
                        elif not self.character.happy:
                            self.character.happy = True
                            currentLevel.toggleState()

                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_RIGHT:
                        R_DOWN = False
                        self.character.right = False

                    elif event.key == pygame.K_LEFT:
                        L_DOWN = False
                        self.character.left = False






            ##NOT ANY OF THIS

            if not self.character.right == self.character.left:
                if self.character.right:
                    self.character.changex = 8
                elif self.character.left:
                    self.character.changex = -8
            else:
                self.character.changex = 0

            if not self.character.level == 0:
                bgw = self.character.bg.get_width()
                bgh = self.character.bg.get_height()
                dz_offset = 200
                if self.character.Wx == 0:
                    xlimitL = 0
                else:
                    xlimitL = dz_offset
                if self.character.Wx >= -self.character.bg.get_width() + self.D_SURF.get_width():
                    xlimitR = self.D_SURF.get_width() - dz_offset - self.character.image.get_width()
                else:
                    xlimitR = self.D_SURF.get_width() - self.character.image.get_width()

                if self.character.Wy >= 0:
                    xlimitU = 0
                else:
                    xlimitU = dz_offset
                if self.character.Wy >= -self.character.bg.get_height() + self.D_SURF.get_height():
                    xlimitD = 525 - 105
                else:
                    xlimitD = 720 - 105


                if self.character.rect.x < xlimitL:
                    self.character.rect.x = xlimitL
                if self.character.rect.x > xlimitR:
                    self.character.rect.x = xlimitR

                if self.character.rect.y < xlimitU:
                    self.character.rect.y = xlimitU
                if self.character.rect.y > xlimitD:
                    self.character.rect.y = xlimitD

                if self.character.rect.y < 0:
                    self.character.rect.y = 0
                if self.character.rect.y > 720 - 105:
                    self.character.rect.y = 720 - 105

                if self.character.rect.x == xlimitR:
                    self.character.rect.x = xlimitR - 1
                    if self.character.changex == 8:
                        self.character.Wx -= 8

                if self.character.rect.x == xlimitL:
                    self.character.rect.x = xlimitL + 1
                    if self.character.changex == -8:
                        self.character.Wx += 8

                if self.character.rect.y == xlimitD:
                    self.character.rect.y = xlimitD - 1
                    self.character.Wy -= self.character.changey

                if self.character.rect.y == xlimitU:
                    self.character.rect.y = xlimitU - 1
                    self.character.Wy -= self.character.changey


                if self.character.Wx <= (-bgw - 960 - 40):
                    self.character.Wx = (-bgw - 960 - 40)
                if self.character.Wx >= 0:
                    self.character.Wx = 0
                if self.character.Wy <= (-bgh - 720 - 105):
                    self.character.Wy = (-bgh - 720 - 105)
                if self.character.Wy >= 0:
                    self.character.Wy = 0

            #ANIMATIONs
            if R_DOWN and not L_DOWN:
                self.character.setAnim('runRight')
                self.character.getAnim().play()

            elif L_DOWN and not R_DOWN:
                self.character.setAnim('runLeft')
                self.character.getAnim().play()


            if R_DOWN == False and L_DOWN == False:
                self.character.setAnim('idle')
                self.character.getAnim().play()




            if self.character.checkDeath():
                self.character.restart()
                self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)


            #PUT IN GROUP FOR TEXT FOR CHARACTERS
            self.character.bg = currentLevel.currentBackground
            self.character.walls = currentLevel.platGroup
            self.character.end = enndGroup
            self.character.resetgroup = checkGroup
            self.character.deathgroup = deathGroup
            self.spritemove(currentLevel.platGroup,checkGroup,enndGroup,currentLevel.platGroup,currentLevel.platGroup,deathGroup)


            #BG
            self.D_SURF.blit(currentLevel.currentBackground,(self.character.Wx,self.character.Wy))
            #Platbox
            #currentLevel.drawPlats(self.D_SURF)

            #Animation Blit
            self.character.getAnim().blit(self.D_SURF, (self.character.rect.x-17,self.character.rect.y))

            #Text Blit
            self.character.text.drawTo(self.D_SURF)


            if self.character.rect.x > self.ghost.trueX:
                ghostright=False
            else:
                ghostright=True
            if self.character.happy is False:


                self.ghost.speed=4
                self.ghost.on=True

                if ghostright==True:
                    self.ghost.right.blit(self.D_SURF, self.ghost.rect.topleft)

                else:
                    self.ghost.left.blit(self.D_SURF,self.ghost.rect.topleft)
                    self.ghost.draw(self.D_SURF)


            if self.character.happy is True:
                self.ghost.on=False
                self.ghost.speed=0
                self.ghost.location=(randrange(-50,1010),self.ghost.randomY())
            self.ghost.update()

            if self.character.level == 2:
                LEVEL_1_DONE = True



            pygame.display.update()
            CLOCK_1.tick(30)