def getAvatar(id): # I edited some parts of this and made it more comprehensible because this dote ... # pretty self explanatory AVAILABLE_SIZES = [60, 88, 95, 120, 300, 600] # Again and again, this is the user's database model user = session.query(User).filter_by(ID=id).first() # By default the size is 120 if it's not specified in the URL (cp?size=integer) size = 120 try: if "size" in request.args: size = int(request.args.get("size")) size = size if size in AVAILABLE_SIZES else 120 except KeyError: pass details = [ user.Photo, user.Color, user.Head, user.Face, user.Neck, user.Body, user.Hand, user.Feet, user.Flag ] if details is None: return abort(404) items = Avatar.initializeImage(list(map(int, details)), size) return send_file(Avatar.buildAvatar(items), mimetype='image/png')
def delete(self): try: self.DistributedAvatar_deleted except: self.DistributedAvatar_deleted = 1 Avatar.delete(self) DistributedActor.delete(self)
def __init__(self, filename): with open(filename, 'r') as f: l = f.readline().split() self.width = int(l[0]) self.height = int(l[1]) l = f.readline().split() self.avatar = Avatar(int(l[0]), int(l[1]), int(l[2]), int(l[3]), float(l[4])) self.tiles = [[None for i in range(self.height)] for j in range(self.width)] for i in range(self.height - 1, -1, -1): l = f.readline().split() for j in range(0, self.width): self.tiles[j][i] = Tile(l[j]) #print(self.tiles[j][i].name) self.mons = [] for line in f: l = line.split() if len(l) == 6: m = Monster(self, l[0], int(l[1]), int(l[2]), int(l[3]), int(l[4]), int(l[5])) t = threading.Thread(target=m.run) self.mons.append(m) t.start() f.close() self.lock = threading.Lock() StdDraw.setCanvasSize(self.width * Tile.SIZE, self.height * Tile.SIZE) StdDraw.setXscale(0.0, self.width * Tile.SIZE) StdDraw.setYscale(0.0, self.height * Tile.SIZE) StdDraw.setFontSize(12) StdDraw.setPenColor(StdDraw.RED)
def onEnterWorld(self, prereqs): Avatar.onEnterWorld(self, prereqs) AvatarBot._ENTITIES.append(self) if not BOTS_DEVELOPMENT_MODE: return else: self.__updateDebugCallBack = None self.__updateDebug() return
def __init__(self): self.personal_detail_fields = ["real_name", "address", "email", "password", "trusted_ips", "phone_number", "verified", "pending_messages"] self.stats_fields = ["win_streak", "loss_streak", "wins_total", "losses_total", "largest_loss_streak", "largest_win_streak", "perfect_victory", "total_play_time_by_size", "total_moves_by_size", "total_games_by_size", "iiq", "win_loss_ratio"] # Identification Information self.real_name = "" # Name of the person associated with this account self.address = "" self.email = "" self.password = "" self.trusted_ips = {} self.phone_number = "" self.pending_messages = {} # Dictionary containing message ID: message, timestamp self.postgame_messages = {} self.verified = False # Account information self.name = UsernameGenerator.generate_isogramic_username() # Username of the user self.catchphrase = "" # Phrase to show to those starting a game with you. # Cosmetic information self.theme = Theme() # Theme the user has equipped self.avatar = Avatar() # Link to avatar object, built from json, of course. # Play-stats self.last_active = 0 self.win_streak = 0 self.loss_streak = 0 self.wins_total = 0 self.losses_total = 0 self.largest_win_streak = 0 self.largest_loss_streak = 0 self.perfect_victory = 0 self.total_play_time_by_size = Profile.by_size(3, 17) self.total_moves_by_size = Profile.by_size(3, 17) self.total_games_by_size = Profile.by_size(3, 17) # Important Stats self.iiq = 2500 # Isogram Intelligence Quotient self.win_loss_ratio = 0 self.level = 0 # Level self.experience = 0 # Total experience self.carousel_pages = "P" # Order of pages on this player's carousel. self.game_pages = "LG" # Order of pages on this player's game carousel, visible during matches. self.grams = 0 # Grams of stardust self.scoins = 0 # Star coins self.marques = 0 # "Sorry" tickets. Distributed to players upon unfortunate circumstances or at admin discretion. # Redeemable 24 hours after distribution. self.pending_marques = {} self.rank = 0 # Default rank. 0 - Normal, 1 - Community Helper, 2 - Moderator, 3 - Admin
def delete(self): """ This method is called when the DistributedObject is permanently removed from the world and deleted from the cache. """ try: self.DistributedAvatar_deleted except: self.DistributedAvatar_deleted = 1 Avatar.delete(self) DistributedActor.delete(self)
def __init__(self, cr): try: return None except: self.DistributedAvatar_initialized = 1 Avatar.__init__(self) DistributedActor.__init__(self, cr) self.hpText = None self.hp = None self.maxHp = None
def onLeaveWorld(self): Avatar.onLeaveWorld(self) AvatarBot._ENTITIES.remove(self) if not BOTS_DEVELOPMENT_MODE: return elif self.__updateDebugCallBack is None: return else: BigWorld.cancelCallback(self.__updateDebugCallBack) self.__updateDebugCallBack = None AvatarBot.clearDebugInfo(self) return
def __init__(self, cr): try: self.DistributedAvatar_initialized return except: self.DistributedAvatar_initialized = 1 Avatar.__init__(self) DistributedActor.__init__(self, cr) self.hpText = None self.hp = None self.maxHp = None
def __init__(self, plyr, parent=None): #Bot __init__ is given starthealth, parent class self.bot = __import__(plyr).Bot(parent.STARTHEALTH, self) self.name = self.bot.getName() self.imagesDict = self.bot.getImages() self.parent = parent self.VERSION = self.parent.VERSION self.botmodifiers = BotModifiers(self.name) self.botstats = BotStats(self.name, self.botmodifiers) self.__position = [0, 0] self.__ids = [0, 0, 0, 0, 0] self.resetStats() self.avatar = Avatar(self.name, self.__position, self.imagesDict)
def getDebugInfo(self): data = Avatar.getDebugInfo(self) def safeAppend(attrName, prettyPrint=None): if hasattr(self, attrName): data.append( (attrName, getattr(self, attrName) if prettyPrint is None else prettyPrint(getattr(self, attrName)))) return safeAppend('AIState', prettyPrint=lambda x: AIState.getStateName(x)) safeAppend('profile') if hasattr(self, 'defendSector') and getattr(self, 'defendSector'): safeAppend('defenderType', prettyPrint=lambda x: enumToString(DEFENDER_TYPE, x)) safeAppend('isPatrolLeader', prettyPrint=bool) else: safeAppend( 'strategyTargetType', prettyPrint=lambda x: enumToString(STRATEGY_TARGET_TYPE, x)) safeAppend('combatMode', prettyPrint=lambda x: enumToString(COMBAT_MODE, x)) safeAppend('bombsCount') safeAppend('rocketsCount') return data
def __init__(self, cr): """ Handle distributed updates """ try: self.DistributedAvatar_initialized return except: self.DistributedAvatar_initialized = 1 Avatar.__init__(self) DistributedActor.__init__(self, cr) # The node that shows the number of hp just gained or lost self.hpText = None self.hp = None self.maxHp = None
def generateAvatar() -> Avatar: velocityPoints = randint(1, 10) attackPoints = randint(1, 3) lifePoints = randint(10, 20) avatar: Avatar = Avatar(attackPoints, lifePoints, 0, velocityPoints) return avatar
def setName(self, name): try: self.node().setName('%s-%d' % (name, self.doId)) self.gotName = 1 except: pass return Avatar.setName(self, name)
def create_player(ID, room=True): created_player = Avatar(ID, room=room) items = [Workbench, Board] for item in items: created_player.recepts.append(item().recept) return created_player
def setName(self, name): try: self.node().setName(name) # NF # Appends name and ID, but why??? #self.node().setName('%s-%d' % (name, self.doId)) self.gotName = 1 except: pass return Avatar.setName(self, name)
def setName(self, name): # Set the name of our top node, so it will be easy to identify # this avatar in the scene graph. try: self.node().setName("%s-%d" % (name, self.doId)) self.gotName = 1 except: # This might fail if the doId hasn't been set yet. # No big deal. pass return (Avatar.setName(self, name))
def __init__(self, filename): with open(filename, 'r') as f: l = f.readline().split() self.width = int(l[0]) self.height = int(l[1]) l = f.readline().split() self.player = Avatar(int(l[0]), int(l[1])) self.tiles = [[None for i in range(self.height)] for j in range(self.width)] for i in range(self.height - 1, -1, -1): l = f.readline().split() for j in range(0, self.width): self.tiles[j][i] = Tile(l[j]) #print(self.tiles[j][i].name) f.close() StdDraw.setCanvasSize(self.width * 16, self.height * 16) StdDraw.setXscale(0.0, self.width * 16) StdDraw.setYscale(0.0, self.height * 16) ##### YOUR CODE HERE ##### pass
def __init__(self,plyr,parent=None): #Bot __init__ is given starthealth, parent class self.bot = __import__(plyr).Bot(parent.STARTHEALTH,self) self.name = self.bot.getName() self.imagesDict = self.bot.getImages() self.parent = parent self.VERSION = self.parent.VERSION self.botmodifiers = BotModifiers(self.name) self.botstats = BotStats(self.name,self.botmodifiers) self.__position = [0,0] self.__ids = [0,0,0,0,0] self.resetStats() self.avatar = Avatar(self.name,self.__position,self.imagesDict)
def from_json(self, json_text): self.real_name = json_text["real_name"] self.address = json_text["address"] self.email = json_text["email"] self.name = json_text["name"] self.catchphrase = json_text["catchphrase"] temp_theme = Theme() temp_theme.from_json(json_text["theme"]) self.theme = temp_theme temp_avatar = Avatar() temp_avatar.from_json(json_text["avatar"]) self.avatar = temp_avatar self.win_streak = json_text["win_streak"] self.loss_streak = json_text["loss_streak"] self.wins_total = json_text["wins_total"] self.losses_total = json_text["losses_total"] self.perfect_victory = json_text["perfect_victory"] self.total_play_time_by_size = json_text["total_play_time_by_size"] self.total_moves_by_size = json_text["total_moves_by_size"] self.total_games_by_size = json_text["total_games_by_size"] self.largest_loss_streak = json_text["largest_loss_streak"] self.largest_win_streak = json_text["largest_win_streak"] self.iiq = json_text["iiq"] self.win_loss_ratio = json_text["win_loss_ratio"] self.password = json_text["password"] self.trusted_ips = json_text["trusted_ips"] self.phone_number = json_text["phone_number"] self.last_active = json_text["last_active"] self.verified = json_text["verified"] self.level = json_text["level"] self.carousel_pages = json_text["carousel_pages"] self.game_pages = json_text["game_pages"] self.scoins = json_text["scoins"] self.grams = json_text["grams"] self.marques = json_text["marques"] self.pending_marques = json_text["pending_marques"] self.experience = json_text["experience"] self.rank = json_text["rank"]
screen = pygame.display.set_mode(size) pygame.display.set_caption("Opus 110") clock = pygame.time.Clock() black = colors["black"] gameState = GameState() #creating all sprites allSprites = pygame.sprite.Group() enemies = pygame.sprite.Group() players = pygame.sprite.Group() #creating all game objects background = BackgroundVScrolling(width, height) leftarrow = Arrow(width, height, True, frec=8) rightarrow = Arrow(width, height, False, frec=12) avatar = Avatar(width, height) scoreboard = ScoreBoard(width, height) for i in range(3): enemy = Enemy((width, height)) enemy.randomTopPosition() enemy.randomSpeed(x=0) enemy.moving = True enemies.add(enemy) allSprites.add(enemy) allSprites.add(avatar) players.add(avatar) avatar.allSprites = allSprites #Game loop
class World: # Constructor for the world # # Input parameter is a file name holding the configuration information # for the world to be created # The constructor reads in file data, stores it in appropriate # attributes and sets up the window within which to draw. # It also initializes the lighting in the world. def __init__(self, filename): with open(filename, 'r') as f: l = f.readline().split() self.width = int(l[0]) self.height = int(l[1]) l = f.readline().split() self.player = Avatar(int(l[0]), int(l[1])) self.tiles = [[None for i in range(self.height)] for j in range(self.width)] for i in range(self.height - 1, -1, -1): l = f.readline().split() for j in range(0, self.width): self.tiles[j][i] = Tile(l[j]) #print(self.tiles[j][i].name) f.close() StdDraw.setCanvasSize(self.width * 16, self.height * 16) StdDraw.setXscale(0.0, self.width * 16) StdDraw.setYscale(0.0, self.height * 16) ##### YOUR CODE HERE ##### pass def validPos(self, x, y): if x >= 0 and x <= self.width - 1 and y >= 0 and y <= self.height - 1: return True else: return False # Accept keyboard input and performs the appropriate action # # Input parameter is a character that indicates the action to be taken def handleKey(self, ch): x = self.player.getX() y = self.player.getY() if ch == "w": if self.validPos(x, y + 1): if self.tiles[x][y + 1].isPassable(): self.player.setLocation(x, y + 1) elif ch == "s": if self.validPos(x, y - 1): if self.tiles[x][y - 1].isPassable(): self.player.setLocation(x, y - 1) elif ch == "a": if self.validPos(x - 1, y): if self.tiles[x - 1][y].isPassable(): self.player.setLocation(x - 1, y) elif ch == "d": if self.validPos(x + 1, y): if self.tiles[x + 1][y].isPassable(): self.player.setLocation(x + 1, y) elif ch == "+": self.player.increaseTorch() elif ch == "-": if self.player.getTorchRadius() >= 2.5: self.player.decreaseTorch() ##### YOUR CODE HERE #### pass # Draw all the lit tiles # # Only action is to draw all the components associated with the world def draw(self): self.setLit(False) x = self.light(self.player.getX(), self.player.getY(), self.player.getTorchRadius()) for i in range(0, self.width): for j in range(0, self.height): self.tiles[i][j].draw(i, j) self.player.draw() ##### YOUR CODE HERE ##### pass # Light the world # # Input parameters are the x and y position of the avatar and the # current radius of the torch. # Calls the recursive lightDFS method to continue the lighting # Returns the total number of tiles lit def light(self, x, y, r): ##### YOUR CODE HERE ##### return self.lightDFS(x, y, x, y, r) def dist(self, x, y, xOne, yOne): xDist = (xOne - x)**2 yDist = (yOne - y)**2 return math.sqrt(xDist + yDist) # Recursively light from (x, y) limiting to radius r # # Input parameters are (x,y), the position of the avatar, # (currX, currY), the position that we are currently looking # to light, and r, the radius of the torch. # Returns the number of tiles lit def lightDFS(self, x, y, currentX, currentY, r): #print("hi") if not self.validPos(currentX, currentY): return 0 elif self.dist(x, y, currentX, currentY) >= r: return 0 elif self.tiles[currentX][currentY].getLit(): return 0 elif self.tiles[currentX][currentY].isOpaque(): self.tiles[currentX][currentY].setLit(True) return 1 else: #print("hello") self.tiles[currentX][currentY].setLit(True) c = 1 c += self.lightDFS(x, y, currentX, currentY + 1, r) c += self.lightDFS(x, y, currentX, currentY - 1, r) c += self.lightDFS(x, y, currentX - 1, currentY, r) c += self.lightDFS(x, y, currentX + 1, currentY, r) return c ##### YOUR CODE HERE #### return 0 # Turn all the lit values of the tiles to a given value. Used # to reset lighting each time the avatar moves or the torch # strength changes # # Input paramter is a boolean value, generally False, to turn off # the light, but is flexible to turn the light on in some future # version def setLit(self, value): for i in range(0, self.width): for j in range(0, self.height): self.tiles[i][j].setLit(value) ##### YOUR CODE HERE ##### pass
} #print 'test 1' # inp=[('move','down'),('attack','down'),('move','down'),('move','down'),('move','down'),('move','right'),('move','right'),('move','right'),('move','down'),('move','down')] # av=Avatar('John') # m=Map(world2) # g=DW2Game(av,m) # print g.transduce(inp) #print '\n' print 'test 2' inp = [('move', 'left'), ('move', 'right'), ('move', 'right'), ('move', 'right'), ('move', 'right'), ('move', 'down'), ('move', 'down'), ('move', 'down'), ('move', 'up')] av = Avatar('John') m = Map(world2) g = DW2Game(av, m) print g.transduce(inp) print '\n' print 'test 3' inp = [('move', 'right'), ('move', 'right'), ('move', 'right'), ('move', 'down'), ('move', 'left'), ('move', 'left'), ('move', 'left'), ('attack', 'left'), ('move', 'left')] av = Avatar('John') m = Map(world2) g = DW2Game(av, m) print g.transduce(inp) print '\n'
def main(): pygame.init() pygame.font.init() size = width, height = 800,600 screen = pygame.display.set_mode(size) pygame.display.set_caption("Juego") clock = pygame.time.Clock() gameState = GameState() #creating all sprites allSprites = pygame.sprite.Group() enemies = pygame.sprite.Group() players = pygame.sprite.Group() #creating all game objects background = BackgroundVScrolling(width,height) avatar = Avatar(width,height) scoreboard = ScoreBoard(width,height) for i in range(5): enemy = Enemy((width,height)) enemy.randomTopPosition() enemy.randomSpeed(x=0) enemy.moving = True enemies.add(enemy) allSprites.add(enemy) allSprites.add(avatar) players.add(avatar) avatar.allSprites = allSprites #Game loop while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: gameState.togglePause() screen.fill(colors["black"]) milliseconds = clock.tick() # milliseconds passed since last frame gameState.update() #these are not a sprites properly #Other shapes or sprites background.draw(screen,gameState) #sprites players.update(gameState) enemies.update(gameState) colisionList = pygame.sprite.spritecollide(avatar, enemies, False) if avatar.blink == False: for enemy in colisionList: enemy.randomTopPosition() enemy.randomSpeed() enemies.add(enemy) allSprites.add(enemy) avatar.startBlink() gameState.lives -=1 allSprites.draw(screen) #draws all sprites scoreboard.draw(screen,gameState) pygame.display.flip()
class Profile: def __init__(self): self.personal_detail_fields = ["real_name", "address", "email", "password", "trusted_ips", "phone_number", "verified", "pending_messages"] self.stats_fields = ["win_streak", "loss_streak", "wins_total", "losses_total", "largest_loss_streak", "largest_win_streak", "perfect_victory", "total_play_time_by_size", "total_moves_by_size", "total_games_by_size", "iiq", "win_loss_ratio"] # Identification Information self.real_name = "" # Name of the person associated with this account self.address = "" self.email = "" self.password = "" self.trusted_ips = {} self.phone_number = "" self.pending_messages = {} # Dictionary containing message ID: message, timestamp self.postgame_messages = {} self.verified = False # Account information self.name = UsernameGenerator.generate_isogramic_username() # Username of the user self.catchphrase = "" # Phrase to show to those starting a game with you. # Cosmetic information self.theme = Theme() # Theme the user has equipped self.avatar = Avatar() # Link to avatar object, built from json, of course. # Play-stats self.last_active = 0 self.win_streak = 0 self.loss_streak = 0 self.wins_total = 0 self.losses_total = 0 self.largest_win_streak = 0 self.largest_loss_streak = 0 self.perfect_victory = 0 self.total_play_time_by_size = Profile.by_size(3, 17) self.total_moves_by_size = Profile.by_size(3, 17) self.total_games_by_size = Profile.by_size(3, 17) # Important Stats self.iiq = 2500 # Isogram Intelligence Quotient self.win_loss_ratio = 0 self.level = 0 # Level self.experience = 0 # Total experience self.carousel_pages = "P" # Order of pages on this player's carousel. self.game_pages = "LG" # Order of pages on this player's game carousel, visible during matches. self.grams = 0 # Grams of stardust self.scoins = 0 # Star coins self.marques = 0 # "Sorry" tickets. Distributed to players upon unfortunate circumstances or at admin discretion. # Redeemable 24 hours after distribution. self.pending_marques = {} self.rank = 0 # Default rank. 0 - Normal, 1 - Community Helper, 2 - Moderator, 3 - Admin def to_json(self, hide_personal_details=False, just_stats=False): return_json = { 'verified': self.verified, 'last_active': self.last_active, 'real_name': self.real_name, 'phone_number': self.phone_number, 'address': self.address, 'email': self.email, 'name': self.name, 'catchphrase': self.catchphrase, 'theme': self.theme.to_json(), 'avatar': self.avatar.to_json(), 'win_streak': self.win_streak, 'loss_streak': self.loss_streak, 'wins_total': self.wins_total, 'losses_total': self.losses_total, 'largest_loss_streak': self.largest_loss_streak, 'largest_win_streak': self.largest_win_streak, 'perfect_victory': self.perfect_victory, 'total_play_time_by_size': self.total_play_time_by_size, 'total_moves_by_size': self.total_moves_by_size, 'total_games_by_size': self.total_games_by_size, 'iiq': self.iiq, 'win_loss_ratio': self.win_loss_ratio, 'password': self.password, 'trusted_ips': self.trusted_ips, 'level': self.level, 'carousel_pages': self.carousel_pages, 'game_pages': self.game_pages, 'grams': self.grams, 'scoins': self.scoins, 'marques': self.marques, 'pending_marques': self.pending_marques, 'experience': self.experience, 'rank': self.rank } if hide_personal_details: for entry in self.personal_detail_fields: return_json.pop(entry, None) if just_stats: for entry in return_json.keys(): if entry not in self.stats_fields: return_json.pop(entry, None) return return_json @staticmethod def by_size(start, end): return_dict = {} for x in xrange(start, end+1): return_dict[x] = 0 return return_dict def from_json(self, json_text): self.real_name = json_text["real_name"] self.address = json_text["address"] self.email = json_text["email"] self.name = json_text["name"] self.catchphrase = json_text["catchphrase"] temp_theme = Theme() temp_theme.from_json(json_text["theme"]) self.theme = temp_theme temp_avatar = Avatar() temp_avatar.from_json(json_text["avatar"]) self.avatar = temp_avatar self.win_streak = json_text["win_streak"] self.loss_streak = json_text["loss_streak"] self.wins_total = json_text["wins_total"] self.losses_total = json_text["losses_total"] self.perfect_victory = json_text["perfect_victory"] self.total_play_time_by_size = json_text["total_play_time_by_size"] self.total_moves_by_size = json_text["total_moves_by_size"] self.total_games_by_size = json_text["total_games_by_size"] self.largest_loss_streak = json_text["largest_loss_streak"] self.largest_win_streak = json_text["largest_win_streak"] self.iiq = json_text["iiq"] self.win_loss_ratio = json_text["win_loss_ratio"] self.password = json_text["password"] self.trusted_ips = json_text["trusted_ips"] self.phone_number = json_text["phone_number"] self.last_active = json_text["last_active"] self.verified = json_text["verified"] self.level = json_text["level"] self.carousel_pages = json_text["carousel_pages"] self.game_pages = json_text["game_pages"] self.scoins = json_text["scoins"] self.grams = json_text["grams"] self.marques = json_text["marques"] self.pending_marques = json_text["pending_marques"] self.experience = json_text["experience"] self.rank = json_text["rank"] def set_real_name(self, newname): self.real_name = newname def get_real_name(self): return self.real_name def set_address(self, naddress): self.address = naddress def get_address(self): return self.address def set_email(self, nemail): self.email = nemail def get_email(self): return self.email def set_account_name(self, naname): self.name = naname def get_account_name(self): return self.name def set_catchphrase(self, ncatchphrase): self.catchphrase = ncatchphrase def get_catchphrase(self): return self.catchphrase def set_theme(self, ntheme): self.theme = ntheme def get_theme(self): return self.theme def set_avatar(self, navatar): self.avatar = navatar def get_avatar(self): return self.avatar def set_win_streak(self, nwin): self.win_streak = nwin def get_win_streak(self): return self.win_streak def set_loss_streak(self, nloss): self.loss_streak = nloss def get_loss_streak(self): return self.loss_streak def set_wins_total(self, nwins): self.wins_total = nwins def get_wins_total(self): return self.wins_total def set_losses_total(self, nlosses): self.losses_total = nlosses def get_losses_total(self): return self.losses_total def set_perfect_victories(self, npvict): self.perfect_victory = npvict def get_perfect_victories(self): return self.perfect_victory def set_iiq(self, niiq): self.iiq = niiq def get_iiq(self): return self.iiq def set_win_loss_ratio(self, nwlr): self.win_loss_ratio = nwlr def get_win_loss_ratio(self): return self.win_loss_ratio def get_total_play_time_by_size(self): return self.total_play_time_by_size def set_total_play_time_by_size(self, dict): self.total_play_time_by_size = dict def get_total_games_by_size(self): return self.total_games_by_size def set_total_games_by_size(self, dict): self.total_games_by_size = dict def set_total_moves_by_size(self, dict): self.total_moves_by_size = dict def get_total_moves_by_size(self): return self.total_moves_by_size def set_password(self, passw): self.password = passw def get_password(self): return self.password def get_trusted_ips(self): return self.trusted_ips def set_trusted_ips(self, tips): self.trusted_ips = tips def get_phone_number(self): return self.phone_number def set_phone_number(self, phone): self.phone_number = phone def set_last_active(self, time): self.last_active = time def get_last_active(self): return self.last_active def get_verified(self): return self.verified def set_verified(self, bool): self.verified = bool def get_pending_messages(self): return self.pending_messages def get_postgame_messages(self): return self.postgame_messages def set_largest_loss_streak(self, nll): self.largest_loss_streak = nll def get_largest_loss_streak(self): return self.largest_loss_streak def set_largest_win_streak(self, nww): self.largest_win_streak = nww def get_largest_win_streak(self): return self.largest_win_streak def clear_pending_messages(self): self.pending_messages.clear() def add_server_message(self, string_message, is_json=False): largest_key = 0 for key in self.pending_messages.keys(): if key > largest_key: largest_key = key self.pending_messages[largest_key + 1] = { "message": string_message, "timestamp": time.time(), "is_json": is_json } def clear_postgame_messages(self): self.postgame_messages.clear() def add_postgame_message(self, string_message, is_json=False): largest_key = 0 for key in self.postgame_messages.keys(): if key > largest_key: largest_key = key self.postgame_messages[largest_key + 1] = { "message": string_message, "timestamp": time.time(), "is_json": is_json } def get_level(self): return self.level def set_level(self, level): self.level = level def get_carousel_pages(self): return self.carousel_pages def set_carousel_pages(self, target): self.carousel_pages = target def get_game_pages(self): return self.game_pages def set_game_pages(self, target): self.game_pages = target def set_scoins(self, scoins): self.scoins = scoins def get_scoins(self): return self.scoins def set_grams(self, gram): self.grams = gram def get_grams(self): return self.grams def get_marques(self): return self.marques def set_marques(self, newmarques): self.marques = newmarques def get_pending_marques(self): return self.pending_marques def set_pending_marques(self, newpend): self.pending_marques = newpend def distribute_marques(self, amount=1): self.pending_marques[time.time()] = amount def get_experience(self): return self.experience def set_experience(self, amount): self.experience = amount def get_rank(self): return self.rank def set_rank(self, newrank): self.rank = newrank
def getToonTag(self): return Avatar.getToonTag(self)
def getName(self): return Avatar.getName(self)
class BotWrapper(object): """Provides access to user bot methods and keeps meta-data for user bots""" def __init__(self,plyr,parent=None): #Bot __init__ is given starthealth, parent class self.bot = __import__(plyr).Bot(parent.STARTHEALTH,self) self.name = self.bot.getName() self.imagesDict = self.bot.getImages() self.parent = parent self.VERSION = self.parent.VERSION self.botmodifiers = BotModifiers(self.name) self.botstats = BotStats(self.name,self.botmodifiers) self.__position = [0,0] self.__ids = [0,0,0,0,0] self.resetStats() self.avatar = Avatar(self.name,self.__position,self.imagesDict) #def addEnemy(self,enemy): # self.bot.addEnemy(enemy) def addPoints(self,n): self.botstats.add("points",n) #args: Damage object #Return: integer health def adjustHealth(self,damage): return self.bot.adjustHealth(damage) #args: string command #Return: none #executes user inputted commands def command(self,command): print "COMMAND: ",command," , made it to the botwrapper of: ",self.name self.bot.command(command) #args integer round number #Return: none def endRound(self,roundnumber): self.bot.endRound(roundnumber) if self.bot.getHealth() <= 0: self.__stance = "OUT!!" #args: none #return: none def endGame(self): self.botstats.endgame() mod = self.botstats.getNextModifier() while mod: self.botmodifiers.adjustModifier(*mod) mod = self.botstats.getNextModifier() def getAvatar(self): self.avatar.stance = self.getStance() self.avatar.setPosition(self.__position) self.avatar.health = self.getHealth() self.avatar.enemies = self.getEnemies() self.avatar.modifiers = self.botmodifiers.getModifiers(True) try: self.avatar.color = self.bot.getColor() except AttributeError: self.avatar.color = (255,255,255) return copy.copy(self.avatar) #args: none #Return: list of enemies' names def getEnemies(self): return self.bot.getEnemies() #args: none #Return: integer health def getHealth(self): return self.bot.getHealth() def getIds(self): return self.__ids #args: none #Return: float angle to look def getLookDirection(self): return self.bot.getLookDirection() def getModifier(self,name): return self.botmodifiers.getModifier(name) def getMoveDirection(self): return self.bot.getMoveDirection() #args: none #Return: string name def getName(self): return self.name def getPosition(self): return self.__position #args: none #Return: Stance object def getStance(self): if self.__stance: return self.__stance else: return self.bot.getStance() def getStats(self): return copy.copy(self.botstats) #args: none #Return: GameOjbect object with position set def getTarget(self): t = self.bot.getTarget() t.measuredFrom = self.position return t def HealMe(self): if self.botmodifiers.getModifier("numHeals") > 0: self.bot.adjustHealth(Damage("HEAL",25,0,"HEAL")) self.botmodifiers.adjustModifier("numHeals", "-",1) avatar = self.getAvatar() avatar.heal = True self.parent.drawHealIcon(avatar) #args: int round number #Return: Stance object def prepare(self,n): st = self.bot.prepare(n) if st.isA("fire"): self.botstats.add("numFires",1) elif st.isA("guard"): self.botstats.add("numGuards",1) return st #def removeEnemy(self,e): # self.bot.removeEnemy(e) #args: health to reset to #Return: none def reset(self,health): self.bot.reset(health) self.botstats.reset() self.botmodifiers.reset() self.resetStats() def resetStats(self): self.botstats.reset() self.__stance = "" def setDamage(self,n): self.__damageDone = n #def setEHealth(self,p,h,s): # self.bot.setEHealth(p,h,s) def setIds(self,i): for index in range(0,len(i)): if i[index]: self.__ids[index]=i[index] #args: GameObject found #Return: none def setLookResults(self,gameobject): self.bot.setLookResults(gameobject) def setPosition(self,pos): #print "I, ",self.name," , just got moved to: ",pos self.__position[0] = pos[0] self.__position[1] = pos[1] #args: integer width of field #Return: none #used to tell your bot what its viewing width is def setWoF(self,WoF): self.bot.setWoF(WoF) def test(self): try: #Testing checklist --> [enemy adding, stance, health, enemy, reset] testingCheck= 0 testingList = ["a stance operation", "a health operation", "a targeting operation", "reset"] for i in range(0,10): assert isinstance(self.bot.prepare(i), Stance) assert isinstance(self.bot.getStance(), Stance) testingCheck +=1 assert self.bot.getHealth() == self.parent.STARTHEALTH assert self.bot.adjustHealth(Damage("Piercing", -5, 20))==self.parent.STARTHEALTH-5 assert self.bot.adjustHealth(Damage("Burning", -15, 220))==self.parent.STARTHEALTH-20 testingCheck +=1 assert isinstance(self.bot.getTarget(), GameObject) testingCheck +=1 self.bot.reset(self.parent.STARTHEALTH) assert self.bot.getHealth() == self.parent.STARTHEALTH return True except AttributeError, attre: print self.bot.getName()," has been removed." print attre print "Error occured during: ",testingList[testingCheck] print "==================================================" return False except AssertionError, asse: print self.bot.getName()," has been removed." print "One of your functions does not return the correct value" print "Error occured during: ",testingList[testingCheck] return False
# This is what you mainly want to edit config = Config(app).build_configuration() Config(app).set_flask_config(config) engine = create_engine("mysql://%s:%s@%s/%s" % (config["db"]["user"], config["db"]["pass"], config["db"]["host"], config["db"]["name"])) session_factory = sessionmaker(bind=engine) session = flask_scoped_session(session_factory, app) recaptcha = ReCaptcha(app) recaptcha.init_app(app) Settings = Settings(session) Utils = Utils(Session) Avatar = Avatar() @app.route("/", methods=["GET", "POST"]) def index(): # Redirects if the user is logged in if Session.get("user"): return redirect(url_for("dashboard")) # on submit (HTTP POST request), retrieve the username and the password if request.method == "POST": username = request.form["username"] password = request.form["password"] # This is the user's database model, so we can easily access his columns (e.g. user.Username) user = session.query(User).filter_by(Username=username).first()
def setToonTag(self, tag): return Avatar.setToonTag(self, tag)
def desafioMatematica(): avatar = Avatar(avatarImagem, "Bruno", 10, 10) DesafioMatematica.jogar(somLigado.somRaposa)
class BotWrapper(object): """Provides access to user bot methods and keeps meta-data for user bots""" def __init__(self, plyr, parent=None): #Bot __init__ is given starthealth, parent class self.bot = __import__(plyr).Bot(parent.STARTHEALTH, self) self.name = self.bot.getName() self.imagesDict = self.bot.getImages() self.parent = parent self.VERSION = self.parent.VERSION self.botmodifiers = BotModifiers(self.name) self.botstats = BotStats(self.name, self.botmodifiers) self.__position = [0, 0] self.__ids = [0, 0, 0, 0, 0] self.resetStats() self.avatar = Avatar(self.name, self.__position, self.imagesDict) #def addEnemy(self,enemy): # self.bot.addEnemy(enemy) def addPoints(self, n): self.botstats.add("points", n) #args: Damage object #Return: integer health def adjustHealth(self, damage): return self.bot.adjustHealth(damage) #args: string command #Return: none #executes user inputted commands def command(self, command): print "COMMAND: ", command, " , made it to the botwrapper of: ", self.name self.bot.command(command) #args integer round number #Return: none def endRound(self, roundnumber): self.bot.endRound(roundnumber) if self.bot.getHealth() <= 0: self.__stance = "OUT!!" #args: none #return: none def endGame(self): self.botstats.endgame() mod = self.botstats.getNextModifier() while mod: self.botmodifiers.adjustModifier(*mod) mod = self.botstats.getNextModifier() def getAvatar(self): self.avatar.stance = self.getStance() self.avatar.setPosition(self.__position) self.avatar.health = self.getHealth() self.avatar.enemies = self.getEnemies() self.avatar.modifiers = self.botmodifiers.getModifiers(True) try: self.avatar.color = self.bot.getColor() except AttributeError: self.avatar.color = (255, 255, 255) return copy.copy(self.avatar) #args: none #Return: list of enemies' names def getEnemies(self): return self.bot.getEnemies() #args: none #Return: integer health def getHealth(self): return self.bot.getHealth() def getIds(self): return self.__ids #args: none #Return: float angle to look def getLookDirection(self): return self.bot.getLookDirection() def getModifier(self, name): return self.botmodifiers.getModifier(name) def getMoveDirection(self): return self.bot.getMoveDirection() #args: none #Return: string name def getName(self): return self.name def getPosition(self): return self.__position #args: none #Return: Stance object def getStance(self): if self.__stance: return self.__stance else: return self.bot.getStance() def getStats(self): return copy.copy(self.botstats) #args: none #Return: GameOjbect object with position set def getTarget(self): t = self.bot.getTarget() t.measuredFrom = self.position return t def HealMe(self): if self.botmodifiers.getModifier("numHeals") > 0: self.bot.adjustHealth(Damage("HEAL", 25, 0, "HEAL")) self.botmodifiers.adjustModifier("numHeals", "-", 1) avatar = self.getAvatar() avatar.heal = True self.parent.drawHealIcon(avatar) #args: int round number #Return: Stance object def prepare(self, n): st = self.bot.prepare(n) if st.isA("fire"): self.botstats.add("numFires", 1) elif st.isA("guard"): self.botstats.add("numGuards", 1) return st #def removeEnemy(self,e): # self.bot.removeEnemy(e) #args: health to reset to #Return: none def reset(self, health): self.bot.reset(health) self.botstats.reset() self.botmodifiers.reset() self.resetStats() def resetStats(self): self.botstats.reset() self.__stance = "" def setDamage(self, n): self.__damageDone = n #def setEHealth(self,p,h,s): # self.bot.setEHealth(p,h,s) def setIds(self, i): for index in range(0, len(i)): if i[index]: self.__ids[index] = i[index] #args: GameObject found #Return: none def setLookResults(self, gameobject): self.bot.setLookResults(gameobject) def setPosition(self, pos): #print "I, ",self.name," , just got moved to: ",pos self.__position[0] = pos[0] self.__position[1] = pos[1] #args: integer width of field #Return: none #used to tell your bot what its viewing width is def setWoF(self, WoF): self.bot.setWoF(WoF) def test(self): try: #Testing checklist --> [enemy adding, stance, health, enemy, reset] testingCheck = 0 testingList = [ "a stance operation", "a health operation", "a targeting operation", "reset" ] for i in range(0, 10): assert isinstance(self.bot.prepare(i), Stance) assert isinstance(self.bot.getStance(), Stance) testingCheck += 1 assert self.bot.getHealth() == self.parent.STARTHEALTH assert self.bot.adjustHealth(Damage( "Piercing", -5, 20)) == self.parent.STARTHEALTH - 5 assert self.bot.adjustHealth(Damage( "Burning", -15, 220)) == self.parent.STARTHEALTH - 20 testingCheck += 1 assert isinstance(self.bot.getTarget(), GameObject) testingCheck += 1 self.bot.reset(self.parent.STARTHEALTH) assert self.bot.getHealth() == self.parent.STARTHEALTH return True except AttributeError, attre: print self.bot.getName(), " has been removed." print attre print "Error occured during: ", testingList[testingCheck] print "==================================================" return False except AssertionError, asse: print self.bot.getName(), " has been removed." print "One of your functions does not return the correct value" print "Error occured during: ", testingList[testingCheck] return False
b = TxtButton(bot,(x,0),self.notificationsGroup) b.setFontSize(32) self.botsDict[bot]= b self.notificationsGroup.add(self.botsDict[bot]) x +=75 if __name__ == "__main__": import Queue gui = ServerGui() q = Queue.Queue() #Create a list of avatars to pull from avs = [] for b in range(0,21): a = "av" + str(b) av = Avatar(a,(random.randint(0,800),random.randint(0,600))) print "init queuing: ", av av.stance = Stance("Fire",random.choice(("Burning","Piercing"))) avs.append(av) i = 0 # Fill the queue with init requests for l in range(0,7): q.put( pickle.dumps( ["init",-1,[avs[i],avs[i+1],avs[i+2]]] ) ) i = i +3 #Fiill the queue with updateBot requests av = Avatar("av19", [200,200]) av.stance = Stance("Fire",random.choice(("Burning","Piercing"))) #av.heal = random.choice((True,False)) q.put( pickle.dumps( ["updateBot", -1, [av]])) p = [500,300]
class World: # Constructor for the world # # Input parameter is a file name holding the configuration information # for the world to be created # The constructor reads in file data, stores it in appropriate # attributes and sets up the window within which to draw. # It also initializes the lighting in the world. def __init__(self, filename): with open(filename, 'r') as f: l = f.readline().split() self.width = int(l[0]) self.height = int(l[1]) l = f.readline().split() self.avatar = Avatar(int(l[0]), int(l[1]), int(l[2]), int(l[3]), float(l[4])) self.tiles = [[None for i in range(self.height)] for j in range(self.width)] for i in range(self.height - 1, -1, -1): l = f.readline().split() for j in range(0, self.width): self.tiles[j][i] = Tile(l[j]) #print(self.tiles[j][i].name) self.mons = [] for line in f: l = line.split() if len(l) == 6: m = Monster(self, l[0], int(l[1]), int(l[2]), int(l[3]), int(l[4]), int(l[5])) t = threading.Thread(target=m.run) self.mons.append(m) t.start() f.close() self.lock = threading.Lock() StdDraw.setCanvasSize(self.width * Tile.SIZE, self.height * Tile.SIZE) StdDraw.setXscale(0.0, self.width * Tile.SIZE) StdDraw.setYscale(0.0, self.height * Tile.SIZE) StdDraw.setFontSize(12) StdDraw.setPenColor(StdDraw.RED) #Checks to see if the entered x,y position exists on the grid of tiles #Returns true if it does false if not def validPos(self, x, y): if x >= 0 and x <= self.width - 1 and y >= 0 and y <= self.height - 1: return True else: return False # Accept keyboard input and performs the appropriate action # # Input parameter is a character that indicates the action to be taken def handleKey(self, ch): x = self.avatar.getX() y = self.avatar.getY() if ch == "w": self.avatarMove(x, y + 1) elif ch == "s": self.avatarMove(x, y - 1) elif ch == "a": self.avatarMove(x - 1, y) elif ch == "d": self.avatarMove(x + 1, y) elif ch == "+": self.avatar.increaseTorch() elif ch == "-": if self.avatar.getTorchRadius() >= 2.5: self.avatar.decreaseTorch() ##### YOUR CODE HERE #### pass # Draw all the lit tiles # # Only action is to draw all the components associated with the world def draw(self): self.avatar.timer += 10 self.setLit(False) x = self.light(self.avatar.getX(), self.avatar.getY(), self.avatar.getTorchRadius()) for i in range(0, self.width): for j in range(0, self.height): self.tiles[i][j].draw(i, j) self.avatar.draw() for m in self.mons: m.draw() # Light the world # # Input parameters are the x and y position of the avatar and the # current radius of the torch. # Calls the recursive lightDFS method to continue the lighting # Returns the total number of tiles lit def light(self, x, y, r): return self.lightDFS(x, y, x, y, r) def dist(self, x, y, xOne, yOne): xDist = (xOne - x)**2 yDist = (yOne - y)**2 return math.sqrt(xDist + yDist) # Recursively light from (x, y) limiting to radius r # # Input parameters are (x,y), the position of the avatar, # (currX, currY), the position that we are currently looking # to light, and r, the radius of the torch. # Returns the number of tiles lit def lightDFS(self, x, y, currentX, currentY, r): #print("hi") if not self.validPos(currentX, currentY): return 0 elif self.dist(x, y, currentX, currentY) >= r: return 0 elif self.tiles[currentX][currentY].getLit(): return 0 elif self.tiles[currentX][currentY].isOpaque(): self.tiles[currentX][currentY].setLit(True) return 1 else: #print("hello") self.tiles[currentX][currentY].setLit(True) c = 1 c += self.lightDFS(x, y, currentX, currentY + 1, r) c += self.lightDFS(x, y, currentX, currentY - 1, r) c += self.lightDFS(x, y, currentX - 1, currentY, r) c += self.lightDFS(x, y, currentX + 1, currentY, r) return c return 0 # Turn all the lit values of the tiles to a given value. Used # to reset lighting each time the avatar moves or the torch # strength changes # # Input paramter is a boolean value, generally False, to turn off # the light, but is flexible to turn the light on in some future # version def setLit(self, value): for i in range(0, self.width): for j in range(0, self.height): self.tiles[i][j].setLit(value) def avatarAlive(self): if self.avatar.getHitPoints() > 0: return True return False def monsterMove(self, x, y, monster): if self.validPos(x, y): if self.tiles[x][y].isPassable(): check = False for m in self.mons: if m.getX() == x and m.getY() == y: check = True if not check: if self.avatar.getX() == x and self.avatar.getY() == y: self.avatar.incurDamage(monster.dmg) else: monster.setLocation(x, y) monster.incurDamage(self.tiles[x][y].getDamage()) #Gets input from handleKey to what would happen if the player moved to that #and then applies those effects def avatarMove(self, x, y): if self.validPos(x, y): if self.tiles[x][y].isPassable(): check = False for m in self.mons: if m.getX() == x and m.getY() == y: check = True m.incurDamage(self.avatar.dmg) if not check: self.avatar.setLocation(x, y) self.avatar.incurDamage(self.tiles[x][y].getDamage()) #Gets the number of monsters remaining and returns it as an int def getNumMonsters(self): c = 0 for m in self.mons: if m.getHitPoints() > 0: c += 1 else: self.mons.remove(m) return c