def take(self, arg): # FUNCTIONNAL """ Parameters ---------- arg : list of items to take, possibly one element """ try: if len(worldRooms[self.location][GROUND]) == 0: print('There is no item to take here.') else: # if no arguments if arg == '': print( 'What do you want to take ? type "look" to see what is on the ground.' ) elif arg == 'all': old_ground = [] for i in worldRooms[self.location][GROUND]: if self.weight( ) + worldItems[i][WEIGHT] <= self.capacity: taken_item = item(i, **worldItems[i]) self.inventory.append(taken_item) old_ground.append(taken_item) print(i, 'added to your inventory.') else: print('Your inventory is full !') for i in old_ground: worldRooms[self.location][GROUND].remove(i.name) else: # transform input into list filled with items to take temp = ["".join(i) for i in arg] if temp[-1] == ',': temp.pop( ) # remove the last automatic',' from user input items_to_take_names = "".join(temp).split(', ') for i in items_to_take_names: try: if worldItems[i][WEIGHT] + self.weight( ) <= self.capacity: self.inventory.append(item(i, **worldItems[i])) worldRooms[self.location][GROUND].remove(i) print(i, 'added to your inventory.') else: print('Your inventory is full !') return except: print( '\nSome items do not exist or are not in the room.' ) except: print('There is no item to take here.' ) # in case no GROUND key in the dictionnary
def drop(self, arg): """Remove items from the inventory and leave them on the current room's ground""" if (len(self.inventory)) == 0: print('You have nothing to drop, your inventory is empty.') else: if arg == '': print('What do you want to drop ?') elif arg == 'all': for i in self.inventory: worldRooms[self.location][GROUND].append(i.name) self.inventory.clear() print('You have emptied your bag on the ground.') else: # transform input into list filled with items to take temp = ["".join(i) for i in arg] if temp[-1] == ',': temp.pop() # remove the last ',' from user input items_to_drop_names = "".join(temp).split(', ') for i in items_to_drop_names: try: item_to_drop = item(i, **worldItems[i]) self.inventory.remove(item_to_drop) worldRooms[self.location][GROUND].append( item_to_drop.name) print(i, 'dropped.') except: print(i, 'is not in your inventory.')
def equip(self, arg: item): if arg == '': print( 'What do you want to equip ? Use "inv" to see your inventory.') else: try: # lines 408 -> 412 transform input into list filled with items (objects) to equip temp = ["".join(i) for i in arg] if temp[-1] == ',': temp.pop() # remove the last comma from user input items_name = "".join(temp).split(', ') items_to_equip = [item(i, **worldItems[i]) for i in items_name] for i in items_to_equip: if worldItems[i.name][TYPE] == 'Weapon': self.weapon = i self.inventory.remove(i) print(i, 'equiped.') elif worldItems[i.name][TYPE] == 'Panoply': self.panoply = i self.inventory.remove(i) print(i, 'equiped.') else: print(i, 'cannot be equiped.') except: print('Some item(s) do not exist.')
def agregarItem(self): #Esta funcion crea un objeto item, comprueba si esta en el array y si no esta lo anade y devuelve el array de items FUNCIONANDO # esto comprobamos si tiene coma y la convertimos a punto: if "," in str(self.precio_item.text()): nprec = str(self.precio_item.text()) nprec = nprec.replace(",", ".") self.precio_item.setText(nprec) # comprobamos si el resultado es un int o un float, sino tiramos error: chequeo = self.precio_item.text() try: int(chequeo) valido = True except ValueError: try: float(chequeo) valido = True except ValueError: print "El numero no es un valor numerico" valido = False if valido: item1 = item(self.newti.text(), self.precio_item.text()) #w: item_db = shelve.open("items.db") item_db[str(item1.getTipo())] = item1 item_db.close() #actualizamos combobox cliente: self.updateComboI(item1.getTipo())
def breakdown(element): name = element.find('span', {'class':"market_listing_item_name"}).encode_contents(encoding="ascii").decode('utf-8') quant = element.find('span',{'class': "market_listing_num_listings_qty"}).encode_contents(encoding="ascii").decode('utf-8') price = element.find('span', {'class':"market_table_value normal_price"}).contents[3].encode_contents(encoding="ascii").decode('utf-8') return item(name,quant,price)
def getSkinEarnItems(query): page = requests.get(query) obj = json.loads(page.text) results = [] for elm in obj['items']: results.append(item(elm['name'],1,elm['price'])) return results
def set_item(e): global xOffset global yOffset global ItemType p2y = get_canvas_height() - e.y t = item(e.x + xOffset, p2y + yOffset, ItemType) gfw.world.add(gfw.layer.item, t)
def __init__(self, row): items = [] for i in row[5][2:-2].split("}, {"): id = {} for x in [x.strip().split(":") for x in i.split(",")]: id[x[0]] = x[1].strip() items.append( item(id["itemId"], id["stackCount"], id["category"], id["subCategory"], id["attachedItems"]))
def __init__(self, row): self.id = row[0] gameEvent.__init__(self, row[1], row[2], row[8], row[9], row[10], row[11]) self.attacker = player(row[2], row[3], row[4], row[5], row[6]) #have a person object instead? self.victim = player(row[7], row[8], row[9], row[10], row[11]) self.damage = damage(row[12], row[13], 0, row[14]) self.item = item(row[15], row[16], row[17], row[18], row[19]) self.distance = row[20]
def test_red_feather(self): # [1] """ We can create a red feather """ created_item = item( collection_id = 1, # arbitrary variant = 15, # feather variant 15 should is the red one item = "feather", spawn=True) self.assertEqual(returned_item.color, red)
def volcarItems(self): # dependiendo de si el item tiene cantidad o no if self.boxitems.currentIndex() != -1: # si no tiene cantidad pillamos la de por default del constructor if not self.cantidad.text(): item1 = item( str(self.boxitems.currentText()),str(self.precio_item.text())) else: # sino creo el objeto con su cantidad dada por el user item1 = item( str(self.boxitems.currentText()),str(self.precio_item.text()),str(self.cantidad.text()) ) # comprobacion para que no se repitan items: if not self.total_items: self.total_items.append(item1) else: indice = 0 existe = False while (not existe and indice < len(self.total_items)): if item1.getTipo() == self.total_items[indice].getTipo(): # si EXISTEN coincidencias es True existe = True else: existe = False # si NO existe coincidencias es False indice += 1 if not existe: self.total_items.append(item1) else: if not self.cantidad.text(): self.cantidad.setText(str(item1.getCantidad())) else: self.total_items[indice-1].setCantidad(self.cantidad.text()) # aprovechamos el indice para usar y sacaar el id del ultimo elemento valido. El -1 es por que se ha iterado una vez de mas. self.cantidad_ro.setText(str(item1.getCantidad())) # actualizamos el read only de cantidad de abajo self.precio_fac.setText(str(item1.getPrecio())) self.cantidad.setText("") #Limpio el texto de la cantidad introducida, a ver si se ve mas limpio :D self.itemfac.clear() for i in self.total_items: self.itemfac.addItem(i.getTipo()) index = self.itemfac.findText( str( self.boxitems.currentText() ))# busco el nf para obtener el index self.itemfac.setCurrentIndex(index) # seteo por index for pepe in self.total_items: print pepe.getPrecio()
def enter(): global map gfw.world.init(['item', 'platform']) with open(map, 'r') as fp: data = json.load(fp) for d in data: t = Tile(d['x'], d['y'], d['sx'], d['sy'], d['isCollision'], d['isFlag']) gfw.world.add(gfw.layer.platform, t) with open(item_map, 'r') as fp: data = json.load(fp) for d in data: i = item(d['x'], d['y'], d['type']) gfw.world.add(gfw.layer.item, i)
def init_game(): window = pygame.display.set_mode(AREA) maze = Maze() maze.create_area() maze.generate_area(window) items = item() items.create_item(maze) items.generate_item(window) hero = Macgyver(INIT_MAC_X, INIT_MAC_Y, MAC, maze) hero.image_hero(MAC) guard = Guardian(GUARDIAN, maze) guard.generate_guardian(window) return window, maze, items, hero, guard
def enter(): gfw.world.init(['bg', 'effect', 'platform', 'item', 'bullet', 'player', 'ui']) global t_max_x t_max_x = 0 global t_max_y t_max_y = 0 global isPaused isPaused = False global stage with open("map_data/Stage" + str(stage) + ".json", 'r') as fp: data = json.load(fp) for d in data: t = Tile(d['x'], d['y'], d['sx'], d['sy'], d['isCollision'], d['isFlag']) gfw.world.add(gfw.layer.platform, t) if t.pos[0] > t_max_x: t_max_x = t.pos[0] if t.pos[1] > t_max_y: t_max_y = t.pos[1] with open("map_data/Stage" + str(stage) + "_item.json", 'r') as fp: data = json.load(fp) for d in data: i = item(d['x'], d['y'], d['type']) gfw.world.add(gfw.layer.item, i) global player player = Player(t_max_x, t_max_y) gfw.world.add(gfw.layer.player, player) bg = Background('bkMoon.png', t_max_x, t_max_y) gfw.world.add(gfw.layer.bg, bg) global stime stime = time.time() global font font = gfw.font.load(res('ENCR10B.TTF'), 30) global timer timer = Timer(canvas_width - 20, canvas_height - 50) gfw.world.add(gfw.layer.ui, timer) global bgm bgm = load_music('sound/bgm_' + str(random.randint(1, 3)) + '.ogg') bgm.set_volume(50) bgm.repeat_play()
def multilist_sort(head, lor, p): # 用表头指代链表,lor表示key分布范围长度, # p为用于排序的表的个数 m = lor // p r = head.next tl = [item(0, 0) for i in range(p)] num1 = 0 num2 = 0 #num1统计移动次数,num2统计比较次数 while r != None: rc = r r = r.next for i in range(p): if 1 + m * i <= rc.key <= m * (1 + i): h = tl[i] while True: if h.next == None: h.next = rc rc.next = None num1 += 2 break elif h.next != None and rc.key >= h.next.key: h = h.next num2 += 1 else: h1 = h.next h.next = rc rc.next = h1 num1 += 2 num2 += 1 break break head = tl[0] r1 = head i = 1 while i < p: if r1.next != None: r1 = r1.next else: r1.next = tl[i].next i += 1 num1 += 1 # 此时已经生成了以head为表头的排序结果(仍为链表) # 可以在此处增加语句对于排序结果进行更多操作 return num1, num2
def read_item(): f = open("item.txt", encoding='UTF8') item_list = [] line = f.readline() while line: sep = '\t' att_list = line.strip().split(sep) new_item = item(att_list[0], att_list[1], att_list[2], att_list[3], att_list[4], att_list[5], att_list[6], att_list[7], att_list[8], att_list[9]) item_list.append(new_item) line = f.readline() f.close() print(len(item_list), 'item readed from file.') return item_list
def unequip(self, arg: item): if self.weapon is None and self.panoply is None: print('You do not have any equipment at the moment.') elif arg == 'all': if self.weapon is not None: self.inventory.append(self.weapon) print(self.weapon, 'unequiped.') self.weapon = None if self.panoply is not None: self.inventory.append(self.panoply) print(self.panoply, 'unequiped.') self.panoply = None else: try: # lines 408 -> 412 transform input into list filled with items (objects) to unequip temp = ["".join(i) for i in arg] if temp[-1] == ',': temp.pop() # remove the last comma from user input items_name = "".join(temp).split(', ') items_to_unequip = [ item(i, **worldItems[i]) for i in items_name ] for i in items_to_unequip: if i.type == 'Panoply': if self.panoply is not None: self.inventory.append(i) print(i, 'unequiped.') self.panoply = None elif i.type == 'Weapon': if self.weapon is not None: self.inventory.append(i) print(i, 'unequiped.') self.weapon = None else: print(i, 'is not equiped at the moment') except: print('Some item(s) do not exist or are not in your stuff.')
def sell(self, arg): """sell items to specific NPC.""" if self.host != '': if arg == '': print('What do you want to sell ?') elif arg == 'all': sold_items = [] for i in self.inventory: worldNpcs[self.host][STOCK].append(i.name) sold_items.append(i) self.gold += worldItems[i.name][SELL_PRICE] print(i.name +' sold for ' + BYELLOW + str(worldItems[i.name][SELL_PRICE]) + \ ' gold.' + RESET + GREEN + PLUS +RESET) for i in sold_items: self.inventory.remove(i) else: # lines 334 -> 335 transform input into list filled with items' names temp = ["".join(i) for i in arg] if temp[-1] == ',': temp.pop() # remove the last ',' from user input items_to_sell_names = "".join(temp).split(', ') for i in items_to_sell_names: try: item_to_sell = item(i, **worldItems[i]) self.inventory.remove(item_to_sell) worldNpcs[self.host][STOCK].append(item_to_sell.name) self.gold += worldItems[i][SELL_PRICE] print(i +' sold for ' + BYELLOW + str(worldItems[i][SELL_PRICE]) +\ ' gold.' + RESET + GREEN + PLUS + RESET) except: print(i, 'is not in your inventory.') else: print( 'You need to be talking to a NPC to sell items. Use "look" to see present NPCs.' )
def store_management(self): if ( isinstance( menu.__current_user, employee ) ): return ("No authorised!") elif ( isinstance( menu.__current_user, manager ) ): # choose = input("what would you want do?\n1.add item\n2.delete item\n3.modify item\n4.search item\n5.sale") try: # add if (int(choose) == 1): barcode = input("Please type the barcode:") name = input("Please type the name:") saleprice = input("Please type the sale price(number only):") original_price = input("Please type the original price(number only):") month = input("Please type the month for when the item is stored( from 1 ~ 12):") quantity = input("Please type the quantity(number only):") new_item = item(name, float(saleprice), float(original_price), int(month), int(quantity)) inventory().add(barcode, new_item) # delete elif (int(choose) == 2): name = input("Please type the barcode or name of item you want to delete:") inventory().delete(name) # modify elif (int(choose) == 3): name_mod = input("Please item the barcode or name you want to modify:") sel = input("Which part would you want to modify?") pass # search elif (int(choose) == 4): name = input("Please type barcode or name you want to search:") item = inventory().search(name) print(item) except Exception as e: print(type(e)) print(e.args) print(e)
def __init__(self,row): gameEvent.__init__(self, row[1], row[0], row[2], row[3], row[4], row[5]) self.item = item(row[6],row[7],row[8],row[9],row[10])
def mainFunc(): #--- --- --- --- --- --- Instantiating Player --- --- --- --- --- --- prot = player(requestString("Please enter your character name.")) #--- --- --- --- --- --- Instantiating Items --- --- --- --- --- --- itemKnife = item(1,"Knife", "A long jagged knife stained with blood from previous uses!") itemKey = item(2,"Key","A key which glows bright red.\nIt might fit that lock in the main room!") #--- --- --- --- --- --- Instantiating Rooms --- --- --- --- --- --- # Entrance roomEntrance = room("Empty Room","To the north you spot a decrepit door sitting in the pale light of a dying torch. " + \ "As you approach, the smell of decay intensifies and you can't help but fear what may be waiting " + \ "for you on the other side. With no other exits in sight, do you choose to move forward?") # Inner Chamber roomChamber = room("Inner Chamber", "Upon entering the room the smell of decaying flesh burns through your nose and fills your " + \ "lungs like a fire consuming a house. In the center of the room stands a single lamp, giving off an eerie " + \ "red glow. The lamp appears to cast living shadows upon the walls. As you cautiously approach the light you " + \ "can't help but notice a faint thump getting louder as the lamp gets closer. Upon reaching the lamp you realize " + \ "the cause of the thumping sound is liquid dripping on to the lamp. You reach and touch the lamp only to " + \ "increased your own dread; the lamp is soaked in blood. With your heart pounding you take swift look around and " + \ "notice there are three doors, all leading in opposite directions. Which door do you choose to open first: " + \ "north, east, or west?") # Secret Room roomSecret = room("The Pit", "You have found some sort of a hidden room behind the painting; hope begins to build that this could " + \ "lead to a way out of this nightmare. After completely entering the room you realize there is no " + \ "source of light other than what is bleeding in from the fire behind you. You step to the side to allow more light in " + \ "to penetrate the darkness and lose your footing. As you had hoped this room was the end to the nightmare... Just not the " + \ "end you were praying for. You have fallen to your death.") # Knife Room roomKnifeBaseDescription = "You immediately notice the warmth of a fire upon your skin as you walk through the door's threshold. " + \ "You begin to feel yourself naturally relax as a result of the fire. This quickly dissipates as you take a look around " + \ "to see the room is decorated with devices that could serve no other purpose than torture. Directly across from you to " + \ "the west, next to the fire, is a single table lined with assorted tools. Looking to the north you notice yet another " + \ "door, meaning a continuation to the nightmare." roomKnife = room("Torture Chamber", roomKnifeBaseDescription + " To the south nothing immediately catches your eye; however, after a " + \ "second look you can't help but notice an elaborate painting of a lovely woman dancing under a pale moon's light.") # Developer Credits Room roomCredits = room("Developer's Shrine", "In the back wall of the room to the North, you see some sort of strange writing. As you approach, " + \ "your heart begins to drop and you feel sick to your stomach as you find that your earlier assumption was correct; you are " + \ "part of a sinister game. All is not lost... if this is a game then there must be a way to win!") # Bear Room roomBearBaseDescription = "Natural light seems for fill this room and you hope this is your exit. You follow the light to find the source is " + \ "an opening high in the ceiling, but you see no way to climb up to it." roomBear = room("Guardian's Quarters",roomBearBaseDescription + " Directly across from you to the east, you see a door which " + \ "appears to be blocked by a monstrous bear. To your relief the animal is asleep, but you will need some sort of weapon to get " + \ "past. To the north you spot a small opening which may contain an answer.") # Riddle Room roomRiddle = room("Prisoner's Cell", "You enter what appears to be a forgotten room. Old spider webs fill the dark crevices and thick carpet of dust " + \ "has collected on the stone floor. On the far wall you see an odd plaque with something written on it but you cannot make out " + \ "what written from this distance. Perhaps you should take a closer look.") # Password Room roomPassword = room("Chamber of Whispers", "You finally reach an opening after what seemed to be an eternity traveling through a lightless tunnel. " + \ "A soft glow radiates from the center of the room with no obvious cause as to where the source of the light is. You slowly " + \ "and very cautiously approach. Once at the soft glow you are able to look at the rest of the room more clearly. " + \ "All around the room you see the remains of what appears to be those that have come before for you. Nothing else stands out, " + \ "so perhaps you should inspect the light further.") # Victory Room roomVictoryBaseDescription = "After placing the key in the lock, the door seems to have taken a hold of it on its own. It's as if it has been " + \ "waiting for this moment for an eternity, like a hungry animal that has been given a scrap of food." roomVictory = room("Exit", roomVictoryBaseDescription + " Speaking of hungry animals, it seems the bear in the next room has awoken. You are not " + \ "able to get the door open before the ravenous bear is upon you.") #--- --- --- --- --- --- Add Inspectable Items --- --- --- --- --- --- --- # Bear in Guardian's Quarters; inspecting will kill the bear if the player has a knife, creating an East door; also updates victory text def bearDoor(): if prot.searchInventory(1) == true : roomBear.setExit("EAST", roomRiddle) roomBear.setDescription(roomBearBaseDescription + " To the east, there is the carcass of a bear near a door. " + \ "To the north you spot a small opening.") roomVictory.setDescription(roomVictoryBaseDescription + " You hear several clicks and slowly the door creeps open. A light so bright " + \ "you have to shield your eyes consumes to blood red glow of the room. Within a couple of seconds you can see " + \ "clearly and walk up long stair case where an open field greets you at the top. You feel the warmth of the " + \ "afternoon sun on your face and realize you have made it out alive.") roomBear.setInspect("BEAR","The bear is quite dead.") roomBear.setInspect("BEAR","The bear sleeps in front of a door and you cannot go through without disturbing it. You need something to kill it.", bearDoor) # Knife on table in Torture Room; inspecting gives the player a knife and changes the bear interaction def tableKnife(): if not prot.searchInventory(itemKnife.getId()): prot.addToInventory(itemKnife) roomKnife.removeInspect("TABLE") roomBear.setInspect("BEAR","You remember the knife in your pocket and quickly use it to kill the sleeping bear. The way east is now clear.",bearDoor) roomKnife.setInspect("TABLE","At the end of the table you spot a long jagged dagger which could be useful in a dangerous situation. You take it.",tableKnife) # Painting on wall of Torture Chamber; inspecting creates a South door def paintingDoor(): roomKnife.setExit("SOUTH", roomSecret) roomKnife.setDescription(roomKnifeBaseDescription + " To the south, behind an elaborate painting of a lovely woman dancing under a pale moon's light, " + \ "there is another door.") roomKnife.setInspect("PAINTING","Upon closer examination you see that the painting is wavering ever so slightly. You step a bit closer " + \ " and feel a cool breeze and the smell of fresh air. You've found a door hidden behind the painting.",paintingDoor) # Inscription on wall in Developer's Shrine roomCredits.setInspect("WALL","The wall reads:\nMatthew Mason - Spinner of Yarns and explorer of Russia\n" + \ "Heather McCabe - Heroine of the Storm and leader of our company\n" + \ "Jason Lloyd - Slayer of Pythons and master of all things logistical\n" + \ "Brett Hansen - He's pretty cool too I guess") # Plaque in Prisoner's Cell; inspecting prompts the player to solve a riddle def riddle(): printNow("The plaque reads: 'It has a white light at the end of it and can be over in the blink of an eye. If you have seen " + \ "our secret, you know its value. What do I speak of?") riddleGuess = requestString("Speak the answer to the riddle: ") if riddleGuess == None: # Cancel printNow(">> Unsure, you step away from the plaque.") return elif riddleGuess.upper() == "LIFE": # Correct answer printNow(">> You speak confidently: 'LIFE'") printNow("You are suddenly certain that the phrase 'password1234' is important.") else: # Incorrect answer printNow(">> You speak confidently: '" + riddleGuess.upper() + "'") printNow ("Nothing happens. Your answer must have been incorrect.") roomRiddle.setInspect("PLAQUE", "", riddle) # Light in Chamber of Whispers; inspecting prompts the player to provide the password which will give player a key def password(): printNow("Suddenly, hundreds of voices begin to talk all at the same time. Through the commotion you cannot make out what they are saying. " + \ "Just before it goes silent you hear a whisper: 'Give us the password to receive our treasure...'") passwordGuess = requestString("State the password:"******">> Unsure, you back away slowly.") elif passwordGuess == "password1234": # Correct answer prot.addToInventory(itemKey) printNow(">> You speak confidently: '" + passwordGuess + "'") printNow( "A key suddenly appears in your pocket.") else: # Incorrect answer printNow(">> You speak confidently: '" + passwordGuess + "'") printNow ("The voices shriek: 'Leave us and return when you know the password!'") roomPassword.setInspect("LIGHT", "", password) #--- --- --- --- --- --- Add Initial Exits --- --- --- --- --- --- # Empty Room roomEntrance.setExit("NORTH", roomChamber) # Inner Chamber roomChamber.setExit("EAST", roomBear) roomChamber.setExit("SOUTH", roomEntrance) roomChamber.setExit("WEST", roomKnife) roomChamber.setExit("NORTH", roomVictory) # Torture Chamber roomKnife.setExit("NORTH", roomCredits) roomKnife.setExit("EAST", roomChamber) # Developer's Shrine roomCredits.setExit("SOUTH", roomKnife) # Guardian's Quarters roomBear.setExit("WEST", roomChamber) roomBear.setExit("NORTH", roomPassword) # Chamber of Whispers roomPassword.setExit("SOUTH",roomBear) # Prisoner's Cell roomRiddle.setExit("WEST", roomBear) #--- --- --- --- --- --- Add Map Print Function --- --- --- --- --- # Get list of room names roomList = [roomEntrance.getName(), roomKnife.getName(),roomChamber.getName(),roomBear.getName(), roomRiddle.getName(), roomCredits.getName(), roomVictory.getName(),roomPassword.getName()] #set flags for rooms visited roomFlags = [false, false, false, false, false, false, false, false] # Print map of dungeon; [_] indicates visited room, [X] indicates current location def printMap(): # Map lines with northern-most point at level three levelOne = "" levelTwo = "" levelThree = "" # Loop through flags list, setting lines to print for all levels for key in range(0, len(roomFlags)): # Level one is southern-most point and single room set (special case) if key in range(0,1): if currRoom.getName() == roomList[key]: levelOne = " [X]" elif roomFlags[key] == true: levelOne = " [_]" # Level two is comprised of middle rooms elif key in range(1, 5): if currRoom.getName() == roomList[key]: levelTwo += "[X]" elif roomFlags[key] == true: levelTwo += "[_]" else: levelTwo += " " # Level three is comprised of northern-most rooms elif key in range(5,len(roomFlags)): if currRoom.getName() == roomList[key]: levelThree += "[X]" elif roomFlags[key] == true: levelThree += "[_]" else: levelThree += " " # Print map by line with northern-most point at level three printNow("----- MAP -----\n" + levelThree+"\n"+levelTwo+"\n"+levelOne) #--- --- --- --- --- --- Add Directions Function --- --- --- --- --- def getDirections(): directionString = "You may move in these directions: " if (currRoom.getExit("NORTH")!= false): directionString = directionString + "[NORTH] " if (currRoom.getExit("EAST")!= false): directionString = directionString + "[EAST] " if (currRoom.getExit("SOUTH")!= false): directionString = directionString + "[SOUTH] " if (currRoom.getExit("WEST")!= false): directionString = directionString + "[WEST] " return directionString #--- --- --- --- --- --- Main Code Segment --- --- --- --- --- --- # Global variable initialization victoryFlag = false # This flag will be flipped when player reaches victory room currRoom = roomEntrance # currRoom contains current location of player character # Print starting Description lineSeparator = "===============================================\n" printNow("You awaken from a dream you cannot remember in an unfamiliar setting. As you wait for your eyes to " + \ "adjust you can't help but notice the pungent sent of decay lingering in the air. You immediately begin " + \ "to feel a chill running down your spine as the realization hits that you may be part of some sinister game.") printNow("(type HELP if you have any questions)\n") printNow(lineSeparator) printNow("Current Location: " + roomEntrance.getName()) printMap() printNow(roomEntrance.getDescription()) # Main game loop; will loop until the player dies, exits, or reaches victory room while(victoryFlag == false): # Set victory flag and break if the player is in the victory room if (currRoom.getName() == roomVictory.getName() and prot.searchInventory(2) == True): # Only win if the bear isn't alive still if roomBear.getExit("EAST") != False: victoryFlag = True break # Break if the player is in the secret room elif (currRoom.getName() == roomSecret.getName()): break # Get player command input (cmd, args) = getUserInput() # Handle MOVE command if (cmd == "MOVE"): nextRoom = currRoom.getExit(args) # Invalid direction/no room in that direction if (nextRoom == false): printNow("That's not a valid direction. " + getDirections()) continue # Victory room is locked elif (nextRoom.getName() == roomVictory.getName() and prot.searchInventory(2) == false): printNow("You don't have the key for that door.") continue # Change room, update map and print new description else: # Set flag for room visited for i in range(0,len(roomList)): if currRoom.getName() == roomList[i]: roomFlags[i] = true # Print description and map printNow(">> You boldly move " + args.lower() + " into the next room.") printNow(lineSeparator) currRoom = nextRoom printNow("Current Location: " + currRoom.getName()) printMap() printNow(currRoom.getDescription()) continue # Handle LOOK command (currently disabled) #elif (cmd == "LOOK"): #printNow(">> You look to the " + args.lower() + ".") #printNow(currRoom.getLook(args)) #continue # Handle INSPECT command elif (cmd == "INSPECT"): printNow(">> You inspect the " + args.lower() + ".") inspectDescription = currRoom.getInspect(args) if inspectDescription != "": printNow(inspectDescription) continue # Handle TAKE command elif (cmd == "TAKE"): canTakeItem = currRoom.takeItem(args) if canTakeItem: prot.addToInventory(item) printNow(">> You take the " + args.lower() + ".") else: printNow("You can't take that.") continue # Handle DIRECTIONS command elif (cmd == "DIRECTIONS"): printNow(getDirections()) # Handle EXIT and HELP requests elif (cmd == "MENU"): if (args == "EXIT"): printNow("\nA grue sneaks up from behind and eats you.") break elif (args == "HELP"): printNow("\n# Commands:") printNow("# MOVE: Lets you move in the cardinal directions. Must be followed by north, south, east or west. Usage: 'move <direction>'") printNow("# INSPECT: Take a closer look at an item. Usage: 'inspect <item>'") printNow("# DIRECTIONS: Get a list of room exits. Usage: 'directions'") #printNow("# LOOK: Take a closer look in a direction. Usage: 'look <direction>'") #printNow("# TAKE: Take an item into your inventory. Usage: 'take <item>'") #printNow("# USE: Use an item in your inventory. Usage: 'use <item>'") printNow("# EXIT: Give up and end your adventure prematurely. Usage: 'exit'") #printNow("# HELP: Bring up this lovely menu. Usage: You really should know this one by now!") printNow("\n") # Handle anything else else: printNow("That's not a valid command.") continue # Declare victory or loss upon exit from the game loop. if (victoryFlag == true): #win showInformation("Way to go, %s!" %prot.getName()) else: #loss showInformation("%s, you are a disgrace to adventurers everywhere!\nThis dungeon is saddened by your patheticness!" %prot.getName())
def __init__(self): pygame.init() #start up pygame self.window = pygame.display.set_mode( (640, 790)) #set window size to 512, 512 pygame.display.set_caption("Search") #title window pygame.key.set_repeat(1, 80) import objects self.all_sprites = pygame.sprite.Group() self.all_tiles = pygame.sprite.Group() self.active_tiles = pygame.sprite.Group() self.inventoryWindow = pygame.sprite.Group( ) #create a sprite group for the inventory window self.doors = pygame.sprite.Group() self.active_doors = pygame.sprite.Group( ) #make sprite group for this room's doors that Horace can walk through self.inactive_doors = pygame.sprite.Group( ) #make sprite group for this room's doors that are closed so that they will change appearance but still be drawn (removing them #from self.active_doors won't actually cause them to disappear) self.status_bar = pygame.sprite.Group() self.entities = pygame.sprite.Group() self.props = pygame.sprite.Group() self.active_props = pygame.sprite.Group() self.active_message_boxes = pygame.sprite.Group( ) #sprite group to hold active message boxes self.active_option_boxes = pygame.sprite.Group() self.active_enemies = pygame.sprite.Group() self.title_screen = pygame.sprite.Group() self.minimap_group = pygame.sprite.Group() self.active_ground_items = pygame.sprite.Group() self.message_box_active = False #check if there are active message boxes self.active_battle = pygame.sprite.Group() self.active_enemy_status_bar = pygame.sprite.Group() #for prop in objects.cave_plants: # self.props.add(prop) self.clock = pygame.time.Clock() apple = item( self, 91, 91, "img/items/misc/apple_2.png", 'Apple', 2, 'Here is an unnecessarily long description of an apple. It is entirely to test the function of the textWrapper class', True, 'common', 1) apple2 = item(self, 64, 64, "img/items/misc/apple_2.png", 'Apple', 2, 'Another apple', True, 'common', 1) apple3 = item(self, 64, 64, "img/items/misc/apple_2.png", 'Apple', 2, 'A third apple', True, 'common', 1) broken_gauntlets_statreq = {"STR": 1, "DEX": 0, "AGL": 0, "INT": 0} broken_cuirass_statreq = {"STR": 2, "DEX": 0, "AGL": 0, "INT": 0} broken_gauntlets_elembonus = { "LIGHT": 12, "DARK": 0, "FIRE": 0, "ICE": 0 } broken_cuirass_elembonus = {"LIGHT": 2, "DARK": 3, "FIRE": 0, "ICE": 0} broken_greaves_statreq = {"STR": 0, "DEX": 0, "AGL": 0, "INT": 0} broken_greaves_elembonus = {"LIGHT": 0, "DARK": 0, "FIRE": 0, "ICE": 0} cracked_helmet_elembonus = { "LIGHT": 12, "DARK": 0, "FIRE": 0, "ICE": 0 } cracked_helmet_statreq = {"STR": 0, "DEX": 0, "AGL": 0, "INT": 0} self.broken_gauntlets = Armor(self, "Broken gauntlets", 64, 64, 2, "Plate", broken_gauntlets_elembonus, broken_gauntlets_statreq, "arms", "broken", "gauntlets", 10, "A pair of broken gauntlets") self.broken_cuirass = Armor(self, "Broken cuirass", 64, 64, 3, "Plate", broken_cuirass_elembonus, broken_cuirass_statreq, "torso", "broken", "cuirass", 6, "A broken cuirass.") self.broken_greaves = Armor(self, "Broken greaves", 64, 64, 2, "Plate", broken_greaves_elembonus, broken_greaves_statreq, "legs", "broken", "greaves", 8, "A pair of broken greaves.") self.cracked_helmet = Armor(self, "Cracked helmet", 64, 64, 3, "Plate", cracked_helmet_elembonus, cracked_helmet_statreq, "head", "broken", "helmet", 8, "A cracked helmet.") broken_sword_statreq = {"STR": 2, "DEX": 0, "AGL": 0, "INT": 0} broken_sword_elembonus = {"LIGHT": 5} self.broken_sword = Weapon( self, "Broken sword", 64, 64, "Straight sword", "right", "medium", "piercing", 8, 8, broken_sword_elembonus, broken_sword_statreq, None, None, "broken_sword", 15, "Horace's guardsman's sword. Mostly ornamental, its blade is now broken in two by falling rubble." ) inventory = [ apple, apple2, apple3, self.broken_gauntlets, self.broken_cuirass, self.broken_greaves, self.cracked_helmet, self.broken_sword ] #create very basic inventory array self.player = Player(self, 64, 64, inventory, 50, 50, 20, 20, 3, 5, 5, 3, 5, None, None, None, None, None, None) goblin_targetable_areas = [ "Target: head", "Target: arms", "Target: legs", "Target: torso" ] self.goblin = Enemy(self, self.player, 384, 384, 2, "Goblin", 20, 20, 3, None, None, None, None, "Beast", "goblin", goblin_targetable_areas) self.goblin_2 = Enemy(self, self.player, 256, 384, 2, "Goblin", 20, 20, 3, None, None, None, None, "Beast", "goblin", goblin_targetable_areas) room_1_enemies = [self.goblin, self.goblin_2] self.rightDoor = Door( self, 9, 4, "right", True, "img/tile/chasm/chasm_door_right.png", "img/tile/chasm/chasm_wall_right.png" ) #initialize doors. There will be only four doors, each representing a cardinal direction. A room can have 1-4 doors. self.leftDoor = Door(self, 0, 4, "left", True, "img/tile/chasm/chasm_door_left.png", "img/tile/chasm/chasm_wall_left.png") self.forwardDoor = Door(self, 4, 0, "forward", True, "img/tile/chasm/chasm_door_top.png", "img/tile/chasm/chasm_wall_top.png") self.backwardDoor = Door(self, 4, 9, "backward", True, "img/tile/chasm/chasm_door_bottom.png", "img/tile/chasm/chasm_wall_top.png") self.display_inventory = False #flag to check whether the inventory window is open or not self.z1r1 = Room( self, "base", [self.backwardDoor], "img/tile/chasm/chasm_01.png", "img/tile/chasm/chasm_01_full.png", objects.props_z1r1, room_1_enemies ) #initialize some basic rooms, each with a different background image to tell them apart. #enter a list of doors to represent the doors of the room. self.z2r2 = Room(self, "base", [self.backwardDoor, self.forwardDoor, self.rightDoor], "img/tile/chasm/chasm_01.png", "img/tile/chasm/chasm_01_full.png", objects.props_z1r2, []) self.z3r3 = Room(self, "base", [self.forwardDoor], "img/tile/chasm/chasm_01.png", "img/tile/chasm/chasm_01_full.png", objects.props_z1r3, []) self.z4r4 = Room(self, "base", [self.leftDoor], "img/tile/chasm/chasm_01.png", "img/tile/chasm/chasm_01_full.png", objects.props_z1r4, []) self.ZONE1 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, self.z1r1, 0, 0, 0, 0], [0, self.z2r2, self.z4r4, 0, 0, 0], [0, self.z3r3, 0, 0, 0, 0]] self.battle = False self.titlescreen = TitleScreen(self, 0, 0) self.clock_group = pygame.sprite.Group() #create a 2D array of rooms to represent this zone. #self.currentLocation = #self.z1r1 = Room(self, "base", "door", "img/tile/chasm/chasm_01.png") #create a new Room object (see assets.py) #for x in range(0, 8): # for y in range(0, 8): # self.active_tiles.add(self.z1r1.tiles[x][y]) #fill the active_tiles sprite group with the tiles from the room object #create some random items #messages = ["Yes", "No", None, None] #dialogBox = optionBox(self, 64, 512, self.player, messages, "Will you accept the blessing?") #dialogBox.add(self.active_option_boxes) pygame.font.init() self.clock = pygame.time.Clock() self.prevKey = None self.minimap = Minimap(self, 500, 500, "minimap", self.player)
i = 1 while i < p: if r1.next != None: r1 = r1.next else: r1.next = tl[i].next i += 1 num1 += 1 # 此时已经生成了以head为表头的排序结果(仍为链表) # 可以在此处增加语句对于排序结果进行更多操作 return num1, num2 a0 = item(0, 1000) b0 = item(0, 5000) c0 = item(0, 10000) a, b, c = a0, b0, c0 na = nb = nc = 0 la = [] lb = [] lc = [] while na < 1000: x = randrange(1, 1000 * 100) a.next = item(x, x) a = a.next la.append(a) na += 1
def __init__(self, row): gameEvent.__init__(self, row[1], row[0], row[2], row[3], row[4], row[5]) self.parentItem = item(row[6], row[7], row[8], row[9], row[10]) self.childItem = item(row[11], row[12], row[13], row[14], row[15])
aux_itens = [] numero_do_item = "" print( "Iremos precisar realizar uma busca do(s) produto(s) a serem registrados na compra: " ) while (str.lower(opcao_venda) != "nao" and str.lower(opcao) != "nao"): opcao = "" aux_produto = buscarProduto(produtos) if (aux_produto != False): quantidade_produtos = input( "Quantos produtos desse mesmo tipo foram comprados? ") aux_num = input( "Por favor, digite agora o número de registro do item: " ) aux_item = item(aux_produto, quantidade_produtos, aux_num) aux_itens.append(aux_item) opcao_venda = input( "Registro de item feito com sucesso! Deseja registrar outro item? (SIM ou NAO): " ) else: while (str.lower(opcao) != "sim" and str.lower(opcao) != "nao"): opcao = input( "Para registrar uma compra é necessário que o produto esteja cadastrado, deseja tentar novamente? (SIM, NAO): " ) if (str.lower(opcao) != "sim" and str.lower(opcao) != "nao"): input( "Por favor, escolha uma das opções dadas! (Pressione ENTER para continuar...)" )
def store_management_add( self,name,saleprice,original_price,month,quantity ): new_item = item(name, float(saleprice), float(original_price), int(month), int(quantity)) inventory().add(barcode, new_item)
def main(self): global FRAME #sprite 그룹 생성 #충돌 검사를 위해 self.all_sprites = pygame.sprite.Group() self.platforms = pygame.sprite.Group() self.remove_platform_ = pygame.sprite.Group() self.player_group = pygame.sprite.Group() self.button = pygame.sprite.Group() self.dino_group = pygame.sprite.Group() self.arrow_sprites = pygame.sprite.Group() pygame.init() #sprite 그룹에 추가할 sprite 선언 self.player1 = Player((self.width / 2, self.height / 2), self) self.button_ = button_image(self) self.dino_1 = Dino(self, 100, 125) #100,125 self.arrow_trap1 = arrow(self, 700, 80) self.arrow_trap2 = arrow(self, 100, 470) self.arrow_trap3 = arrow(self, 500, 550) self.arrow_trap4 = arrow(self, 150, 330) self.arrow_trap5 = arrow(self, 300, 450) #sprite 그룹에 sprite 추가 self.all_sprites.add(self.player1) self.player_group.add(self.player1) self.platforms.add(self.button_) self.dino_group.add(self.dino_1) self.arrow_sprites.add(self.arrow_trap1, self.arrow_trap2, self.arrow_trap3, self.arrow_trap4, self.arrow_trap5) #배경 벽 불러옴 for plat in PlatformList: p = Platform(*plat) self.all_sprites.add(p) self.platforms.add(p) for plat in remove_platform: p = platform_remove(*plat) self.remove_platform_.add(p) #선언 및 초기화 fire_trap = bomb(self) detect_button = button_detect() background_ = background(self.width, self.height) item_ = item(self) self.shot_ = shot(self.screen, self) item_.item_display(self.screen) #아이템은 사라질 수 있으므로 while 밖 face = face_recog.face(self) while True: while (face.cap.isOpened()): time = self.clock.tick(60) FRAME += 1 self.screen.fill((255, 193, 158)) #배경 background_.background(self.screen) # trap1.trap_draw(self.screen,self.fire_rect) #폭탄제어 fire_trap.bomb_draw(self.screen, self.fire_rect) #버튼제어 self.button_.button_draw(self.screen) detect_button.detect(self.screen, self) #창살제어 self.arrow_trap1.arrow_player_detect() #공룡제어 if self.DINO_alive == True: self.dino_1.update(self.screen) #공격제어 self.shot_.shooting() self.shot_.shoot_dino(self) self.event() self.all_sprites.update() #플레이어가 창 밖으로 나가지 못하게 if self.player1.rect.right > WIDTH: self.player1.rect.right = WIDTH if self.player1.rect.left < 0: self.player1.rect.left = 0 self.all_sprites.draw(self.screen) if self.BUTTON_ON == False: self.remove_platform_.draw(self.screen) mouthOpen = face.face_recognition(self.screen) item_.item_eat_red2(self.screen, mouthOpen) item_.item_eat_red3(self.screen, mouthOpen) item_.item_eat_red4(self.screen, mouthOpen) item_.item_eat_red1(self.screen, mouthOpen) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0)
def look(self): """Display infos about the current location : current room description, takeable items, present npcs and possible exits.""" # highlighted location name loc = self.location print(INVERTED + BOLD + loc.upper() + RESET) if loc in worldRooms: # description of the room print('\n'.join(textwrap.wrap(worldRooms[loc][DESC], SCREEN_WIDTH))) print() # Takeable items (items on the ground) print(INVERTED + BOLD + 'TAKEABLE ITEMS :' + RESET) try: L = [] ground = worldRooms[loc][GROUND] if len(ground) > 0: for items in ground: l = [] i = item(items, **worldItems[items]) l.extend([i, i.grounddesc]) L.append(l) headers = ['Name', 'Description'] print(columnar(L, headers, no_borders=True, justify=['r', 'l'])) except: print('None\n') # Present NPCs print(INVERTED + BOLD + 'PRESENT NPC(S) :' + RESET) try: L = [] npcs = worldRooms[loc][NPC] if len(npcs) > 0: for npc in npcs: l = [] l.extend([npc, worldNpcs[npc][TYPE]]) L.append(l) headers = ['Name', 'Type'] print(columnar(L, headers, no_borders=True)) except: print('None\n') # All possible exits with associated room exits = [] for direction in { NORTH, SOUTH, EAST, WEST, NORTHEAST, NORTHWEST, SOUTHEAST, SOUTHWEST }: if direction in worldRooms[loc].keys(): exits.append( [direction.upper(), worldRooms[loc][direction]]) print(INVERTED + BOLD + 'POSSIBLE PATHS :' + RESET) headers = ['Direction', 'Room'] print(columnar(exits, headers, no_borders=True)) else: print('There is no information about this room.')
def buy(self, arg): """buy items to specific NPC.""" if self.host != '': if arg == '': print('What do you want to buy ? Use "shop" to see ' + BGREEN + self.host + RESET + ' \'s shop.') elif arg == 'all': items_to_buy_names = [] for i in worldNpcs[self.host][STOCK]: if worldItems[i][BUY_PRICE] <= self.gold: if worldItems[i][WEIGHT] + self.weight( ) <= self.capacity: self.inventory.append(item(i, **worldItems[i])) items_to_buy_names.append(i) self.gold -= worldItems[i][BUY_PRICE] print(i + ' bought for ' + BYELLOW + str(worldItems[i][BUY_PRICE]) + ' gold.' + RESET + RED + MINUS + RESET) else: print(i, 'is too heavy. You cannot buy it.') else: print(i, 'is too expensive. You need', worldItems[i][BUY_PRICE] - self.gold, 'more gold to buy it.') for i in items_to_buy_names: worldNpcs[self.host][STOCK].remove(i) else: # lines 378 -> 380 transform input into list filled with items' names temp = ["".join(i) for i in arg] if temp[-1] == ',': temp.pop() # remove the last ',' from user input items_to_buy_names = "".join(temp).split(', ') for i in items_to_buy_names: #try: if self.gold >= worldItems[i][BUY_PRICE]: if worldItems[i][ WEIGHT] <= self.capacity - self.weight(): worldNpcs[self.host][STOCK].remove(i) self.inventory.append(item(i, **worldItems[i])) self.gold -= worldItems[i][BUY_PRICE] print(i + ' bought for ' + BYELLOW + str(worldItems[i][BUY_PRICE]) + ' gold.' + RESET + RED + MINUS + RESET) else: print( i + ' exceeds your inventory capacity. Transaction cancelled.' ) else: print('You cannot buy ' + i + '. You need ' + BYELLOW + str(int(worldItems[i][BUY_PRICE]) - self.gold) + ' gold.' + RESET) # except: # print('Some item(s) do no exist or are not in the shop.') else: print( 'You need to be talking to a NPC to buy items. Use "look" to see present NPCs.' )
def main(self): global GAME_OVER_FIRE,GAME_OVER_ARROW,GAME_OVER_MOVING_ARROW,GAME_END #spite_group 정의 self.all_sprite=pygame.sprite.Group() self.player_sprite=pygame.sprite.Group() self.arrow_sprites=pygame.sprite.Group() self.dino_group1=pygame.sprite.Group() self.dino_group2=pygame.sprite.Group() #초기화 FPS=30 clock = pygame.time.Clock() self.background_=background() #sprite 아닌 background teleport_=teleport(self) #teleport box_1=box1() #box1 box_2=box2() #box2 box_3=box3() #box3 fire_bomb1=bomb(self) #폭탄1 fire_bomb2=bomb(self) #폭탄2 fire_bomb3=bomb(self) #폭탄3 self.shot_=shot(self) #총알 self.moving_arrow_1=moving_arrow() #움직이는 창살 #공룡 self.dino_1=Dino(self,2500,290) self.dino_2=Dino(self,3000,290) #아이템 self.item1=item(self) self.item2=item(self) self.item3=item(self) self.item4=item(self) self.item5=item(self) self.item6=item(self) self.item7=item(self) self.item8=item(self) self.item9=item(self) self.item10=item(self) self.item11=item(self) self.item12=item(self) #창살 self.arrow_trap1=arrow(self,360,620,0) self.arrow_trap2=arrow(self,1840,1420,0) self.arrow_trap3=arrow(self,1880,1420,0) self.arrow_trap4=arrow(self,1920,1420,0) self.arrow_trap5=arrow(self,1960,1420,0) self.arrow_trap6=arrow(self,2000,1420,0) self.arrow_trap7=arrow(self,2040,1420,0) self.arrow_trap8=arrow(self,2080,1420,0) self.arrow_trap9=arrow(self,2120,1420,0) self.arrow_trap10=arrow(self,2160,1420,0) self.arrow_trap11=arrow(self,2200,1420,0) self.arrow_trap12=arrow(self,2240,1420,0) self.arrow_trap13=arrow(self,2280,1420,0) self.arrow_trap14=arrow(self,2320,1420,0) #버튼 self.button_detect_1=button_detect() #버튼 바꼈는지 확인 self.button1=button_image(self) #버튼 눌렸을 때 이미지 바꿔줌 #캐릭터 따라오는 불 self.fire_enemy=following_fire() #레벨,플레이어,배경sprite level = Level("level1") level.create_level(0,0,self) self.world = level.world self.player = level.player #sprite 그룹에 sprite 추가 self.arrow_sprites.add(self.arrow_trap1,self.arrow_trap2,self.arrow_trap3,self.arrow_trap4,self.arrow_trap5,self.arrow_trap6,\ self.arrow_trap7,self.arrow_trap8,self.arrow_trap9,self.arrow_trap10,self.arrow_trap11,self.arrow_trap12,self.arrow_trap13,self.arrow_trap14) self.world.append(self.button1) self.dino_group1.add(self.dino_1) self.dino_group2.add(self.dino_2) #sprite 그룹에 sprite 추가 self.arrow_sprites.add(self.arrow_trap1,self.arrow_trap2) self.world.append(self.button1) #함수정의 pygame.init() self.camera = Camera(self.screen, self.player.rect, level.get_size()[0], level.get_size()[1]) FONT = pygame.font.SysFont("Sans", 20) gameover_=gameover(self.screen,clock,FONT) username_=username(self.screen) face=face_recog.face(self,self.screen) #시간 표시 글자색 TEXT_COLOR=(0,0,0) BG_COLOR=(255,255,255) while True: #print(self.player.rect.x,self.player.rect.y) #Gameover if self.gameStart: gameover_.show_gameover_screen(self.score,self.dir) self.start_time=pygame.time.get_ticks() self.gameStart=False elif GAME_END: self.user_name=username_.show_username_screen(self.score,self.dir) #재초기화 self.up=False self.down=False self.right=False self.left=False self.BUTTON_ON1=False self.fire_enemy.first=True self.all_sprite=pygame.sprite.Group() self.player_sprite=pygame.sprite.Group() self.arrow_sprites=pygame.sprite.Group() self.dino_group1=pygame.sprite.Group() self.dino_group2=pygame.sprite.Group() self.camera = Camera(self.screen, self.player.rect, level.get_size()[0], level.get_size()[1]) #아이템 self.item1=item(self) self.item2=item(self) self.item3=item(self) self.item4=item(self) self.item5=item(self) self.item6=item(self) self.item7=item(self) self.item8=item(self) self.item9=item(self) self.item10=item(self) self.item11=item(self) #sprite 그룹에 sprite 추가 self.arrow_sprites.add(self.arrow_trap1,self.arrow_trap2,self.arrow_trap3,self.arrow_trap4,self.arrow_trap5,self.arrow_trap6,\ self.arrow_trap7,self.arrow_trap8,self.arrow_trap9,self.arrow_trap10,self.arrow_trap11,self.arrow_trap12,self.arrow_trap13,\ self.arrow_trap14) self.world.append(self.button1) self.dino_group1.add(self.dino_1) self.dino_group2.add(self.dino_2) self.box2_hit=False self.box3_hit=False self.start_time=pygame.time.get_ticks() self.gameover=False GAME_OVER_FIRE=False GAME_OVER_MOVING_ARROW=False GAME_OVER_ARROW=False GAME_END=False self.item1.ate=False self.item1.visible=True self.item2.ate=False self.item2.visible=True self.item3.ate=False self.item3.visible=True self.item4.ate=False self.item4.visible=True self.item5.ate=False self.item5.visible=True self.item6.ate=False self.item6.visible=True self.item7.ate=False self.item7.visible=True self.item8.ate=False self.item8.visible=True self.item9.ate=False self.item9.visible=True self.item10.ate=False self.item10.visible=True self.item11.ate=False self.item11.visible=True #레벨,플레이어,배경sprite level.create_level(0,0,self) self.world = level.world self.player = level.player self.background_.ispink=False pygame.init() elif self.gameover or GAME_OVER_FIRE or GAME_OVER_ARROW or GAME_OVER_MOVING_ARROW: gameover_.show_gameover_screen(self.score,self.dir) #재초기화 self.up=False self.down=False self.right=False self.left=False self.BUTTON_ON1=False self.fire_enemy.first=True self.all_sprite=pygame.sprite.Group() self.player_sprite=pygame.sprite.Group() self.arrow_sprites=pygame.sprite.Group() self.dino_group1=pygame.sprite.Group() self.dino_group2=pygame.sprite.Group() #레벨,플레이어,배경sprite level.create_level(0,0,self) self.world = level.world self.player = level.player self.background_.ispink=False pygame.init() self.camera = Camera(self.screen, self.player.rect, level.get_size()[0], level.get_size()[1]) #아이템 self.item1=item(self) self.item2=item(self) self.item3=item(self) self.item4=item(self) self.item5=item(self) self.item6=item(self) self.item7=item(self) self.item8=item(self) self.item9=item(self) self.item10=item(self) self.item11=item(self) #sprite 그룹에 sprite 추가 self.arrow_sprites.add(self.arrow_trap1,self.arrow_trap2,self.arrow_trap3,self.arrow_trap4,self.arrow_trap5,self.arrow_trap6,\ self.arrow_trap7,self.arrow_trap8,self.arrow_trap9,self.arrow_trap10,self.arrow_trap11,self.arrow_trap12,self.arrow_trap13,\ self.arrow_trap14) self.world.append(self.button1) self.dino_group1.add(self.dino_1) self.dino_group2.add(self.dino_2) self.box2_hit=False self.box3_hit=False self.start_time=pygame.time.get_ticks() self.gameover=False GAME_OVER_FIRE=False GAME_OVER_MOVING_ARROW=False GAME_OVER_ARROW=False GAME_END=False self.item1.ate=False self.item1.visible=True self.item2.ate=False self.item2.visible=True self.item3.ate=False self.item3.visible=True self.item4.ate=False self.item4.visible=True self.item5.ate=False self.item5.visible=True self.item6.ate=False self.item6.visible=True self.item7.ate=False self.item7.visible=True self.item8.ate=False self.item8.visible=True self.item9.ate=False self.item9.visible=True self.item10.ate=False self.item10.visible=True self.item11.ate=False self.item11.visible=True #player 좌표 확인 #print(self.player.rect.x,self.player.rect.y) # self.event() #화면 이동 asize = ((self.screen_rect.w // self.background_rect.w + 1) * self.background_rect.w, (self.screen_rect.h // self.background_rect.h + 1) * self.background_rect.h) bg = pygame.Surface(asize) for x in range(0, asize[0], self.background_rect.w): for y in range(0, asize[1], self.background_rect.h): self.screen.blit(self.background, (x, y)) #배경그림 self.background_.background_blit(self) time_spent = self.tps(clock, FPS) self.camera.draw_sprites(self.screen, self.all_sprite) #순간이동 teleport_.sprite_def(self,self.player) if(teleport_.ready==True): teleport_.collide_detect(self) #box제어 box_1.collide_detect(self,self.background_) box_2.collide_detect(self,self.background_) box_3.collide_detect(self,self.background_) #폭탄제어 GAME_OVER_FIRE=fire_bomb1.bomb_draw(self,self.fire_rect1,3) GAME_OVER_FIRE=fire_bomb2.bomb_draw(self,self.fire_rect2,2.5) GAME_OVER_FIRE=fire_bomb3.bomb_draw(self,self.fire_Rect3,3.8) #캐릭터 따라오는 불 제어 if self.player.rect.x>=2200 and self.player.rect.x<=3240 and self.player.rect.y>=560 and self.player.rect.y<=880: GAME_OVER_FIRE=self.fire_enemy.follow(self,self.player.rect.x,self.player.rect.y) self.fire_enemy.count+=1 else: self.fire_enemy.first=True #버튼 제어 self.button_detect_1.detect(self.screen,self) self.button1.button_draw(self) #공룡제어 if self.DINO_alive1==True: self.dino_1.update(self) if self.DINO_alive2==True: self.dino_2.update(self) #공격제어 self.shot_.shooting() self.shot_.shoot_dino1(self) self.shot_.shoot_dino2(self) #창살제어 if self.BUTTON_ON1 is True: self.arrow_sprites.remove(self.arrow_trap3,self.arrow_trap4,self.arrow_trap5,self.arrow_trap6,self.arrow_trap8,self.arrow_trap9,\ self.arrow_trap10,self.arrow_trap11,self.arrow_trap12,self.arrow_trap13,self.arrow_trap14) #움직이는 창살 제어 GAME_OVER_MOVING_ARROW=self.moving_arrow_1.moving_arrow_player_detect(self) GAME_OVER_ARROW=self.arrow_trap1.arrow_player_detect() #문 제어 GAME_END=self.background_.door_open(self) #창살제어 GAME_OVER_ARROW=self.arrow_trap1.arrow_player_detect() #점수 환산 if self.start_time: time_since_enter=pygame.time.get_ticks()-self.start_time message='Score: '+str(time_since_enter)+'ms' self.screen.blit(FONT.render(message, True, TEXT_COLOR), (10, 10)) self.score=time_since_enter #일시정지 버튼 buttonPressed=gameover_.button("Pause",900,0,150,50,(103,153,255),(107,102,255),"paused") #PAUSE 버튼이 눌린 경우 while buttonPressed==2: buttonPressed=gameover_.pausePressed() if buttonPressed==1: self.gameover=True break #얼굴인식 mouthOpen=face.face_recognition(self.screen) eyebrow=face.eyebrowDetection(self.screen) #아이템 self.item1.draw_item(self,2400,1200,mouthOpen) self.item2.draw_item(self,400,600,mouthOpen) self.item3.draw_item(self,800,900,mouthOpen) self.item4.draw_item(self,800,700,mouthOpen) self.item5.draw_item(self,1050,800,mouthOpen) self.item6.draw_item(self,2390,1300,mouthOpen) self.item7.draw_item(self,1750,1390,mouthOpen) self.item8.draw_item(self,1950,1400,mouthOpen) self.item9.draw_item(self,1900,1419,mouthOpen) self.item10.draw_item(self,2210,1210,mouthOpen) self.item11.draw_item(self,3000,610,mouthOpen) if self.box3_hit is True: self.item12.draw_item(self,3160,360,mouthOpen) self.event(eyebrow) #print(mouthOpen) #배경 update self.player.update(self,self.up,self.down,self.left, self.right) self.camera.update() pygame.display.flip()