def createAI(self): self.AI = Penguin(username=self.AI_username, nickname="FindFour AI", password='', email='*****@*****.**') yield self.AI.save() yield self.AI.refresh() # update values from DB
def checkForSensei(): username = Sensei.username exists = yield Penguin.exists(where=['username = ?', username]) if not exists: sensei = Penguin(username=username, nickname="Sensei", password='', email='*****@*****.**', coins=1000, igloos='', urnitures='', floors='', locations='', care='', stamps='', cover='') yield sensei.save() yield sensei.refresh() SenseiNinja = Ninja( penguin_id=sensei.id, belt=10, cards= '427,99|749,99|591,99|724,99|90,99|259,99|574,99|736,99|257,99|580,99|83,99|97,99|748,99|76,99|252,99|355,99|590,99|593,99|734,99|260,99|739,99', matches='') yield SenseiNinja.save() logger.debug('Sensei has been born!')
def setupAI(self): AIExists = yield Penguin.exists(['`Username` = ?', self.AI_username]) if not AIExists: yield self.createAI() if self.AI is None: self.AI = yield Penguin.find( where=['Username = ?', self.AI_username], limit=1)
def handleFriends(self, newFriends, friendRemoved, originalFriends): self.cache.friends = list( originalFriends.union(newFriends) - friendRemoved) for friend in newFriends: friendObj = (yield Penguin.find(where=['swid = ?', friend.friend], limit=1)) if friendObj is None: friend.delete() continue friend.friend_id = friendObj.id friendOnline = (yield self.penguin.engine.redis.server.hmget( "online:{}".format(int(friendObj.id)), ['place_name'])) if not self.penguin['moderator'] and friendObj.moderator == 2: friendOnline = None friendOnline = friendOnline[0] if friendOnline is not None \ else 'N/A' data = [ int(friendObj.id), friendObj.nickname, friendObj.swid, friend.bff, int(friendOnline != 'N/A'), friendOnline ] self.penguin.send('fb', '|'.join(map(str, data))) for friend in friendRemoved: self.penguin.send('frf', friend.swid) for friend in originalFriends: friendObj = (yield Penguin.find(where=['swid = ?', friend.friend], limit=1)) if friendObj is None: friend.delete() continue friendOnline = (yield self.penguin.engine.redis.server.hmget( "online:{}".format(int(friendObj.id)), ['place_name'])) if not self.penguin['moderator'] and friendObj.moderator == 2: friendOnline = None friendOnline = friendOnline[0] if friendOnline is not None \ else 'N/A' self.penguin.send( 'fo', '|'.join( map(str, [ friend.friend, int(friendOnline != 'N/A'), friendOnline, 0 ])))
def handleSendMail(client, to, _id): to_peng = yield Penguin.find(to) if to_peng is None: returnValue(client.send('ms', client['coins'], 0)) client['RefreshHandler'].sendMail(to, _id)
def handleSearchPenguin(client, data): searchQuery = data[2][0].strip() searchResults = [] results = yield Penguin.find(where = ['nickname like ?', '%{}%'.format(searchQuery)]) no_space_query = searchQuery.replace(' ', '') if not no_space_query.isalnum(): searchResults.append({'msg' : 'The search query must contain only alphabets, numbers or a space.', 'nickname': 'Search Moderator'}) if len(searchQuery) < 4: searchResults.append({'msg' : 'The search query must be atleast 4 characters long.', 'nickname': 'Search Moderator'}) if len(searchResults) > 0: returnValue(client.send('fs', json.dumps(searchResults))) for r in results: if r.swid == client['swid'] or client['RefreshHandler'].is_friend(r.swid): continue a = {'nickname' : r.nickname} if hasattr(r, 'search_msg') and r.search_msg is not None and r.search_msg.strip() != '': a['msg'] = r.search_msg else: a['swid'] = r.swid searchResults.append(a) if len(searchResults) < 1: searchResults.append({'msg' : 'Your query yield no result. Search for some other penguin.', 'nickname': 'Search Moderator'}) client.send('fs', json.dumps(searchResults))
def initPenguinIglooRoom(self, penguin_id): penguin = ( yield Penguin.find(penguin_id) ) if penguin_id != self.penguin['id'] else self.penguin.dbpenguin if penguin is None: returnValue(None) iglooRoom = self.penguin.engine.iglooCrumbs.getPenguinIgloo(penguin_id) currentIgloo = int(penguin.igloo) igloo = yield Igloo.find(currentIgloo) if igloo is None: igloo = Igloo(penguin_id=penguin_id) yield igloo.save() currentIgloo = penguin.igloo = int(igloo.id) yield penguin.save() yield igloo.refresh() if iglooRoom is None: iglooRoom = IglooRoom(self.penguin.engine.roomHandler, (1000 + penguin_id), '{} igloo'.format(penguin_id), "{}'s Igloo".format(penguin.nickname), 100, False, False, None) self.penguin.engine.iglooCrumbs.penguinIgloos.append(iglooRoom) self.penguin.engine.roomHandler.rooms.append(iglooRoom) iglooRoom.owner = int(penguin_id) iglooRoom.opened = not bool(igloo.locked) iglooRoom._id = int(igloo.id) returnValue(iglooRoom)
def handleRequests(self, newRequests, removedRequests, originalRequests): self.cache.requests = list( originalRequests.union(newRequests) - removedRequests) for request in newRequests: penguin = yield Penguin.find( where=['swid = ?', request.requested_by], limit=1) self.penguin.send('fn', penguin.nickname, penguin.swid) if penguin is not None else 0
def handleGetUsernames(client, swid): usernames = list() for s in swid: user = yield Penguin.find(where = ['swid = ?', s], limit = 1) if user is None: usernames.append('') else: usernames.append(str(user.nickname)) client.send('pbsu', ','.join(usernames))
def handleGetPlayerStamps(client, _id): peng = yield Penguin.find(_id) if peng is None: returnValue(client.send('gps', _id, '')) stamps = str(peng.stamps) if stamps == '': client.send('gps', _id, '') client.send('gps', _id, '|'.join(map(lambda x: x.split(',')[0], stamps.split("|"))))
def handleGetSBCoverDetails(client, _id): peng = (yield Penguin.find(_id)) if _id != client['id'] else client.dbpenguin if peng is None: returnValue(client.send('gsbcd', '', '', '', '', '', '')) colourID, highlightID, patternID, claspIconArtID = peng.cover_color, peng.cover_highlight, peng.cover_pattern, \ peng.cover_icon pengCoverItems = yield peng.stampCovers.get() rest = map(lambda x: '{i.type}|{i.stamp}|{i.x}|{i.y}|{i.rotation}|{i.depth}'.format(i=x), pengCoverItems) client.send('gsbcd', colourID, highlightID, patternID, claspIconArtID, *rest)
def handleNewFriendRequest(client, data): swid = data[2][0] requested = yield Request.count(where=['penguin_swid = ? AND requested_by = ?', swid, client['swid']]) requestPending = yield Request.find(where=['penguin_swid=? and requested_by=?', client['swid'], swid]) if not requested and not requestPending: peng = yield Penguin.find(where=['swid=?', swid], limit=1) if peng is None: return (yield Request(penguin_id=peng.id, penguin_swid=swid, requested_by=client['swid']).save()) if not requested else None
def handleAcceptOrRejectFriendRequest(client, data): accepted = data[1][-1] == 'a' swid = data[2][0] requested = yield client.dbpenguin.requests.get(where=['requested_by = ?', swid] , limit=1) if not requested: return requested.delete() if not accepted: return friend = yield Penguin.find(where=['swid = ?', swid], limit=1) yield Friend(penguin_id=friend.id, penguin_swid=friend.swid, friend=client['swid']).save() yield Friend(penguin_id=client['id'], penguin_swid = client['swid'], friend = swid).save()
def handleGetSBCoverDetails(client, _id): peng = yield Penguin.find(_id) if peng is None: returnValue(client.send('gsbcd', '', '', '', '', '', '')) cover = str(peng.cover) if cover == '': cover = peng.cover = '1|0|0|0|0' peng.save() cover_details = cover.split('%') cover_properties = cover_details[0].split('|') colourID, highlightID, patternID, claspIconArtID = map( lambda x: int(x) if x != '' else 0, cover_properties) rest = cover_details[1:] client.send('gsbcd', colourID, highlightID, patternID, claspIconArtID, *rest)
def handleMails(self, mailArrived, mailBurnt, originalMails): for mail in mailArrived: nickname = 'Timeline Team' peng = yield Penguin.find(mail.from_user) if peng is not None: nickname = peng.nickname self.penguin.send('mr', nickname, int(mail.from_user), int(mail.type), mail.description, mail.get_sent_on(), int(mail.id), int(mail.opened)) mails = [((yield i.refresh()), i)[-1] for i in list(originalMails.union(mailArrived) - mailBurnt)] self.cache.mails = [i for i in mails if not i.junk] if len(self.cache.mails) < 1 and len(originalMails) > 0: self.penguin.send('mdp', 0)
def handleGetMail(client, data): mails = client['data'].mails mailstr = [] for mail in mails: nick = yield Penguin.find(mail.from_user) nick = nick.nickname if nick is not None else 'Timeline Team' mailstr.append('|'.join( map(str, [ nick, int(mail.from_user), mail.description, mail.get_sent_on(), int(mail.id), int(mail.opened) ]))) client.send('mg', * mailstr) if len(mailstr) > 0 else client.send('%xt%mg%-1%')
Registry.register(Penguin, Igloo, Avatar, Currency, Ninja, Asset, Ban, CareItem, Friend, Request, Ignore, Inventory, Mail, Membership, MusicTrack, Puffle, Stamp, StampCover, Coin) Registry.register(Igloo, IglooFurniture, IglooLike) Registry.DBPOOL = ReconnectingMySQLConnectionPool('MySQLdb', user=user, passwd=passd, db=db, cp_reconnect=True) self.conn = True except Exception, e: self.logger.error("Unable to start MySQL Pool on given details. (E:{0})".format(e)) self.conn = False return self.conn def validateNickname(peng): peng.nickname = peng.nickname.strip() n = peng.nickname m = n.replace(' ', '') if len(n) > 20: peng.errors.add('nickname', "Nickname should be less than 21 characters") if not m.isalnum(): peng.errors.add('nickname', "Nickname should be alpha numeric") def validateInventory(peng): peng.inventory = peng.inventory.strip('%') Penguin.addValidator(validateNickname)
def _setupCache(self): self.penguin.penguin.recentStamps = [] database_penguin = self.penguin.dbpenguin self.cache.avatar = yield database_penguin.avatar.get() if self.cache.avatar is None: self.cache.avatar = yield Avatar( penguin_id=self.penguin['id']).save() yield self.cache.avatar.refresh() self.cache.inventories = yield database_penguin.inventories.get() self.cache.assets = yield database_penguin.assets.get() self.cache.friends = yield database_penguin.friends.get() self.cache.requests = [] friends_data = [] for friend in self.cache.friends: friendObj = (yield Penguin.find(where=['swid = ?', friend.friend], limit=1)) if friendObj is None: continue friend.friend_id = friendObj.id friend.onlinePresence = {'online_status': False} data = [ int(friendObj.id), friendObj.nickname, friendObj.swid, friend.bff ] friends_data.append('|'.join(map(str, data))) self.penguin.send('fl', (yield database_penguin.requests.count()), *friends_data) self.cache.ignores = yield database_penguin.ignores.get() self.cache.careItems = yield database_penguin.careItems.get() self.cache.stamps = yield database_penguin.stamps.get() self.cache.mails = yield database_penguin.mails.get() self.cache.bans = yield database_penguin.bans.get() self.cache.puffles = yield database_penguin.puffles.get() self.cache.stampCovers = yield database_penguin.stampCovers.get() self.cache.igloos = deque() igloos = yield database_penguin.igloos.get(limit=6) for igloo in igloos: iglooCache = PenguinObject() iglooCache.igloo = igloo iglooCache.iglooFurnitures = yield igloo.iglooFurnitures.get( limit=99) iglooCache.iglooLikes = yield igloo.iglooLikes.get() self.cache.igloos.append(iglooCache) self.cache.memberships = yield database_penguin.memberships.get() self.cacheHandlers.inventories = self.handleInventory self.cacheHandlers.assets = self.handleAssets self.cacheHandlers.friends = self.handleFriends self.cacheHandlers.requests = self.handleRequests self.cacheHandlers.ignores = self.handleIgnores self.cacheHandlers.careItems = self.handleCareItems self.cacheHandlers.stamps = self.handleStamps self.cacheHandlers.mails = self.handleMails self.cacheHandlers.bans = self.handleBans self.cacheHandlers.puffles = self.handlePuffles self.cacheHandlers.stampCovers = self.handleStampCovers self.cacheHandlers.igloos = self.handleIgloos self.penguin.penguin.coins = (yield Registry.getConfig().\ execute("SELECT COALESCE(SUM(transaction), 0) FROM coins where penguin_id = %s" % self.penguin['id']))[0][0] self.penguin.penguin.igloo = yield self.initPenguinIglooRoom( self.penguin['id']) if self.penguin['igloo']._id not in self.getIgloos(): igloo = yield database_penguin.igloos.get( where=['id = ?', self.penguin['igloo']._id], limit=1) iglooCache = PenguinObject() iglooCache.igloo = igloo iglooCache.iglooFurnitures = yield igloo.iglooFurnitures.get( limit=99) iglooCache.iglooLikes = yield igloo.iglooLikes.get() self.cache.igloos.append(iglooCache) self.penguin.penguin.currentIgloo = self.getIgloos()[ self.penguin.dbpenguin.igloo].igloo self.setupCJMats() membership = yield database_penguin.memberships.get( orderby='expires desc', limit=1) if membership is None: #no membership records, give a free 7 day trial trialExpiry = time.time() + 7 * 24 * 60 * 60 membership = yield \ Membership(penguin_id=self.penguin['id'], expires=Registry.getDBAPIClass("TimestampFromTicks")(trialExpiry), comments='Redeemed 7-day auto free trial membership. - Timeline Server').save() self.penguin.penguin.member = MembershipHandler( membership, self.penguin) self.cache.avatar = yield database_penguin.avatar.get() if self.cache.avatar is None: self.cache.avatar = yield Avatar( penguin_id=self.penguin['id']).save() GeneralEvent('Setup-Cache', self) self.CacheInitializedDefer.callback(True)
def handleGetPlayerStamps(client, _id): peng_stamps = (yield ((yield Penguin.find(_id))).stamps.get() ) if _id != client['id'] else client['data'].stamps stamps = [str(k.stamp) for k in peng_stamps] client.send('gps', _id, '|'.join(stamps))
class FindFourAI(IPlugin): """ Adds an intelligent find four bot to the four lounge! Make sure you have dassets.swf active! """ requirements = [Requirement(**{'name': 'Commands', 'developer': 'Dote'})] name = 'FindFourAI' developer = 'Dote' AI_username = '******' # username of bot in the database Bots = dict() # engine => Bot AI = None Call_AI_Command = "Find4" def __init__(self): super(FindFourAI, self).__init__() self.logger = logging.getLogger(TIMELINE_LOGGER) self.Bots = {} self.AICreatedDefer = self.setupAI() self.setupCommands() self.logger.debug("FindFour AI Active!") self.logger.debug("Please ensure you have dassets.swf active!") GeneralEvent.on('onEngine', self.attachBotToServer) def Play4(self, client, params): if client['room'].ext_id is not 220: return engine = client.engine if engine not in self.Bots: return client.send('sm', client['id'], "Sorry, bot is not available in this server!") AI = self.Bots[engine]['bot'] if self.Bots[engine]['playing'] is not None: return client.send( 'sm', AI['id'], "Sorry, am currently playing with {}".format( self.Bots[engine]['playing']['nickname'])) try: difficulty = int(params[0]) except: difficulty = 2 # default if difficulty > self.Bots[engine]['difficulty'] or difficulty < 1: difficulty = self.Bots[engine]['difficulty'] # maximum client.send( 'sm', AI['id'], "Let's play! Difficulty level set to {}".format(difficulty)) sleep(3) client.send('sm', AI['id'], "Finding a board to play...") AvailableBoard = self.getFourBoard(engine) if AvailableBoard is None: return client.send('sm', AI['id'], "Sorry, no boards are available to play! :(") self.Bots[engine]['playing'] = client AI.penguin.difficulty = difficulty GeneralEvent.on( 'Table-Left-{}-{}'.format(client['id'], AvailableBoard.table), self.ClientLeft) client.send('zaf', AvailableBoard.table) # make sure you have dote's assets Event.call('JoinTable-{}'.format(AvailableBoard.table), AI, AvailableBoard.table) AI['room'].send( 'sm', AI['id'], "FindFour: {} V/S {}, difficulty: {}, started!".format( AI['nickname'], client['nickname'], difficulty)) AI['game'].joinGame(AI) def makeNextTurn(self, AI): FourGame = AI['game'] if FourGame is None: return FourBoard = list(FourGame.FourGame) nextMove = self.Bots[AI.engine]['algorithm'].calculateNextMove( FourBoard, AI['difficulty']) x, y = nextMove[0] AI.penguin.lastMoved = True FourGame.play(AI, [y, x]) def manipulateSend(self, AI, *a): if len(a) < 2: return FourGame = AI['game'] if a[0] == 'sz': self.makeNextTurn(AI) elif a[0] == 'zm': if FourGame.currentPlayer() is not AI: reactor.callLater(1, self.makeNextTurn, AI) def ClientLeft(self, client, FourGame): GeneralEvent.removeListener( 'Table-Left-{}-{}'.format(client['id'], FourGame.table), self.ClientLeft) if client.engine not in self.Bots: return FourGame.remove(self.Bots[client.engine]['bot']) self.Bots[client.engine]['playing'] = None AI = self.Bots[client.engine]['bot'] AI['room'].send( 'sm', AI['id'], "I've completed my game with {}. Ready for next round!".format( client['nickname'])) def getFourBoard(self, engine): FourLounge = self.Bots[engine]['Room'] _id = FourLounge.ext_id RoomHandler = engine.roomHandler if not _id in RoomHandler.ROOM_CONFIG.FourGame: return None Tables = RoomHandler.ROOM_CONFIG.FourGame[_id] for table in Tables: table = RoomHandler.ROOM_CONFIG.FourGame[_id][table] if table.FourStarted == False and len(table.Waddling) == 0: return table return None @inlineCallbacks def attachBotToServer(self, engine, defer=None): if defer is not None: engine = defer if engine.type is not WORLD_SERVER: return if self.AI is None: self.AICreatedDefer.addCallback(self.attachBotToServer, engine) return AI = engine.protocol(engine) AI.dbpenguin = self.AI AI.penguin.id = self.AI.id # Nullify major methods AI.disconnect = AI.makeConnection = lambda *x, **y: None # might need this to identify next moves! AI.send = lambda *x: self.manipulateSend(AI, *x) AI.initialize() yield AI['RefreshHandler'].CacheInitializedDefer AI.penguin.x = 351 AI.penguin.y = 269 AI.penguin.frame = 24 FourLounge = engine.roomHandler.getRoomByExtId(220) # increasing difficulty may increase time to process next move self.Bots[engine] = { 'bot': AI, 'algorithm': FindFourAlgorithm(), 'difficulty': 3, 'Room': FourLounge, 'playing': None } # Attach algo to each FindFour game object created suring gameplay FourLounge.append(AI) self.logger.debug('FindFour AI added to %s', engine) def setupCommands(self): CommandsPlugin = self.dependencies[0] if self.Call_AI_Command not in CommandsPlugin.__commands__: CommandsPlugin.__commands__.append(self.Call_AI_Command) GeneralEvent.on('command={}'.format(self.Call_AI_Command.lower()), self.Play4) self.logger.debug("FindFour AI Call Command set. Command : %s", self.Call_AI_Command) # Maybe make a comprehensive link between a bot plugin and this AI, to a specific room? @inlineCallbacks def setupAI(self): AIExists = yield Penguin.exists(['`Username` = ?', self.AI_username]) if not AIExists: yield self.createAI() if self.AI is None: self.AI = yield Penguin.find( where=['Username = ?', self.AI_username], limit=1) @inlineCallbacks def createAI(self): self.AI = Penguin(username=self.AI_username, nickname="FindFour AI", password='', email='*****@*****.**') yield self.AI.save() yield self.AI.refresh() # update values from DB