Пример #1
0
class GameLoop:
    """Game Loop."""
    def __init__(self):
        self.things = Items()
        self.character = MacGyver()
        self.draw = Display()

    def game_loop(self):
        """Launch the game loop and check the victory conditions"""
        start = True
        while start:
            time.Clock().tick(30)
            self.draw.maze_create()
            self.things.items_create(self.draw.maze)
            while self.character.win is False and self.character.lose is False:
                self.draw.update_display(self.things, self.character)
                self.character.mg_move(self.draw, self.things)
                if len(self.things.backpack) <= 3:
                    self.things.items_colleted(self.character)
            if self.character.lose is True:
                self.draw.gameover()
                self.draw = Display()
                self.character = MacGyver()
                self.things = Items()
            else:
                exit()
Пример #2
0
    def __init__(self, hash_lang):
        style = (wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.SIMPLE_BORDER)
        super().__init__(None, title='TMH database builder', size=(300, 54), style=style)
        self.panel = wx.Panel(self)
        self.SetTransparent(220)
        self.SetBackgroundColour("black")
        self.hash_lang = hash_lang

        self.previous_item_hash = None
        self.items = Items(self.hash_lang)
        # self.item = pandas.DataFrame()
        # self.item_state = "No item"
        self.item_hash = ""

        self.current_item_position = 0
        self.items_names_len = len(self.items.items_names)

        self.name_text = wx.StaticText(self.panel, label="")
        self.hash_text = wx.StaticText(self.panel, label="")

        self.init_ui()

        self.thread_is_on = False
        self.set_update_frame(True)
        self.Show(True)
Пример #3
0
def read_db_for_items():
    '''Read show_db SQLite database and populate item list'''
    try:

        db = sqlite3.connect('data/show_db.db')
        cur = db.cursor()
        cur.execute("PRAGMA foreign_keys=ON")

        # Fetch some data, using the cursor. This returns another cursor object
        # that can be iterated over
        for row in cur.execute('select * from items'):
            #ui.message(row)
            update_ind = g.BLANK
            item = Items(row[1], row[2], row[3], update_ind)
            item.set_id(row[0])
            g.items_list.append(item)

        # ui.message('************* Items **************')
        # ui.message(g.items_list)
        # ui.message('')

    except sqlite3.Error as e:
        # As we are reading, no changes to roll back
        print('Error reading from database', e)
        logging.error('Database error {}'.format(e))
        traceback.print_exc()

    finally:
        db.close()
Пример #4
0
 def generateItems(self):
     self.itemsContainer.append(
         Items(name="item1",
               id_item=1,
               value=20,
               description="item top",
               status="available"))
     self.itemsContainer.append(
         Items(name="item2",
               id_item=2,
               value=50,
               description="item fera",
               status="available"))
     self.itemsContainer.append(
         Items(name="item3",
               id_item=3,
               value=990,
               description="item caro",
               status="available"))
     self.itemsContainer.append(
         Items(name="item4",
               id_item=4,
               value=110.5,
               description="item show",
               status="available"))
Пример #5
0
def create_object(ch, x, y):
    if ch in ['1', '2', '3', '4']:
        obj = Items(ord(ch) - ord('1'), x, y)
        gfw.world.add(gfw.layer.item, obj)
        # print('creating Jelly', x, y)
    elif ch in ['5', '6', '7', '8']:
        obj = Items(ord(ch) - ord('1'), x, y)
        gfw.world.add(gfw.layer.item, obj)
    elif ch == '9':
        obj = Items(ord(ch) - ord('1'), x, y)
        gfw.world.add(gfw.layer.item, obj)
    elif ch in ['O', 'P', 'Q']:
        dy = 1 if ch == 'Q' else 3.8
        y -= int(dy * BLOCK_SIZE) // 2
        x -= BLOCK_SIZE // 2
        obj = floor.Platform(ord(ch) - ord('O'), x, y)
        gfw.world.add(gfw.layer.platform, obj)
        # print('creating Platform', x, y)
    else:
        ao = factory.create(ch, x, y)
        if ao is None:
            global ignore_char_map
            if ch not in ignore_char_map:
                print("Error? I don't know about: '%s'" % ch)
                ignore_char_map |= {ch}
            return
        gfw.world.add(gfw.layer.enemy, ao)
Пример #6
0
def modify_items_record(item_index, item_id):
    print('Your record to modify is:')
    print(g.items_list[item_index])

    while True:
        clear()
        itemtype = input('Enter the type of item (e.g. print, painting, sculpture, other): ')
        itemname = input('Enter the name of the item: ')
        while True:
            try:
                itemartistid = int(input('Enter the Artist ID from the above list: '))
                if itemartistid < 0:
                    message('Enter a positive number')
                else:
                    break
            except ValueError:
                message('Enter a whole number')
        message('You entered {} {} {}  '.format(itemtype, itemname, itemartistid))
        check = input('Is this correct? "y" or "n": ')
        if check.lower() == 'y':
            break

    update_ind = g.MODIFY
    item = Items(itemtype, itemname, itemartistid, update_ind)  # generate a new replacement object
    item.set_id(item_id)
    g.items_list.insert(item_index, item)  # insert the object back into the list where it came from

    for item in g.items_list:
        message(item)
Пример #7
0
def main():
    """Début du programme
    """

    pygame.init()
    pygame.font.init()
    config = Config()
    display = Display(config)
    level = config.loading_stage("level.txt")
    hero = Hero(level)
    guardian = Guardian(level)
    needle = Items("needle", level)
    ether = Items("ether", level)
    tube = Items("tube", level)
    keys = Event()
    display.draw_window(config)

    while config.run:

        display.draw_labyrinth(level, config)
        keys.actions(level, hero)
        hero.pick(needle)
        hero.pick(ether)
        hero.pick(tube)
        hero.craft()
        display.draw_items(hero, display.hero, config)
        display.draw_items(guardian, display.guardian, config)
        display.draw_items(ether, display.ether, config)
        display.draw_items(needle, display.needle, config)
        display.draw_items(tube, display.tube, config)
        display.draw_inventory(hero, config)
        guardian.is_there_anyone_here(hero, config)
        pygame.display.update()
    display.draw_final(config)
Пример #8
0
 def __init__(self):
     self.paths = []
     self.walls = []
     self.end = None
     self.guardian = None
     self.start = None
     self.hero = None
     self.items = Items(labyrinth=self)
Пример #9
0
def start_game():

    Map = MapPrincess(0, 0)
    item = Items()
    game = Controleur(liste_map=Map.generate_map())

    item.generate_items()
    game.deplacement()
    game.affichage_map()
Пример #10
0
 def __init__(self):
     self.all_items = pygame.sprite.Group()
     self.player = Player(self)
     self.maze = Maze()
     self.item_needle = Items('needle.png', self)
     self.item_tube = Items('plastic_tube.png', self)
     self.item_ether = Items('ether.png', self)
     self.item_syringe = Items('syringe.png', self)
     self.spawn_items()
Пример #11
0
 def createItem(self, lines, j, i, char):
     x = self.stageScale * (j)
     y = self.stageScale * (i)
     rect = pygame.Rect((x, y), (20,20))
     if char ==  "º":
         item = Items(self.itemsDict1, rect)
         item.id = "points"
     else:
         item = Items(self.itemsDict2, rect)
         item.id = "life"
     
     self.itemsGroup.add(item)
Пример #12
0
 def __init__(self):
     name = RandomMonsterName()
     self.fullName = name.getFullName()
     self.shortName = name.getShortName()
     self.hp = 10
     self.strength = 1
     self.killed = False
     self.hasLoot = False
     self.level = 1
     self.item = Items()
     self.Loot = self.item.randomWeapon(self.level)
     self.handler = Stringhandler()
Пример #13
0
def parseItems(directoryPath):
    # Array to hold all the information
    data = []
    # Iterate and extract the files
    for itemFile in ItemFiles:
        # Parse file
        df = pd.read_csv(os.path.join(directoryPath, itemFile.value),
                         sep='\t',
                         header=0,
                         index_col=0)
        # Push dataframe to array
        data.append(df)
    # Generate new items class
    Items.setInstance(data)
Пример #14
0
class ScanTest(unittest.TestCase):
    def setUp(self):
        self.item = Items(456, 10.55, 0)
        self.scan = Scans()
        self.scandate = datetime.datetime.fromtimestamp(time.time())

    def test_scan(self):
        self.item.setRFID(self.scan.scan('SHRUB987'))
        self.assertEqual(self.item.RFID, 'SHRUB987')

    def test_datetime(self):
        self.item.setRFID(self.scan.scan('RABB17'))
        self.scandate = datetime.datetime.fromtimestamp(time.time())
        self.assertEqual(self.scan.date, self.scandate.ctime())
Пример #15
0
 def setUp(self):
     self.Map = MapPrincess(5, 5)
     self.User = User("adel", 3)
     self.contenue = CaseType(4, 0, 0)
     self.Items = Items()
     self.Controleur = Controleur([])
     self.game = Game()
Пример #16
0
 def getItem(self, loot, qty=1):
     if loot.name not in [item.name for item in self.items]:
         self.items.append(Items(loot.name, loot.description, qty))
     else:
         for item in self.items:
             if item.name == loot.name:
                 item.qty += qty
Пример #17
0
    def __init__(self, joystickList, screenSize, systemState, container):
        self.font1 = pygame.font.SysFont("arial", 50)
        self.font2 = pygame.font.SysFont("arial", 30)
        self.screenSize = screenSize
        self.joystickList = joystickList
        self.systemState = systemState
        self.container = container
        
        self.buttonPressed = False##
        self.joystickButtonActivated = True
        self.allowButtonPressing = False
        self.button2Pressed = False##
        self.joystickButton2Activated = True
        self.allowButton2Pressing = False
        
        self.player1 = pygame.sprite.Sprite()
        self.player2 = pygame.sprite.Sprite()
        self.player1.image = pygame.image.load("still//fire01.png").convert_alpha()
        self.player2.image = pygame.image.load("still//fire01.png").convert_alpha()

        self.storyboard = StoryBoard2()
        self.stillDictionary1 = self.container.path1
        self.stillDictionary2 = self.container.path12
        self.itemDictionary = self.container.itemAnimation2
        
        self.score1 = 0
        self.score2 = 0
        self.hp1 = 0
        self.hp2 = 0
        self.time = 0
        
        self.lifeSprite = Items(self.itemDictionary, pygame.Rect((0,0), (20,20)))
        self.background = pygame.image.load("blocks//pausa.png").convert_alpha()
        self.background = pygame.transform.scale(self.background, (self.screenSize[0],self.screenSize[1]))  
Пример #18
0
def main():

    DBconnection()
    db = DBconnection.getInstance().connection

    while True:
        print("Acciones a realizar: \n \
                1. Cliente\n \
                2. Categorías de item\n \
                3. Items\n \
                4. Factura\n \
                5. Salir")
        action = input("Ingrese el número de la acción que desea realizar: ")
        if action == "1":
            customer = Customers(db)
        elif action == "2":
            category = ItemCategories(db)
        elif action == "3":
            item = Items(db)
        elif action == "4":
            bill = Bills(db)
        elif action == "5":
            exit()
        else:
            print("Ingrese un número válido")
Пример #19
0
 def getItem(self, loot, qty=1):
     # remove item from room
     availableQty = self.room.dropItem(loot, qty)
     # add item to player inventory
     if availableQty > 0:
         if loot.name not in [item.name for item in self.inventory]:
             newItem = Items(loot.name, loot.description, availableQty)
             self.inventory.append(newItem)
             newItem.on_take(availableQty)
         else:
             for item in self.inventory:
                 if item.name == loot.name:
                     item.qty += availableQty
                     item.on_take(availableQty)
     else:
         print('No such item available in this room!')
Пример #20
0
def input_art_items_info():
    '''get user information for items in show'''

    message('*** Here are the available Artists. One must be specified')
    message('    when adding an item.')
    for arty in g.artists_list:
        message(arty)
    message('')

    check = ''
    while True:
        clear()
        itemtype = input('Enter the type of item (e.g. print, painting, sculpture, other): ')
        itemname = input('Enter the name of the item: ')
        while True:
            try:
                itemartistid = int(input('Enter the Artist ID from the above list: '))
                if itemartistid < 0:
                    message('Enter a positive number')
                else:
                    break
            except ValueError:
                message('Enter a whole number')
        message('You entered {} {} {}  '.format(itemtype, itemname, itemartistid))
        check = input('Is this correct? "y" or "n": ')
        if check.lower() == 'y':
            break

    update_ind = g.ADD
    item = Items(itemtype, itemname, itemartistid, update_ind)
    g.items_list.append(item)

    for item in g.items_list:
        message(item)
Пример #21
0
    def draw_maze(self):
        """Draws the self.layout's content on screen and creates different entities

        Each number in self.layout corresponds to an element of the maze.
        0 = Free space to walk and place items
        1 = Walls blocking the player
        2 = items placed by the place_items function at random
        3 = Guard : kills the player if he doesn't have all 3 items
        4 = Exit : Enables the win screen
        5 = Start position of player
        At each number (except 0) a sprite is created and added to its group
        """

        # Size of the maze in height and width (both are equal)
        size = 15
        # Counters to build the maze
        column = 0
        row = 0

        # size**2 because width*height = number of tiles
        for tile in range(size**2):
            # 1 = walls
            if self.layout[row + column * size] == 1:
                # We create an instance of Maze and add it to wall group
                wall = Maze(self, row*32, column*32)
                self.all_walls.add(wall)

            # 2 = Items, randomised with self.place_items()
            elif self.layout[row + column * size] == 2:
                asset_name = self.item_list.pop()
                item = Items(self, asset_name, row*32, column*32)
                self.all_items.add(item)

            # 3 = Guard
            elif self.layout[row + column * size] == 3:
                guard = Guard(self, row*32, column*32)
                self.all_guards.add(guard)

            # 4 = Exit
            elif self.layout[row + column * size] == 4:
                exit = Exit(self, row*32, column*32)
                self.all_exits.add(exit)

            # 5 = Player
            elif self.layout[row + column * size] == 5:
                self.player = Player(self, row*32, column*32)
                self.all_players.add(self.player)

                # Entrance addead beneath player
                entrance = Maze(self, row*32, column*32)
                entrance.image = pygame.image.load(ASSETS + "entrance.png")
                entrance.image = pygame.transform.scale(
                    entrance.image, (32, 32))
                self.all_walls.add(entrance)

            column += 1
            if column > size - 1:
                column = 0
                row += 1
Пример #22
0
 def __init__(self, player):
     name = "item"
     self.opened = False
     self.player = player
     self.level = player.level
     self.item = Items()
     self.handler = Stringhandler()
     self.hasLoot = True
     if self.level > 5:
         self.Loot = self.item.randomWeapon(self.level)
     else:
         rnd = random.randint(0, 10)
         if rnd < 3:
             self.hasLoot = False
             self.Loot = ""
         else:
             self.Loot = self.item.randomWeapon(self.level)
Пример #23
0
    def __init__(self):
        """initializing all class of the game"""

        self.labyrinth = Maze()
        self.labyrinth.build('maze.txt')
        self.hero = Hero(self.labyrinth)
        self.items = Items(self.labyrinth)
        self.display_gui = Display(self.labyrinth)
Пример #24
0
 def __init__(self, file):
     self.file = file
     self.passages = set()
     self.start = set()
     self.exit = set()
     self.read_file()
     self.mac_gyver = Character(self)
     self.tools = Items()
Пример #25
0
 def generateRandomCharacter():
     # Get instance of classes
     items = Items.getInstance()
     config = Config.getInstance()
     # Generate all items for new character
     gen = [items.getRandomItem(item) if item != ItemTypes.ALTURA else items.getRandomHeight() for item in ItemTypes]
     # Return character, generated items should be in correct positions
     return Character(config.clase, gen[0], gen[1], gen[2], gen[3], gen[4], gen[5])
Пример #26
0
 def getFamousItems():
     items = It.getItems()['items']
     items = quick(items, 'items')
     #now we will print the three most famous items in the list
     for item in items[-3:][::-1]:
         print('************************')
         print('Item name {}'.format(item['name']))
         print('Ordered : {} times'.format(item['times_ordered']))
         time.sleep(0.5)
Пример #27
0
def main():

    display = Screen('marvinconfig.txt', parser)
    menu = Pages('marvinconfig.txt', parser)
    artifacts = Items('marvinconfig.txt', parser)
    players = Users('marvinconfig.txt', parser)
    universe = Devices('marvinconfig.txt', parser)
    while True:
        '''TODO:
Пример #28
0
    def __getRandomGene(geneIdx):
        items = Items.getInstance()
        # Get item for that index
        item = ItemTypes(geneIdx)
        # Generate random item
        if item != ItemTypes.ALTURA:
            newItem = items.getRandomItem(item)
        else:
            newItem = items.getRandomHeight()

        return newItem
Пример #29
0
    def set_items(self):
        liste_obj = []
        for items in ITEMS:
            # retrieve coordinates to place an object
            x = random.choice(self.free_cells)

            # check if the randomly selected box has not already been taken by a previous loop.
            for cell in self.free_cells:
                if cell == x:
                    self.free_cells.remove(cell)
                    # put an object in the box of coordinates found randomly
                    self.maze[x] = Items(items)
Пример #30
0
class Chest(object):
    def __init__(self, player):
        name = "item"
        self.opened = False
        self.player = player
        self.level = player.level
        self.item = Items()
        self.handler = Stringhandler()
        self.hasLoot = True
        if self.level > 5:
            self.Loot = self.item.randomWeapon(self.level)
        else:
            rnd = random.randint(0, 10)
            if rnd < 3:
                self.hasLoot = False
                self.Loot = ""
            else:
                self.Loot = self.item.randomWeapon(self.level)

    def getLoot(self):
        return self.Loot

    def is_opened(self):
        return self.opened

    def open(self, player):
        self.opened = True
        player.lvlUp()
        if self.hasLoot:
            return self.handler.strChest(
                "open",
                self.getLoot().name) + "\n\n" + self.player.addItem(
                    self.getLoot())
        else:
            string = self.handler.strChest("empty", self.getLoot())

        return string

    def has_loot(self):
        return self.hasLoot
    def __init__(self, hash_lang, fps):
        """
        Init of MainFrame that show item price when mouse is pointing on an item

        Arguments:
        hash_lang -- chosen lang of game client
        fps -- how often will be updated MainFrame
        """
        # Set style and options of Frame
        style = (wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.SIMPLE_BORDER)
        super().__init__(None,
                         title='Tarkov Market Helper',
                         size=(92, 76),
                         style=style)
        self.panel = wx.Panel(self)
        self.SetTransparent(220)
        self.SetBackgroundColour('black')

        # Items init with chosen lang
        self.items = Items(hash_lang)

        # Remember prev item hash to compare with current item hash (for optimization)
        self.previous_item_hash = ''

        # Starting value for item values
        self.item = DataFrame()
        self.item_state = 'No item'

        # MainFrame update time with fps value that get from settings
        self.update_time = 1 / fps

        # Init UI
        self.min_price_text = None
        self.slot_price_text = None
        self.trader_price_text = None
        self.init_ui()

        # Starting thread for positioning frame
        self.thread_is_on = True
        self.turn_thread()
Пример #32
0
    def __init__(self,
                 username=None,
                 password=None,
                 access_token=None,
                 request=None):

        self.request = request or PlayNicelyRequest(username, password)

        self.projects = Projects(self.request)
        self.milestones = Milestones(self.request)
        self.items = Items(self.request)
        self.users = Users(self.request)
        self.echo = Echo(self.request)
Пример #33
0
	def reset( self ):

		self.p1 = self.Paddle( self, "P1", "K_w", "K_s", "LEFT" )
		self.p2 = self.Paddle( self, "P2", "K_UP", "K_DOWN", "RIGHT" )
		self.items = Items( self )
		self.end = False
		self.score = [0, 0]

		self.balllist = [  ]

		for i in range( 2 ):

			self.makeball()
Пример #34
0
 def __init__(self, window, winW, winH):
     self.players = []
     self.itX = []
     self.itY = []
     self.winW = winW
     self.winH = winH
     self.win = window
     self.dicts = {}
     self.action = {}
     self.pic = 0
     self.teamList = ["Team : "]
     self.threadList = {}
     self.mp = Map(window, winW, winH)
     self.perso = Player(window, self.mp)
     self.item = Items(window, self.mp)
     self.initCommands()
     self.initAction()
     self.stat = 0
Пример #35
0
 def __init__(self, plugin):
     self.plugin = plugin
     self.items = Items(self.plugin)
Пример #36
0
class Main:

	class Ball:

		def __init__( self, par, radius, spd, color, t ):

			self.par = par
			self.orgspeed = spd[ 0 ]
			self.topspeed = spd[ 1 ]
			self.speed = self.orgspeed
			self.color = color
			self.r = radius
			self.angle = randint( 0, 359 )
			self.x, self.y = [ i / 2. for i in par.size ]

			self.treshold = 20
			self.hitcooldown = -1
			self.dead = False
			self.lasthit = None

			self.btype = t
			self.types = [  ]
			for t in self.btype:
				self.types.append( t( self ) )

		def update( self ):

			self.x += self.speed * cos( self.angle / ( 180. / pi ) )
			self.y += self.speed * sin( self.angle / ( 180. / pi ) )
			self.hitcooldown -= 1

			for p in ( self.par.p1, self.par.p2 ):
				if self.hitcooldown < 0:
					if self.x + self.r > p.x and self.x - self.r < p.x + p.w and \
					   self.y + self.r > p.y and self.y - self.r < p.y + p.h:

						self.angle %= 360
						
						print self.angle

						if p == self.par.p1: 
							if self.par.p1.m < 0: 
								if not ( 270 > self.angle > 220 ):
									self.angle += 30

							elif self.par.p1.m > 0:
								if not ( 90 < self.angle < 160 ):
									self.angle -= 30

						elif p == self.par.p2: 
							if self.par.p2.m < 0: 
								if not ( 270 < self.angle < 320 ):
									self.angle -= 30

							elif self.par.p2.m > 0:
								if not ( 90 > self.angle > 40 ):
									self.angle += 30

						self.angle = 180 + 360 - self.angle
						#+ ( 45 * ( self.y - (p.y + p.h / 2.) ) / ( p.h / 2. ) )    ##randint( -30, 30 ) ## angle on impact


						if p.x + p.w / 2 - self.x > 0:
							self.x = p.x - self.r
						elif p.x + p.w / 2 - self.x < 0:
							self.x = p.x + p.w + self.r

						p.ballhit = True
						self.hitcooldown = p.w / self.speed + 60
						self.lasthit = p

			if self.x - self.r > self.par.s.get_size(  )[ 0 ]:
				self.dead = True
				self.par.score[0] += 1

			elif self.x + self.r < 0:
				self.dead = True
				self.par.score[1] += 1

			if self.y + self.r > self.par.s.get_size(  )[ 1 ]:
				self.angle = ( ( 360 - self.angle ) % 360 ) + randint( -1, 1 )
				self.y = self.par.s.get_size(  )[ 1 ] - self.r

				if 270 < self.angle < 270 + self.treshold:
					self.angle += 1.5 * self.treshold

				if 270 > self.angle > 270 - self.treshold:
					self.angle += -1.5 * self.treshold

			elif self.y - self.r < 0:
				self.angle = ( ( 360 - self.angle ) % 360 ) + randint( -1, 1 )
				self.y = self.r

				if 90 < self.angle < 90 + self.treshold:
					self.angle += 1.5 * self.treshold

				if 90 > self.angle > 90 - self.treshold:
					self.angle += -1.5 * self.treshold

			for t in self.types:
				t.update(  )

		def draw( self ):

			for t in self.types:
				t.draw(  )

	class Paddle:

		def __init__( self, parent, player, ctrlup, ctrldn, side ):

			self.par = parent
			self.name = player
			self.up = ctrlup
			self.down = ctrldn
			self.color = [ 255, 255, 255 ]
			self.speed = 5
			self.timer = 0
			self.m = 0
			
			self.w = 20
			self.orgh = 60
			self.h = self.orgh
			self.y = self.par.size[ 1 ] / 2.
			self.ballhit = False

			if side == "LEFT": self.x = 20
			if side == "RIGHT": self.x = self.par.size[ 0 ] - 20 - self.w

		def update( self ):

			self.timer += 1
			self.y += self.m

			if not self.y >= 0: self.m = 0; self.y = 0
			if not self.y + self.h <= self.par.s.get_height(  ):
				self.m = 0; self.y = self.par.s.get_height(  ) - self.h

			for e in self.par.events:

				if self.y >= 0 and self.y + self.h <= self.par.s.get_height(  ):

					if e.type == p.KEYDOWN:
						if e.key == getattr( p, self.up ):
							self.m = -self.speed

						if e.key == getattr( p, self.down ):
							self.m = self.speed
							

				if e.type == p.KEYUP:
					if e.key == getattr( p, self.up ) and self.m < 0:
						self.m = 0
					if e.key == getattr( p, self.down ) and self.m > 0:
						self.m = 0

			self.ballhit = False

		def draw( self ):

			p.draw.rect( self.par.s, self.color,
				[ int( self.x ), int( self.y ), int( self.w ), int( self.h ) ] )



	def __init__( self ):

		self.size = ( 640, 480 )
		self.s = p.display.set_mode( self.size ) #, p.FULLSCREEN

		self.reset(  )
		self.debug = 0

	def reset( self ):

		self.p1 = self.Paddle( self, "P1", "K_w", "K_s", "LEFT" )
		self.p2 = self.Paddle( self, "P2", "K_UP", "K_DOWN", "RIGHT" )
		self.items = Items( self )
		self.end = False
		self.score = [0, 0]

		self.balllist = [  ]

		for i in range( 2 ):

			self.makeball()

	def makeball(self):
		
		cs = [ 63, 127, 255 ]
		c = [ cs[ randint( 0, 2 ) ],
			  cs[ randint( 0, 2 ) ],
			  cs[ randint( 0, 2 ) ] ]

		self.balllist.append( self.Ball( self, 8, ( 3, 4 ), c, ( BallTypes.SHADE, ) ) )

	def update( self ):
		
		self.p1.update(  )
		self.p2.update(  )

		l = list( self.balllist )
		for b in self.balllist:
			b.update(  )
			if b.dead: l.remove( b )
		self.balllist = l

		self.items.update(  )

		if len( self.balllist ) <= 0:
			self.end = True
			self.reset(  )

		for b in self.balllist:
			if b.speed < 6:
				b.speed += 1 / 600.

	def draw( self ):

		self.p1.draw(  )
		self.p2.draw(  )
		self.items.draw(  )

		for b in self.balllist:
			b.draw(  )

		if self.debug:

			for n in self.balllist:
				try:
					msg( self.s, n.lasthit.name, ( n.x, n.y - 20 ), size=20, centered=True )
				except:
					msg( self.s, n, ( n.x, n.y - 20 ), size=20 )


		msg( self.s, self.score[0], [self.s.get_width() / 2. - 40,30], size=40, centered=True )
		msg( self.s, self.score[1], [self.s.get_width() / 2. + 40,30], size=40, centered=True )

	def loop( self ):

		c = p.time.Clock(  )

		while 1:

			self.events = p.event.get(  )

			self.s.fill( ( 0,0,0 ) )

			for e in self.events:

				if e.type == p.QUIT:
					p.quit(  )
					quit(  )
				if e.type == p.KEYDOWN:
					if e.key == p.K_d:
						self.debug = self.debug * -1 + 1
					if e.key == p.K_ESCAPE:
						p.quit(  )
						quit(  )

			self.update(  )
			self.draw(  )

			p.display.flip(  )

			c.tick( 60 )
Пример #37
0
    def __init__(self, joystickList, screenSize, initialPath, container):

        self.screenSize = screenSize
        self.joystickList = joystickList
        self.container = container
        self.font = pygame.font.SysFont("arial", 18)
        self.font.set_bold(True)
        self.pauseGame = False
        self.gameOver = False
        self.playerInDeadZone = False
        self.totalElapsedTime = 0
        self.deadMessage = ""
        
        self.walk  = self.container.soundDictionary["walk"]
        self.walk.set_volume(0.1)
        self.jump = self.container.soundDictionary["jump"]
        self.jump.set_volume(0.1)
        self.slide = self.container.soundDictionary["slide1"]
        self.slide.set_volume(0.1)

        self.background = Background(self.screenSize, initialPath, self.container)        
        self.backgroundImage = self.container.imageDictionary[self.background.levelMaker.actualBackgroundKey]
        self.backgroundImage = pygame.transform.scale(self.backgroundImage, (self.screenSize[0], self.screenSize[1]))

        # Relacionado al hub
        self.lifeSprite = Items(self.background.itemAnimation2, pygame.Rect((0,0), (20,20)))
        self.hub = pygame.image.load("blocks//hub.png").convert_alpha()
        self.hub = pygame.transform.scale(self.hub, (670, 65))

        x = self.background.levelMaker.startXPosition
        y = self.background.levelMaker.startYPosition

        if len(self.joystickList) == 2 and self.joystickList != None:
            self.player1  = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
            self.player2  = Player(self.joystickList[1], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
        else:
            self.player1  = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
            self.player2  = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
        self.player1.id = "p1"
        self.player2.id = "p2"
        
        self.player1.companero = self.player2
        self.player2.companero = self.player1

        # Flecha guia (para ubicar a otro player
        self.compassImageUp   = pygame.image.load("blocks//arrowUp.png").convert_alpha()
        self.compassImageDown = pygame.image.load("blocks//arrowDown.png").convert_alpha()
        self.compassImageRight = pygame.image.load("blocks//arrowRight.png").convert_alpha()
        self.compassImageLeft = pygame.image.load("blocks//arrowLeft.png").convert_alpha()
        self.compass = pygame.sprite.Sprite()
        self.compass.image = self.compassImageUp
        self.verticalCompassNeeded  = False
        self.horizontalCompassNeeded = False
        self.P1horizontalCompassNeeded = False

        self.buttonPressed = False##
        self.joystickButtonActivated = True
        self.allowButtonPressing = False
        self.button2Pressed = False##
        self.joystickButton2Activated = True
        self.allowButton2Pressing = False
Пример #38
0
class PauseState(gameObject):


    def __init__(self, joystickList, screenSize, systemState, container):
        self.font1 = pygame.font.SysFont("arial", 50)
        self.font2 = pygame.font.SysFont("arial", 30)
        self.screenSize = screenSize
        self.joystickList = joystickList
        self.systemState = systemState
        self.container = container
        
        self.buttonPressed = False##
        self.joystickButtonActivated = True
        self.allowButtonPressing = False
        self.button2Pressed = False##
        self.joystickButton2Activated = True
        self.allowButton2Pressing = False
        
        self.player1 = pygame.sprite.Sprite()
        self.player2 = pygame.sprite.Sprite()
        self.player1.image = pygame.image.load("still//fire01.png").convert_alpha()
        self.player2.image = pygame.image.load("still//fire01.png").convert_alpha()

        self.storyboard = StoryBoard2()
        self.stillDictionary1 = self.container.path1
        self.stillDictionary2 = self.container.path12
        self.itemDictionary = self.container.itemAnimation2
        
        self.score1 = 0
        self.score2 = 0
        self.hp1 = 0
        self.hp2 = 0
        self.time = 0
        
        self.lifeSprite = Items(self.itemDictionary, pygame.Rect((0,0), (20,20)))
        self.background = pygame.image.load("blocks//pausa.png").convert_alpha()
        self.background = pygame.transform.scale(self.background, (self.screenSize[0],self.screenSize[1]))  


    # Setea los datos que se imprimiran en pantalla
    def setParams(self, time, score1, score2, hp1, hp2):
        self.time = time
        self.score1 = score1
        self.score2 = score2
        self.hp1 = hp1
        self.hp2 = hp2

            
    # Update del estado
    def update(self, elapsedTime):
        self.joystickButtonManager(0)
        self.joystickButtonManager(1)
            
        if self.button2Pressed:
            self.container.soundDictionary["pause"].play()
            self.changeState("playState")
            pygame.mixer.music.set_volume(1)


    def render(self):
        screen = pygame.display.get_surface()
        screen.blit(self.background, (0,0))

        textSurf  = self.font1.render("PAUSA" , True,(255, 0, 0))
        screen.blit(textSurf, (self.screenSize[0] / 2 - 100, 30))
        
        textSurf2  = self.font2.render("presione b para volver" , True,(255, 0, 0))
        screen.blit(textSurf2, (self.screenSize[0] / 2 - 145, 400))

        self.animation(len(self.stillDictionary1), self.stillDictionary1, self.player1)
        self.animation(len(self.stillDictionary2), self.stillDictionary2, self.player2)
        self.player1.image = pygame.transform.scale(self.player1.image, (50,50))
        self.player2.image = pygame.transform.scale(self.player2.image, (50,50))

        screen.blit(self.player1.image,  (50, 500))
        screen.blit(self.player2.image,  (670, 200))

        for i in range(self.hp2):
            screen.blit(self.lifeSprite.image,  (120 + (i * 25), 500))
        for i in range(self.hp1):
            screen.blit(self.lifeSprite.image,  (720 + (i * 25), 200))
        self.lifeSprite.update()

        
        textSurf3  = self.font2.render("Puntaje player 1: " + str(self.score1) , True,(0, 0, 0))
        screen.blit(textSurf3, (720, 250))
        
        textSurf4  = self.font2.render("Puntaje player 2: " + str(self.score2), True,(0, 0, 0))
        screen.blit(textSurf4, (120, 550))
        
        textSurf5  = self.font2.render("Tiempo restante : "  + str(int(150 - self.time)), True,(255, 0, 0))
        screen.blit(textSurf5, (self.screenSize[0] / 2 - 143, 690))


    # ChangeState
    def changeState(self, stateName):
        self.systemState.changeState(stateName)
        self.systemState.currentState.buttonPressed = False##
        self.systemState.currentState.joystickButtonActivated = True
        self.systemState.currentState.allowButtonPressing = False
        self.systemState.currentState.button2Pressed = False##
        self.systemState.currentState.joystickButton2Activated = True
        self.systemState.currentState.allowButton2Pressing = False


    # Ahora keys son las imagenes que se pasan a storyboard
    def animation(self, number, images, sprite):
        if self.storyboard.inProcess == False:
            self.storyboard.play(number, images)
        elif self.storyboard.inProcess:
            return self.storyboard.update(sprite, False)

        
    ## JOYSTICK
    def joystickButtonManager(self, id):
        if id == 0:
            if  (not self.joystickList[0].get_button(id) and self.joystickButtonActivated):
                self.joystickButtonActivated = False
                self.allowButtonPressing = True
            if (self.joystickList[0].get_button(id) and self.joystickButtonActivated and not self.allowButtonPressing):
                self.buttonPressed = False
            if (self.joystickList[0].get_button(id) and not self.buttonPressed and self.allowButtonPressing):
                self.allowButtonPressing = False
                self.buttonPressed = True
                self.joystickButtonActivated = True
        elif id == 1:
            if (not self.joystickList[0].get_button(id) and self.joystickButton2Activated):
                self.joystickButton2Activated = False
                self.allowButton2Pressing = True
            if (self.joystickList[0].get_button(id) and self.joystickButton2Activated and not self.allowButton2Pressing):
                self.button2Pressed = False
            if (self.joystickList[0].get_button(id) and not self.button2Pressed and self.allowButton2Pressing):
                self.allowButton2Pressing = False
                self.button2Pressed = True
                self.joystickButton2Activated = True
Пример #39
0
class level:

    
    # Constructor
    def __init__(self, joystickList, screenSize, initialPath, container):

        self.screenSize = screenSize
        self.joystickList = joystickList
        self.container = container
        self.font = pygame.font.SysFont("arial", 18)
        self.font.set_bold(True)
        self.pauseGame = False
        self.gameOver = False
        self.playerInDeadZone = False
        self.totalElapsedTime = 0
        self.deadMessage = ""
        
        self.walk  = self.container.soundDictionary["walk"]
        self.walk.set_volume(0.1)
        self.jump = self.container.soundDictionary["jump"]
        self.jump.set_volume(0.1)
        self.slide = self.container.soundDictionary["slide1"]
        self.slide.set_volume(0.1)

        self.background = Background(self.screenSize, initialPath, self.container)        
        self.backgroundImage = self.container.imageDictionary[self.background.levelMaker.actualBackgroundKey]
        self.backgroundImage = pygame.transform.scale(self.backgroundImage, (self.screenSize[0], self.screenSize[1]))

        # Relacionado al hub
        self.lifeSprite = Items(self.background.itemAnimation2, pygame.Rect((0,0), (20,20)))
        self.hub = pygame.image.load("blocks//hub.png").convert_alpha()
        self.hub = pygame.transform.scale(self.hub, (670, 65))

        x = self.background.levelMaker.startXPosition
        y = self.background.levelMaker.startYPosition

        if len(self.joystickList) == 2 and self.joystickList != None:
            self.player1  = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
            self.player2  = Player(self.joystickList[1], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
        else:
            self.player1  = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
            self.player2  = Player(self.joystickList[0], ProjectileMotion(), FreeFall(15), StoryBoard2(), self.container, x, y)
        self.player1.id = "p1"
        self.player2.id = "p2"
        
        self.player1.companero = self.player2
        self.player2.companero = self.player1

        # Flecha guia (para ubicar a otro player
        self.compassImageUp   = pygame.image.load("blocks//arrowUp.png").convert_alpha()
        self.compassImageDown = pygame.image.load("blocks//arrowDown.png").convert_alpha()
        self.compassImageRight = pygame.image.load("blocks//arrowRight.png").convert_alpha()
        self.compassImageLeft = pygame.image.load("blocks//arrowLeft.png").convert_alpha()
        self.compass = pygame.sprite.Sprite()
        self.compass.image = self.compassImageUp
        self.verticalCompassNeeded  = False
        self.horizontalCompassNeeded = False
        self.P1horizontalCompassNeeded = False

        self.buttonPressed = False##
        self.joystickButtonActivated = True
        self.allowButtonPressing = False
        self.button2Pressed = False##
        self.joystickButton2Activated = True
        self.allowButton2Pressing = False

  
    # Update de todas las variables relevantes
    def update(self, elapsedTime):

        # Tiempo
        self.totalElapsedTime += elapsedTime
        if self.totalElapsedTime > 200:
            self.gameOver = True
            self.deadMessage = "TIME'S UP!"

        # Brujula que apunta a player 2
        if  self.player2.Y <= -50 or self.player2.Y >= self.screenSize[1]:
            self.horizontalCompassNeeded = True
        elif self.player2.X <= -50 or self.player2.X >= self.screenSize[0]:
            self.verticalCompassNeeded = True
        else:
            self.horizontalCompassNeeded = False
            self.verticalCompassNeeded = False
            
        # Brujula que apunta a player 1
        if  self.player1.Y <= -50 or self.player1.Y >= self.screenSize[1]:
            self.P1horizontalCompassNeeded = True
        else:
            self.P1horizontalCompassNeeded = False
        
        # Update a las instancias del nivel
        #for sprite in self.background.group:
        #   if sprite.activada:
        #       if not((self.player1.color == sprite.color and pygame.sprite.collide_rect(sprite,self.player1.sprite))) and  not((self.player2.color == sprite.color and pygame.sprite.collide_rect(sprite,self.player2.sprite)))  :
        #            sprite.activada = False
        #       if not((self.player2.color == sprite.color and pygame.sprite.collide_rect(sprite,self.player2.sprite))):
        #           sprite.activada = False
               #else:
               #   sprite.activada = False
        #for sprite in self.background.group:
        #    if sprite.activada:
        #        if (pygame.sprite.collide_rect(sprite,self.player1.sprite)):
        #               if(self.player1.color == sprite.color):
        #                   sprite.activada = True
        #        if (pygame.sprite.collide_rect(sprite,self.player2.sprite)):
        #               if(self.player2.color == sprite.color):
        #                   sprite.activada = True
        
        for sprite in self.background.group:
            sprite.activada = False             
        self.player2.update(elapsedTime, self.background.group, self.background.exitGroup, self.background.damageGroup, self.background.itemsGroup, self.background.zGroup, self.background.groupList)#-----------------#
        self.player1.update(elapsedTime, self.background.group, self.background.exitGroup, self.background.damageGroup, self.background.itemsGroup, self.background.zGroup,  self.background.groupList)
        self.backgroundXMovementManager(self.player1, self.player2)
        self.backgroundYMovementManager(self.player1, self.player2)
        for torreta in self.background.levelMaker.torretas:
            torreta.update(elapsedTime,self.background.group,self.background.xAdvance, self.background.yAdvance, self.player1, self.player2,self.screenSize)
            
        self.background.update(elapsedTime, self.player1.X, self.player1.Y)

        
        """
        # DISTANCIA PERSONAJES (TEMPORAL)
        if abs(self.player1.X - self.player2.X) >= self.screenSize[0]:
            self.player2.X = self.player1.X
            self.player2.Y = self.player1.Y
        if abs(self.player1.Y - self.player2.Y) >= self.screenSize[1]:
            self.player2.X = self.player1.X
            self.player2.Y = self.player1.Y
        #"""   


        ###########CAMBIO_DE_ETAPA##################################
        if self.player1.exitStage or self.player2.exitStage:
            self.player1.exitStage = False
            self.player2.exitStage = False

            self.background.changeBackground()

            self.backgroundImage = self.container.imageDictionary[self.background.backgroundKey]
            self.backgroundImage = pygame.transform.scale(self.backgroundImage, (self.screenSize[0], self.screenSize[1]))
            
            self.player1.X = self.background.levelMaker.startXPosition
            self.player1.Y = self.background.levelMaker.startYPosition
            self.player2.X = self.background.levelMaker.startXPosition 
            self.player2.Y = self.background.levelMaker.startYPosition

        #################GAME_OVER##################################
        if self.player1.dead or self.player2.dead:
            self.gameOver = True
            if self.player1.dead:
                self.deadMessage = self.player1.deadMessage
            else:
                self.deadMessage = self.player2.deadMessage
                 

    # Dibuja en pantalla los sprites y el escenario
    def render(self):
        
        # Instancia de la ventana de pygame
        screen = pygame.display.get_surface()

        # Render a las instancias del nivel
        screen.blit(self.backgroundImage, (0,0))
        
        self.player1.render()   
        self.player2.render()
        self.background.render()
        for torreta in self.background.levelMaker.torretas:
            torreta.render()

        # Brujula que apunta a otro player
        if self.horizontalCompassNeeded or self.P1horizontalCompassNeeded:
            if self.player2.Y <= -50 or self.player1.Y <= -50:
                self.compass.image = self.compassImageUp
                if self.player2.Y <= -50:
                    screen.blit(self.compass.image, (self.player2.X, 0))
                else:
                    screen.blit(self.compass.image, (self.player1.X, 0))
            if self.player2.Y >= self.screenSize[1] or self.player1.Y >= self.screenSize[1]:
                self.compass.image = self.compassImageDown
                if self.player2.Y >= self.screenSize[1]:
                    screen.blit(self.compass.image, (self.player2.X, self.screenSize[1] - 15))
                else:
                    screen.blit(self.compass.image, (self.player1.X, self.screenSize[1] - 15))
        if self.verticalCompassNeeded:
            if self.player2.X <= -50:
                self.compass.image = self.compassImageLeft
                screen.blit(self.compass.image, (0, self.player2.Y))
            if self.player2.X >= self.screenSize[0]:
                self.compass.image = self.compassImageRight
                screen.blit(self.compass.image, ((self.screenSize[0] - 15), self.player2.Y))

        # HUB SCREEN
        screen.blit(self.hub,  (180, 0))
        
        textSurf1 = self.font.render("P1 HP: " , True,(27, 141, 67))
        textSurf2 = self.font.render("P2 HP: " , True,(0, 0, 255))
        textSurf3 = self.font.render("Puntaje: " + str(int(self.player1.score)) , True, (27, 141, 67))
        textSurf4 = self.font.render("Puntaje: " + str(int(self.player2.score)) , True, (0, 0, 255))
        textSurf5 = self.font.render("Tiempo restante: " + str(150 - int(self.totalElapsedTime)) , True,(255, 0, 0))
        
        screen.blit(textSurf1,  (400, 10))
        screen.blit(textSurf2,  (400, 40))
        screen.blit(textSurf3,  (700, 10))
        screen.blit(textSurf4,  (700, 40))
        screen.blit(textSurf5,  (190, 10))
    

        for i in range(self.player1.lives):
            screen.blit(self.lifeSprite.image,  (470 + (i * 20), 10))
        for i in range(self.player2.lives):
            screen.blit(self.lifeSprite.image,  (470 + (i * 20), 40))
        self.lifeSprite.update()
 

    # Intento de arreglar el algoritmo. Veamos como resulta
    def backgroundYMovementManager(self, player1, player2):
 
        # Obtiene los valores de posicion de primer y ultimo sprite del grupo
        firstRect = self.background.levelMaker.firstRect
        lastRect  = self.background.levelMaker.lastRect
        
        # relevante para scrolling horizontal y vertical

        leftStageX = firstRect.left
        rightStageX = lastRect.left
        topStageY = firstRect.top
        bottomStageY = lastRect.top
        halfH = self.screenSize[1]/2.0
        height = self.screenSize[1]

        levelHigherThanScreen = self.background.levelMaker.height * 50 > self.screenSize[1]
    
        _2playerUpperLimit = 0
        _2playerBottomLimit = height - 100
        _2PlayerInScreen = player2.Y >= _2playerUpperLimit and player2.Y <= _2playerBottomLimit
        # El 50 es para tomar en cuenta la altura del personaje
        _2PlayerInRealScreen = _2PlayerInScreen  #player2.Y >= -50 and player2.Y <= height
        _1PlayerInRealScreen = player1.Y >= -50 and player1.Y <= height
                
        deltaDownDeadZone = abs(firstRect.top) # Background moving down
        deltaUpDeadZone = lastRect.top - height # Background moving up

        # Caso en que etapa es demasiado pequena
        if not levelHigherThanScreen:
            player1.Y -= player1.deltaY
            
        # Si player esta centrado y player 2 se encuentra en pantalla ficticia
        # Camara seguira a player 1 hasta que player 2 salga de pantalla por delta de player 1
        # Revisar que se respeten las deadZones
        elif player1.Y == halfH and _2PlayerInScreen:
        
            # Caso en que el player2 esta dentro del area y no toca los bordes
            if (player2.Y + player1.deltaY > _2playerUpperLimit) and (player2.Y + player1.deltaY < _2playerBottomLimit):
                self.background.yAdvance = player1.deltaY
                if   player1.deltaY < 0:
                    self.background.moveBackGroundUp = True
                    self.background.yAdvance = -min(abs(player1.deltaY), deltaUpDeadZone)
                elif player1.deltaY > 0:
                    self.background.moveBackGroundDown = True
                    self.background.yAdvance = min(player1.deltaY, deltaDownDeadZone)

                player2.Y += self.background.yAdvance#---------------------------#
                player1.Y -= player1.deltaY - self.background.yAdvance

            # Si player dos se sale del limite inferior al aplicar movimiento de player 1
            # Player 1 esta subiendo
            elif player2.Y < _2playerBottomLimit and (player2.Y + player1.deltaY > _2playerBottomLimit):
                self.background.moveBackGroundDown = True
                deltaP1 = (player2.Y + player1.deltaY) - _2playerBottomLimit
                deltaBackground =  player1.deltaY - deltaP1
                deltaBackground = min(deltaBackground , deltaDownDeadZone)#######################################################33
                self.background.yAdvance = deltaBackground      
                player1.Y -= deltaP1
                player2.Y += self.background.yAdvance#---------------------------#  
            
            # Si player 2 se sale de limite superior al aplicar movimiento de player 1
            # Player 1 esta cayendo
            elif player2.Y > _2playerUpperLimit and (player2.Y + player1.deltaY < _2playerUpperLimit):
                self.background.moveBackGroundUp = True
                deltaBackground = player2.Y # antes era (-), asi que si cualquier bug aparece, volver a eso
                deltaBackground = -min(deltaBackground , deltaUpDeadZone)#######################################################33
                deltaP1 = (-1) * abs(player1.deltaY - deltaBackground)
                self.background.yAdvance = deltaBackground
                player1.Y -= deltaP1
                player2.Y += self.background.yAdvance#--------------------------#
            
        # Player esta centrado y player 2 no esta en pantalla
        # Camara sigue a player 1 de forma completa
        # Revisar que se respeten las deadZones OK
        elif player1.Y == halfH and not _2PlayerInRealScreen:
            self.background.yAdvance = player1.deltaY
            if   player1.deltaY < 0:
                self.background.moveBackGroundUp = True
                self.background.yAdvance = -min(abs(player1.deltaY), deltaUpDeadZone)
            elif player1.deltaY > 0:
                self.background.moveBackGroundDown = True
                self.background.yAdvance = min(player1.deltaY, deltaDownDeadZone)

            player1.Y -= player1.deltaY - self.background.yAdvance
            player2.Y += self.background.yAdvance
            
        # Si ningun player esta en pantalla, esta se centra automaticamente en player 1
        # es una prueba
        elif not _2PlayerInRealScreen and not _1PlayerInRealScreen :
            self.jump.play()
        
        # Si player 1 no esta centrado : 
        # Si player 2 esta en pantalla, se centrara sujeto a que no quede fuera de pantalla ficticia
        # Si player 2 no esta en pantalla, solo se centrara
        # Revisar que se respeten las deadZones
        elif player1.Y != halfH:

            # Si player 2 esta en el area
            if player2.Y > _2playerUpperLimit and player2.Y < _2playerBottomLimit and (firstRect.top <= 0 and lastRect.top >= height):
                #player2.Y > _2playerUpperLimit and player2.Y < _2playerBottomLimit and 
                deltaP1 = player1.Y - halfH           
                    
                # Esta sobre la linea media. Escenario baja con player 1 para dejarlo centrado
                # No puede pasar que firstRect.top quede mayor que cero (al alejarse de origen)
                if player1.Y < halfH: #and _2PlayerInScreen:
                    deltaDeadZone = abs(firstRect.top)
                    #if player2.deltaY > 0:
                    deltaP1 = -min(abs(_2playerBottomLimit - player2.Y), abs(deltaP1), deltaDeadZone)
                    #elif player2.deltaY <= 0: #and player1.Y + player2.deltaY > 0:
                    #    deltaP1 = - player2.deltaY
                    self.background.moveBackGroundDown = True
                
                # Esta bajo la linea media. Escenario sube con player 1 para dejarlo centrado
                # No puede pasar que lastRect.bottom quede menor que height
                elif player1.Y > halfH: #and _2PlayerInScreen:
                    deltaDeadZone = lastRect.top - height
                    deltaP1 = min(abs(player2.Y), abs(deltaP1), deltaDeadZone)
                    self.background.moveBackGroundUp = True
                
                self.background.yAdvance = -deltaP1
                player2.Y += self.background.yAdvance#-----------------#
                player1.Y -= deltaP1
            
            ## Player 1 se encuentra bajo linea media 
            if player1.Y > halfH:
                # Si saltar lo deja arriba de linea media
                if player1.Y - player1.deltaY <= halfH:
                    deltaP1 = player1.Y - halfH
                    self.background.moveBackGroundDown = True
                    deltaBackground1 = abs(player1.deltaY) - deltaP1
                    deltaBackground2 = min(deltaBackground1, deltaDownDeadZone)#######################################################33
                    self.background.yAdvance = deltaBackground2
                    deltaP1 -= abs(deltaBackground2 - deltaBackground1)
                    player2.Y += self.background.yAdvance#-----------------#
                    player1.Y -= deltaP1
                # Si saltar lo sigue dejando abajo de la linea
                elif player1.Y - player1.deltaY > halfH:
                    player1.Y -= player1.deltaY

            ## Se encuentra sobre linea media
            elif player1.Y < halfH:
                # Si caer lo deja bajo la linea
                if player1.Y - player1.deltaY >= halfH:
                    deltaP1 = player1.Y - halfH
                    deltaBackground1 = abs(player1.deltaY) - abs(deltaP1)
                    deltaBackground2 = - min(deltaBackground1, deltaUpDeadZone)#######################################################33
                    self.background.moveBackGroundUp = True
                    self.background.yAdvance = deltaBackground2
                    deltaP1 -= abs(abs(deltaBackground2) - abs(deltaBackground1))
                    player2.Y += self.background.yAdvance#-----------------#
                    player1.Y -= deltaP1
                # Si caer lo sigue dejando sobre la linea
                elif player1.Y - player1.deltaY < halfH:
                    player1.Y -= player1.deltaY

            ## Se tiene que llegar a esto en caso de que todo el resto no se cumpla
            else:
                player1.Y -= player1.deltaY


    # Se encarga de movimiento horizontal para camara con dos jugadores
    def backgroundXMovementManager(self, player1, player2):

        levelWiderThanScreen = self.background.levelMaker.width * 50 > self.screenSize[0]

        # Obtiene los valores de posicion de primer y ultimo sprite del grupo
        firstRect = self.background.levelMaker.firstRect
        lastRect  = self.background.levelMaker.lastRect
        
        # relevante para scrolling horizontal y vertical
        leftStageX = firstRect.left
        rightStageX = lastRect.left
        halfW = self.screenSize[0]/2.0


        if not levelWiderThanScreen:
            player1.X += player1.deltaX

        elif  ((player1.X + player1.deltaX) - leftStageX <= halfW) and (player1.X - leftStageX > halfW) and player1.deltaX < 0:
            rightPart = player1.X - (halfW + leftStageX)
            leftPart = abs(player1.deltaX) - rightPart

            player1.X += player1.deltaX + rightPart
            self.background.moveBackGroundForward = True
            self.background.xAdvance = abs(rightPart)
        
        elif (player1.X - leftStageX <= halfW) and ((player1.X + player1.deltaX) - leftStageX > halfW) and player1.deltaX > 0 :
            leftPart = (leftStageX + halfW) - player1.X
            rightPart = player1.deltaX - leftPart
                
            player1.X += player1.deltaX - rightPart
            self.background.moveBackGroundBackward = True
            self.background.xAdvance = abs(rightPart) * (-1)
        
        elif (rightStageX - player1.X > halfW) and (rightStageX - (player1.X + player1.deltaX) <= halfW) and player1.deltaX > 0:
            leftPart = (rightStageX - halfW) - player1.X
            rightPart = player1.deltaX - leftPart

            player1.X += player1.deltaX  - leftPart
            self.background.moveBackGroundBackward = True
            self.background.xAdvance = abs(leftPart) * (-1)
        
        elif (rightStageX - player1.X <= halfW) and (rightStageX - (player1.X + player1.deltaX) > halfW) and player1.deltaX < 0:
            rightPart = player1.X - (rightStageX - halfW)
            leftPart = abs(player1.deltaX) - rightPart

            player1.X += player1.deltaX + leftPart
            self.background.moveBackGroundForward = True
            self.background.xAdvance = abs(leftPart)
        
        elif((player1.X - leftStageX) >= halfW) and ((rightStageX - player1.X) >= halfW):
            self.background.xAdvance = -int(player1.deltaX)
            if player1.deltaX > 0:
                self.background.moveBackGroundBackward = True
            elif player1.deltaX < 0:
                self.background.moveBackGroundForward = True
        else:
            player1.X += player1.deltaX


        player2.X += self.background.xAdvance#---------------------------#
Пример #40
0
class Parser:
    """Check all command et execute command"""

    def __init__(self, window, winW, winH):
        self.players = []
        self.itX = []
        self.itY = []
        self.winW = winW
        self.winH = winH
        self.win = window
        self.dicts = {}
        self.action = {}
        self.pic = 0
        self.teamList = ["Team : "]
        self.threadList = {}
        self.mp = Map(window, winW, winH)
        self.perso = Player(window, self.mp)
        self.item = Items(window, self.mp)
        self.initCommands()
        self.initAction()
        self.stat = 0

    def initCommands(self):
        self.dicts["msz"] = self.Cmsz
        self.dicts["pnw"] = self.Cpnw
        self.dicts["enw"] = self.Cenw
        self.dicts["pbc"] = self.Cpbc
        self.dicts["eht"] = self.Ceht
        self.dicts["edi"] = self.Cedi
        self.dicts["ppo"] = self.Cppo
        self.dicts["plv"] = self.Cplv
        self.dicts["pfk"] = self.Cpfk
        self.dicts["pdi"] = self.Cpdi
        self.dicts["bct"] = self.Cbct
        self.dicts["pex"] = self.Cpex
        self.dicts["pin"] = self.Cpin
        self.dicts["pic"] = self.Cpic
        self.dicts["pie"] = self.Cpie
        self.dicts["pdr"] = self.Cpdr
        self.dicts["pgt"] = self.Cpgt
        self.dicts["ebo"] = self.Cebo
        self.dicts["sgt"] = self.Csgt
        self.dicts["seg"] = self.Cseg
        self.dicts["smg"] = self.Csmg
        self.dicts["tna"] = self.Ctna
        self.dicts["suc"] = self.Cunknown
        self.dicts["sbp"] = self.Cunknown

    def initAction(self):
        self.action["msz"] = self.mp.displayMap
        self.action["pnw"] = self.perso.add
        self.action["enw"] = self.perso.makeEggs
        self.action["pbc"] = self.perso.broadcast
        self.action["eht"] = self.perso.hatchEggs
        self.action["edi"] = self.perso.hatchEggs
        self.action["ppo"] = self.perso.update
        self.action["plv"] = self.perso.setLevel
        self.action["pfk"] = self.perso.shield
        self.action["pdi"] = self.perso.die
        self.action["bct"] = self.item.addItem

    def checkCommand(self, command):
        if command[0] == "BIENVENUE":
            return
        print command
        if (self.dicts[command[0]](command) == False):
            print "Invalid Command =>" + command[0]

    def updateMap(self, winW, winH):
        self.winW = winW
        self.winH = winH
        self.mp.updateMap(winW, winH, self.item, self.perso, self.players, self.teamList)

    def play_music(self, song, lop):
        try:
            if not pygame.mixer.get_init():
                pygame.mixer.init()
            pygame.mixer.music.load(song)
            pygame.mixer.music.set_volume(float(50.00)/100)
            channel = pygame.mixer.music.play(lop)
        except:
            print "Could not load music"

    def checkInt(self, valArray, size):
        i = 1
        while (i < size):
            if (valArray[i].isdigit == False):
                print "ioJAIODJOJIOJDIOJ"
                return False
            i += 1
        return True

    def run(self, id):
        self.perso.execCommand(id)

    def Cmsz(self, command):
        if (len(command) != 3 or self.checkInt(command, 3) == False):
            return False
        self.action[command[0]](int(command[1]) - 1,
                                int(command[2]) - 1)
        self.stat = 1
        self.displayAll()
        self.play_music("bgm/Rick_Rolled.wav", -1)

    def Cpnw(self, command):
        if (len(command) != 7 or self.checkInt(command, 6) == False):
            return False
        self.action[command[0]](int(command[1]),
                                int(command[2]),
                                int(command[3]),
                                int(command[4]),
                                int(command[5]),
                                command[6], self.mp)
        self.players.append(int(command[1]))

    def Cenw(self, command):
        if (len(command) != 5 or self.checkInt(command, 5) == False):
            return False
        self.action[command[0]](int(command[1]),
                                int(command[2]),
                                int(command[3]),
                                int(command[4]))

    def Cpbc(self, command):
        if (len(command) <= 3 or self.checkInt(command, 1) == False):
            return False
        self.action[command[0]](int(command[1]))

    def Ceht(self, command):
        if (len(command) != 2 or self.checkInt(command, 2) == False):
            return False
        self.action[command[0]](int(command[1]))

    def Cedi(self, command):
        if (len(command) != 2 or self.checkInt(command, 2) == False):
            return False

    def Cppo(self, command):
        if (len(command) != 5 or self.checkInt(command, 5) == False):
            return False
        self.action[command[0]](int(command[1]),
                                  int(command[2]),
                                  int(command[3]),
                                  int(command[4]),
                                  self.mp,
                                  self.winW,
                                  self.winH,
                                  self.item,
                                  self.perso, self.players, self.teamList)

    def Cplv(self, command):
        if (len(command) != 3 or self.checkInt(command, 3) == False):
            return False
        self.action[command[0]](int(command[1]),
                                int(command[2]))

    def Cpfk(self, command):
        if (len(command) != 2 or self.checkInt(command, 2) == False):
            return False
        self.action[command[0]](int(command[1]))

    def Cpdi(self, command):
        if (len(command) != 2 or self.checkInt(command, 2) == False):
            return False
        self.action[command[0]](int(command[1]), self.winW, self.winH, self.item, self.perso, self.players, self.teamList)
        value = int(command[1]) in self.players
        if value == True:
            self.players.remove(int(command[1]))

    def Cbct(self, command):
        o = 0
        i = 0
        if (len(command) != 10 or self.checkInt(command, 10) == False):
            return False
        self.action[command[0]](int(command[1]),
                                  int(command[2]),
                                  int(command[3]),
                                  int(command[4]),
                                  int(command[5]),
                                  int(command[6]),
                                  int(command[7]),
                                  int(command[8]),
                                  int(command[9]))
        while i < len(self.itX):
            if (int(command[1]) == self.itX[i]):
                if (int(command[2]) == self.itY[i]):
                    o += 1
            i += 1
        if (o == 0):
            self.itX.append(int(command[1]))
            self.itY.append(int(command[2]))

    def Cpex(self, command):
        if (len(command) != 2 or self.checkInt(command, 2) == False):
            return False

    def Cpin(self, command):
        if (len(command) != 11 or self.checkInt(command, 10) == False):
            print "pin failed!"
            return False

    def Ctna(self, command):
        if len(command) != 2:
            return False
        self.teamList.append(command[1])

    def Cpic(self, command):
        if len(command) <= 4:
            return False
        self.perso.incantation(command)
        self.pic = 1

    def Cpie(self, command):
        if (len(command) != 4 or self.checkInt(command, 4) == False):
            return False
        if command[3] == 1:
            self.perso.endIncantation(command)

    def Cpdr(self, command):
        if (len(command) != 3 or self.checkInt(command, 3) == False):
            return False

    def Cpgt(self, command):
        if (len(command) != 3 or self.checkInt(command, 3) == False):
            return False

    def Cebo(self, command):
        if (len(command) != 2 or self.checkInt(command, 2) == False):
            return False

    def Csgt(self, command):
        if len(command) != 2:
            return False
        try:
            float(command[1])
        except:
            return False

    def Cseg(self, command):
        try:
            if len(command) != 2:
                return False
            loading = pygame.image.load("../map/logo/victory.png").convert_alpha()
            self.win.blit(loading, (0,0))
            pygame.display.update()
            team = "Team : "
            team += command[1]
            myfont = pygame.font.Font("Lato-Light.ttf", 30)
            label = myfont.render(team, 1, (255, 255, 255))
            self.play_music("bgm/victory.wav", 0)
            while 1:
                Kinput = pygame.key.get_pressed()
                if (Kinput[pygame.K_ESCAPE]):
                    sys.exit()
                pygame.event.pump()
                self.win.blit(label, (550, 200))
                pygame.display.update()
        except:
            sys.exit("VICTORY")

    def Csmg(self, command):
        if len(command) != 1:
            return False

    def Cunknown(self, command):
        if len(command) != 1:
            return False
        pass

    def displayPlayers(self):
        i = 0
        while i < len(self.players):
            self.perso.display(self.players[i], self.winW, self.winH)
            i += 1

    def displayItems(self):
        i = 0
        while i < len(self.itX):
            self.item.displayItem(self.itX[i], self.itY[i], self.winW, self.winH)
            i += 1

    def displayMap(self):
        self.mp.updateMap(self.winW, self.winH, self.item, self.perso, self.players, self.teamList)

    def displayAll(self):
        if (self.stat == 1):
            self.displayMap()
            self.displayPlayers()
            pygame.display.update()
Пример #41
0
class Parser:

    def __init__(self, plugin):
        self.plugin = plugin
        self.items = Items(self.plugin)

    def rails_items(self, data, id_):
        if id_ == 'home':
            epg = {
                'mode': 'epg',
                'title': self.plugin.get_string(30212),
                'plot': 'Schedule',
                'params': 'today',
            }
            epg['cm'] = Context(self.plugin).highlights(epg, mode='epg_highlights')
            self.items.add_item(epg)
        for i in data.get('Rails', []):
            item = Rails(self.plugin, i).item
            if item.get('id', '') == 'CatchUp':
                item['cm'] = Context(self.plugin).highlights(item, mode='rail_highlights')
            self.items.add_item(item)
        self.items.list_items()

    def rail_items(self, data, mode, list_=True):
        highlights = True if 'highlights' in mode else False
        focus = data.get('StartPosition', False)
        for i in data.get('Tiles', []):
            context = Context(self.plugin)
            item = Tiles(self.plugin, i).item
            if highlights:
                if item['type'] == 'Highlights':
                    item['cm'] = context.goto(item)
                    self.items.add_item(item)
                elif item.get('related', []):
                    for i in item['related']:
                        if i.get('Videos', []):
                            _item = Tiles(self.plugin, i).item
                            _item['cm'] = context.goto(_item)
                            self.items.add_item(_item)
            else:
                if item.get('related', []):
                    cm_items = []
                    for i in item['related']:
                        if i.get('Videos', []):
                            cm_items.append(Tiles(self.plugin, i).item)
                    context.related(cm_items)
                item['cm'] = context.goto(item)
                self.items.add_item(item)
        if list_:
            self.items.list_items(focus)

    def epg_items(self, data, params, mode):
        update = False if params == 'today' else True
        if data.get('Date'):
            date = self.plugin.epg_date(data['Date'])
            cm = Context(self.plugin).epg_date()

            def date_item(day):
                return {
                    'mode': mode,
                    'title': '{0} ({1})'.format(self.plugin.get_resource(day.strftime('%A')), day.strftime(self.plugin.date_format)),
                    'plot': '{0} ({1})'.format(self.plugin.get_resource(date.strftime('%A')), date.strftime(self.plugin.date_format)),
                    'params': day,
                    'cm': cm
                }

            self.items.add_item(date_item(self.plugin.get_prev_day(date)))
            self.rail_items(data, mode, list_=False)
            self.items.add_item(date_item(self.plugin.get_next_day(date)))
        self.items.list_items(upd=update, epg=True)

    def playback(self, data, name=False, context=False):
        self.items.play_item(Playback(self.plugin, data), name, context)
Пример #42
0
class Parser:

    def __init__(self, plugin):
        self.plugin = plugin
        self.items = Items(self.plugin)

    def channel(self, data):
        hits = data['data']['Airings']
        for i in hits:
            item = Hits(self.plugin, i).item
            if item.get('id'):
                self.items.add_item(item)
        date = self.plugin.epg_date()
        prev_date = self.plugin.get_prev_day(date)
        self.items.add_item(
            {
                'mode': 'epg',
                'title': self.plugin.get_string(30103),
                'plot': self.plugin.get_string(30103),
                'id': date.strftime(self.plugin.date_format),
                'params': prev_date.strftime(self.plugin.date_format)
            }
        )
        self.items.add_item(
            {
                'mode': 'sports',
                'title': self.plugin.get_string(30101),
                'plot': self.plugin.get_string(30102)
            }
        )
        self.items.add_item(
            {
                'mode': 'events',
                'title': self.plugin.get_string(30104),
                'plot': self.plugin.get_string(30104)
            }
        )
        self.items.list_items(sort=True)

    def sport(self, data):
        self.items.add_item(
            {
                'mode': 'all_sports',
                'title': self.plugin.get_string(30105).upper(),
                'plot': self.plugin.get_string(30105)
            }
        )
        hits = data['data']['sports_filter']['list']
        for i in hits:
            self.items.add_item(Sports(self.plugin, i).item)
        self.items.list_items(sort=True)

    def all_sports(self, data):
        hits = data['data']['CategoryAll']
        for i in hits:
            item = Sports(self.plugin, i).item
            if item.get('thumb') and item.get('id'):
                self.items.add_item(item)
        self.items.list_items(sort=True)

    def events(self, data):
        hits = data['data']['EventPageByLanguage']
        for i in hits:
            self.items.add_item(Events(self.plugin, i).item)
        self.items.list_items()

    def event(self, data):
        media = data['data']['EventPageByContentId']['media']
        for m in media:
            hits = m['videos']
            for i in hits:
                self.items.add_item(Hits(self.plugin, i, event=True).item)
        self.items.list_items()

    def video(self, data, id_):
        sport_id = 'sport_{0}'.format(id_)
        hits = data['data'][sport_id]['hits']
        for i in hits:
            hit = i['hit']
            item = Hits(self.plugin, hit).item
            if item.get('id'):
                self.items.add_item(item)
        self.items.list_items()

    def epg(self, data, prev_date, date):

        def date_item(params, id_):
            return {
                'mode': 'epg',
                'title': '{0} {1}'.format(self.plugin.get_resource(id_.strftime('%A')), id_.strftime(self.plugin.date_format)),
                'plot': '{0} {1}'.format(self.plugin.get_resource(self.plugin.epg_date(date).strftime('%A')), self.plugin.epg_date(date).strftime(self.plugin.date_format)),
                'id': id_.strftime(self.plugin.date_format),
                'params': params.strftime(self.plugin.date_format),
                'cm': cm
            }

        update = False if date == self.plugin.epg_date().strftime(self.plugin.date_format) else True
        cm = Context(self.plugin).epg_date()

        self.items.add_item(date_item(self.plugin.get_prev_day(self.plugin.epg_date(prev_date)), self.plugin.epg_date(prev_date)))
        hits = data['data']['Airings']
        hits = sorted(hits, key=lambda k: k.get('startDate'))
        for i in hits:
            self.items.add_item(Hits(self.plugin, i, epg=True).item)
        self.items.add_item(date_item(self.plugin.epg_date(date), self.plugin.get_next_day(self.plugin.epg_date(date))))
        self.items.list_items(upd=update, epg=True)

    def play(self, data):
        if data.get('stream'):
            for i in data['stream']:
                path = data['stream'][i].replace('desktop','wired50')
                break
            key = data['license_key']
            self.items.play_item(path, key)

    def license_renewal(self, license_key):
        self.items.add_token(license_key)