def _arrange_top_left_corner_tile(tile_db: TileDB, corner: Tile): lone_edges = corner.lone_edges(tile_db) times = 0 while lone_edges not in [(Edge.U, Edge.L), (Edge.L, Edge.U)]: times += 1 lone_edges = tuple([Edge((edge.value + 1) % 4) for edge in lone_edges]) corner.rotate(times=times)
def post(self): tile = Tile() tile.x = int(self.request.get("x")) tile.y = int(self.request.get("y")) tile.height = int(self.request.get("height")) tile.type = int(self.request.get("type")) tile.put()
def get(self): """ Generate a response to /tile?x=<tileX>&y=<tileY> If a record exists in the datastore for tileX, tileY, returns a png image from the blobstore corresponding to that tile. Otherwise, returns a 404 error status. """ #Get Parameters x = int(self.request.get('x')) y = int(self.request.get('y')) #Get record for tile from the datastore query = Tile.gql("WHERE x = :1 AND y = :2", x, y) myTile = query.get() if myTile is None: #No corresponding tile data, return 404 status self.response.set_status(404) else: #Set headers indicating response is a png image self.response.headers["content-type"] = "image/png" #Get png image from blobstore blob_reader = blobstore.BlobReader(myTile.blob_key) #Return the image as the response. self.response.write(blob_reader.read())
def get(self): #move the unit towards the x and y goto positions #xy = re.match('tile(\d+)', self.request.get("tile_id")).groups() x_goto = int(self.request.get("x-goto")) y_goto = int(self.request.get("y-goto")) unitID = int(re.match('unit(\d+)', self.request.get("unitid")).group(1)) destinationTile = Tile.gql("where x = :1 ans y = :2",x_goto, y_goto); if destinationTile.type.canTravel: # just select the unit with that id unit = Unit.get_by_id(unitID) if unit.x > x_goto: unit.x = unit.x - 1 elif unit.x < x_goto: unit.x = unit.x + 1 if unit.y > y_goto: unit.y = unit.y - 1 elif unit.y < y_goto: unit.y = unit.y + 1 unit.put() self.response.out.write("ok") else: self.response.out.write("obstructed")
def start(): red = db.session.query(Team).filter_by(team='red').first() blue = db.session.query(Team).filter_by(team='blue').first() death = db.session.query(Team).filter_by(team='death').first() neutral = db.session.query(Team).filter_by(team='neutral').first() potential_first = [red, blue] first = potential_first[random.getrandbits(1)] game = Game(first=first.team) db.session.add(game) db.session.commit() db.session.refresh(game) tiles = (([red] * 8) + ([blue] * 8) + ([neutral] * 7) + [death] + [first]) random.shuffle(tiles) deck = Card.query.all() random.shuffle(deck) cards = deck[:25] board = [] results = {'game': game.id, 'first': game.first, 'cards': []} for idx, card in enumerate(cards): team = tiles.pop() cur_card = Tile(game, card, team, idx) db.session.add(cur_card) board.append(cur_card) results['cards'].append({ 'card': card.serialize, 'team': team.serialize }) db.session.commit() return jsonify(results)
def parse(filename: str) -> TileDB: tile_defs = open(filename).read().strip().split("\n\n") tiles = TileDB() for tile_def in tile_defs: tile_def = tile_def.split("\n") tile_id = int(tile_def[0].strip().split()[1][:-1]) tile_def = tuple(map(tuple, tile_def[1:])) tiles.add(Tile(tile_id, tile_def)) return tiles
def get(self, location=''): """ Shows login button if not logged in, otherwise shows logout. Creates a new channel for use with live updates and chat. If location is unspecified, use a random initial tile. Output created using template index.html :param location: x, y of tile to display when opening the graffiti wall """ #Check if user is logged in. user = users.get_current_user() if user: #If so, show logout button login_url = users.create_logout_url(self.request.uri) login_label = 'logout' user_login = 1 else: #If not, show login button login_url = users.create_login_url(self.request.uri) login_label = 'login' user_login = 0 #For live updates token = self.session.get('token') if token is None: channel_id = (str(datetime.now()) + "," + str(random.randint(1, 10000))) token = channel.create_channel(channel_id) self.session['channel_id'] = channel_id self.session['token'] = token ch = UpdateChannel(channel_id=channel_id) ch.put() #Get random initial tile rand_num = random.random() tile = Tile.gql("WHERE rand_num >= :1 ORDER BY rand_num", rand_num).get() if tile is None: locX = 0 locY = 0 else: locX = tile.x locY = tile.y #Output from template template = jinja_environment.get_template('index.html') self.response.out.write(template.render( login_url=login_url, login_label=login_label, token=token, locX=locX, locY=locY, adnum=random.randint(0, 4), user_login=user_login))
def api(request,z,x,y): datauri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' post = request.POST arurl = post['arurl'] #magic imgstr = re.search(r'base64,(.*)', arurl).group(1) tempimg = cStringIO.StringIO(imgstr.decode('base64')) im = Image.open(tempimg) image_pre_path = '%s/%s/'%(z,x) image_path = os.path.join("/home/panosfirbas/webapps/static_mandelbrot/media/"+image_pre_path) if not os.path.exists(image_path): os.makedirs(image_path) im.save(image_path +y+ '.png', 'PNG') tile = Tile(z=z,x=x,y=y) tile.save() return HttpResponse("1")
def tile(self): z = 11 x = randint(496,523) y = randint(772,797) try: z,x,y = map(int,[z,x,y]) tid = "t:%s:%d+%d+%d"%(self.ts.shpfile,z,x,y) tile = Tile.get_by_key_name(tid) if tile: self._tile = tile return tile else: shpfile = memcache.get(self.ts.shpfile.encode('utf8')) if not shpfile: shpfile = Shapefile.get_by_key_name(self.ts.shpfile) memcache.set(self.ts.shpfile.encode('utf8'),shpfile) typ,dat = shpfile.raw_tile(x,y,z) tile = Tile(tid) tile.typ = typ tile.dat = str(dat) tile.put() self._tile = tile return tile except: raise return False return False
def api(request, z, x, y): datauri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' post = request.POST arurl = post['arurl'] #magic imgstr = re.search(r'base64,(.*)', arurl).group(1) tempimg = cStringIO.StringIO(imgstr.decode('base64')) im = Image.open(tempimg) image_pre_path = '%s/%s/' % (z, x) image_path = os.path.join( "/home/panosfirbas/webapps/static_mandelbrot/media/" + image_pre_path) if not os.path.exists(image_path): os.makedirs(image_path) im.save(image_path + y + '.png', 'PNG') tile = Tile(z=z, x=x, y=y) tile.save() return HttpResponse("1")
def get(self): map = memcache.get("map") HeightMapData = FetchImage("http://humanitymmo.appspot.com/static/earthmini.png") w,h = HeightMapData[:2] # should get the tiles, within proximity of units. # foreach unit, get tiles within range of the unit # in this instance limit it to 1 unit only unit = Unit.get_by_id( int(self.request.get("id")) ) json = {"tiles":[],"enemyunits":[]} fov = 2 # fov is how many tiles a unit can see around it xleft = max(unit.x - fov, 0) xright = min(unit.x + fov + 1, w) ytop = max(unit.y - fov, 0) ybottom = min(unit.y + fov + 1, h) # get heightmap based tiles for x in range(xleft, xright): for y in range(ytop, ybottom): # is the tile in the datastore curTile = Tile.gql("where x = :1 and y = :2", x,y) if curTile.count() > 0: if curTile.type.canTravel: curAlt = 80 else: curAlt = 81 json["tiles"].append( {"x":curTile.x,"y":curTile.y,"alt":curAlt} ) else alt = GetHeightAt(x,y,HeightMapData) json["tiles"].append( {"x":x, "y":y, "alt":alt } ) # write to datastore t = Tile() t.x = x t.y = y t.height = alt if alt < 81: # get tile type where name = water, then reference it else: # get tile type for land t.put() self.response.out.write(demjson.encode(json))
def get_tile(self,z,x,y): tid = "t:%s:%d+%d+%d"%(self.ts.name,z,x,y) tile = memcache.get(tid) if tile is not None: self._tile = tile return True tile = Tile.get_by_key_name(tid) if tile: #if tile.typ == 'B': # tile.delete() # return False #if not memcache.add(tid, tile): # logging.error("Memcache set failed [ %s ]"%tid) self._tile = tile return True return False
def tile(self): if self._tile and not self._get_raw: return self._tile if not self.ts: return False get = self.request.REQUEST.get x = get('x') y = get('y') z = get('z') b = True if get('b',-1) == '0': b = False if not (x and y and z): return False try: z,x,y = map(int,[z,x,y]) if self._get_raw: shpfile = Shapefile.get_by_key_name(self.ts.shpfile) png = shpfile.raw_png(x,y,z,border=b) return png if b: tid = "t:%s:%d+%d+%d"%(self.ts.shpfile,z,x,y) else: tid = "u:%s:%d+%d+%d"%(self.ts.shpfile,z,x,y) tile = Tile.get_by_key_name(tid) if tile: self._tile = tile return tile else: logger.info("Creating tile x%d,y%d,z%d of %s"%(x,y,z,tid)) shpfile = memcache.get(self.ts.shpfile.encode('utf8')) if not shpfile: shpfile = Shapefile.get_by_key_name(self.ts.shpfile) memcache.set(self.ts.shpfile.encode('utf8'),shpfile) typ,dat = shpfile.raw_tile(x,y,z,border=b) tile = Tile(tid) tile.typ = typ tile.dat = str(dat) tile.put() self._tile = tile return tile except: logger.error("Exception occured while Getting or Creating Tile (x%d,y%d,z%d)"%(x,y,z)) return False return False
def find_tile(self,z,x,y): if z is not None and x is not None and y is not None and self.ts: z,x,y = map(int,(z,x,y)) #logging.info('Find Tile: %d+%d+%d'%(z,x,y)) if self.get_tile(z,x,y): return self._tile elif self.valid_tile(z,x,y): #logging.info('Tile: %d+%d+%d Not Found, will search'%(z,x,y)) while z: z-=1 x_quad = x&1 y_quad = y&1 x = x>>1 y = y>>1 #logging.info('Tile: search %d+%d+%d'%(z,x,y)) if self.get_tile(z,x,y): #logging.info('Tile: found %d+%d+%d'%(z,x,y)) regionID = query.query(self._tile,qx=x_quad,qy=y_quad) #logging.info('Region ID: %d'%(regionID)) #logging.info('Quad x,y: (%d,%d)'%(x_quad,y_quad)) t = Tile() t.dat = str(regionID) if regionID == 0: t.typ = 'A' else: t.typ = 'B' self._tile = t return self._tile else: #logging.info('Tile: %d+%d+%d Is Not Valid'%(z,x,y)) return False else: #logging.info('not z,x,y or ts') t =Tile() t.dat = '0' t.typ = 'A' self._tile = t return self._tile return False
def loadLevel(tileData, decorationData, outputLevel): for y in range(0, 16): for x in range(0, 16): if tileData[y][x] == 'W': tile = Tile('wall', False) tile.image = choice(wallTextures) tile.offsetY = -16 * gameScale elif tileData[y][x] == 'c': tile = Tile('ceiling', True) tile.image = choice(ceilingTextures) tile.offsetY = 0 else: tile = Tile('floor', True) tile.image = choice(floorTextures) tile.offsetY = 0 if decorationData[y][x] == 'c': dec = Tile('ceiling', True) dec.image = choice(ceilingTextures) dec.offsetY = -16 * 2 * gameScale else: dec = None outputLevel.setTileAt(x, y, tile) outputLevel.setDecorationAt(x, y, dec)
def get_tiles(): tiles = Tile.get_all_tiles() return jsonify([tile.to_json() for tile in tiles])
def get(self): #Assure that the user is logged in #There is no way of mocking the user servise #As the system that google app engine provides deos not work user = users.get_current_user() if user: self.testbed = testbed.Testbed() self.testapp = webtest.TestApp(app) #activates the testbed (Used for creating face DB and blobstore) #Swaps the fake systems in for the real systems #Should make this only work offline self.testbed.activate() #Initializes the fake blobstore and datastore self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() ########################## # MainPage Unit Testing ########################## AllParts = 0 #Unit test for MainPage (MainPage_test1) #Checks to assure that the main page can load try: response = self.testapp.get('/') MainPage_test1 = "<font color=green>Passed</font>" #Unit test for MainPage (MainPage_test3) #Checks to assure that the page has a section "wall" try: response.mustcontain('<section id="wall">') MainPage_test3 = "<font color=green>Passed</font>" AllParts = AllParts + 1 except: MainPage_test3 = ("<font color=red>Failed, the main " + "page did not contain a section with ID wall.</font>") #Unit test for MainPage (MainPage_test4) #Checks to assure that the page has the directional scrolling divs try: response.mustcontain('<div id="left">') response.mustcontain('<div id="right">') response.mustcontain('<div id="top">') response.mustcontain('<div id="bottom">') response.mustcontain('<div id="top_left">') response.mustcontain('<div id="top_right">') response.mustcontain('<div id="bottom_left">') response.mustcontain('<div id="bottom_right">') MainPage_test4 = "<font color=green>Passed</font>" AllParts = AllParts + 1 except: MainPage_test4 = ("<font color=red>Failed, the main page " + "did not contain a section with ID wall.</font>") #Unit test for MainPage (MainPage_test2) #Checks to assure that the page has the specified sections if AllParts == 2: MainPage_test2 = "<font color=green>Passed</font>" else: MainPage_test2 = ("<font color=red>Failed, this is " + "not the page as it was intended..</font>") except: MainPage_test1 = ("<font color=red>Failed, the main page " + "did not respond at all.</font>") MainPage_test3 = ("<font color=red>Can't be run " + "if test 1 fails.</font>") #Unit test for MainPage (MainPage_test4) #Check to assure that the random tile is retrieved correctly #Creating fake tile to test tile reading with open("UnitTestTile.png", "rb") as image_file: imageFile = image_file.read() image_file.close() blob_key = 'TestBlobkey' self.testbed.get_stub('blobstore').CreateBlob(blob_key, imageFile) #rand_num=1 to be always selected in a random selection Tile(x=-12, y=-1, blob_key=blobstore.BlobKey(blob_key), rand_num=1).put() try: response = self.testapp.get('/') try: response.mustcontain('<input id="locX" type="hidden" value="-12">') response.mustcontain( '<input id="locY" type="hidden" value="-1">') MainPage_test5 = "<font color=green>Passed</font>" except: MainPage_test5 = ("<font color=red> The start location " + "was not correct. </font>") except: MainPage_test5 = ("<font color=red> The location based page " + "failed to load. </font>") ########################## # GetTile Unit Testing ########################## #Reinitializes the fake blobstore and datastore for the next test self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() #Creating fake tile to test tile reading with open("UnitTestTile.png", "rb") as image_file: imageFile = image_file.read() image_file.close() with open("UnitTestTile2.png", "rb") as image_file2: imageFile2 = image_file2.read() image_file2.close() blob_key = 'TestBlobkey' self.testbed.get_stub('blobstore').CreateBlob(blob_key, imageFile) Tile(x=0, y=0, blob_key=blobstore.BlobKey(blob_key), rand_num=random.random()).put() params = {'x': 0, 'y': 0} #Unit test for get tile (GetTile_test1) #Checks to assure that the file can load at all try: response = self.testapp.get('/tile', params) GetTile_test1 = "<font color=green>Passed</font>" #Unit test for get tile (GetTile_test2) #Checks to assure that the file can load correctly try: response.mustcontain(imageFile) GetTile_test2 = "<font color=green>Passed</font>" except: GetTile_test2 = ("<font color=red>Failed, the " + "response did not contain the test image file</font>") #Unit test for get tile (GetTile_test3) #Checks to assure that the mach in test 1 is not erroneous try: response.mustcontain(imageFile2) GetTile_test3 = ("<font color=red>Failed, the tile " + "retrieved does not correspond to the tile put in.</font>") except: GetTile_test3 = "<font color=green>Passed</font>" except: GetTile_test1 = ("<font color=red>Failed, there was no " + "response from the mock database.</font>") GetTile_test2 = ("<font color=red>Can't be run " + "if test 1 fails.</font>") GetTile_test3 = GetTile_test2 #Unit test for get tile (GetTile_test4) #Checks to assure that a tile that does not #exist in the database does not load params = {'x': 0, 'y': 1} try: self.testapp.get('/tile', params) GetTile_test4 = ("<font color=red>The load did not " + "fail as it was intended to</font>") except: GetTile_test4 = "<font color=green>Passed</font>" ########################## # SaveTile Unit Testing ########################## #Reinitializes the fake blobstore and datastore for the next test self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() #We can't actualy create an object in the test bed Datastore with open("UnitTestTile.png", "rb") as image_file: imageFile = base64.b64encode(image_file.read()) image_file.close() #The perameters to create a blob at x=0,y=0 params = {'x': 0, 'y': 0, 'data': imageFile} #Test if there is even a responce from /save try: response = self.testapp.post('/save', params) if response.status_int == 200: #test to see if the created tile actualy exists query = Tile.gql("WHERE x = :1 AND y = :2", 0, 0) myTile = query.get() if myTile is None: SaveTile_test1 = ("<font color=red>The tile data could not be retrieved from the database.</font>") SaveTile_test2 = ("<font color=red>Test 2 requires test 1 to succeed.</font>") else: SaveTile_test1 = ("<font color=green>Passed</font>") oldblobkey = myTile.blob_key try: response = self.testapp.post('/save', params) if response.status_int == 200: query = Tile.gql("WHERE x = :1 AND y = :2", 0, 0) myTile = query.get() if myTile.blob_key == oldblobkey: SaveTile_test2 = ("<font color=red>The tile was not replaced.</font>") else: SaveTile_test2 = ("<font color=green>Passed</font>") else: SaveTile_test2 = ("<font color=red>/save did not return a 200 responce.</font>") except: SaveTile_test1 = ("<font color=red>Failed, there was no " + "response from SaveTile.</font>") else: SaveTile_test1 = ("<font color=red>/save did not return a 200 responce.</font>") SaveTile_test2 = ("<font color=red>Test 2 requires test 1 to succeed.</font>") except: SaveTile_test1 = ("<font color=red>Failed, there was no " + "response from SaveTile.</font>") SaveTile_test2 = ("<font color=red>Test 2 requires test 1 to succeed.</font>") ########################## # UserTileClaimNumber Unit Testing ########################## #Reinitializes the fake blobstore and datastore for the next test self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() #Check if the system can handle a user who has not been entered yet try: response = self.testapp.get('/howmenytiles') query = UserData.gql("WHERE user = :1", user) thisUserData = query.get() if thisUserData is None: UserTileClaimNumber_test1 = ("<font color=red>The new user information was not created in the database.</font>") else: if thisUserData.Number_Tiles == 0: UserTileClaimNumber_test1 = ("<font color=green>Passed</font>") else: UserTileClaimNumber_test1 = ("<font color=red>UserTileClaimNumber did not create a user information with 0 tiles claimed.</font>") except: UserTileClaimNumber_test1 = ("<font color=red>Failed, there was no response from UserTileClaimNumber.</font>") #Reinitializes the fake datastore for the next test self.testbed.init_datastore_v3_stub() #Assure data about users is retrieved correctly day_time = datetime.today() - timedelta(1) UserData(user=user, lastemail=day_time, Number_Tiles=6).put() try: response = self.testapp.get('/howmenytiles') try: #Check if the correct number of tiles information was contianed in the resoponce response.mustcontain(6) UserTileClaimNumber_test2 = ("<font color=green>Passed</font>") except: UserTileClaimNumber_test2 = ("<font color=red>The correct number of tiles was not returned.</font>") except: UserTileClaimNumber_test2 = ("<font color=red>Failed, there was no response from UserTileClaimNumber.</font>") ########################## # CreateClaim Unit Testing ########################## #Reinitializes the fake blobstore and datastore for the next test self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() params = {'x': 0, 'y': 0} day_time = datetime.today() - timedelta(1) UserData(user=user, lastemail=day_time, Number_Tiles=0).put() try: response = self.testapp.post('/claim', params) try: query = Claim.gql("WHERE user = :1", user) thisClaimData = query.get() if thisClaimData is not None: CreateClaim_test1 = ("<font color=green>Passed</font>") query = Claim.gql("WHERE user = :1 AND x=:2 AND y=:3", user, 0, 0) thisClaimData2 = query.get() if thisClaimData2 is not None: CreateClaim_test2 = ("<font color=green>Passed</font>") else: CreateClaim_test2 = ("<font color=red>The correct database claim did not exist.</font>") else: CreateClaim_test1 = ("<font color=red>Failed, no claim created for the given user.</font>") CreateClaim_test2 = ("<font color=red>Test1 must succeed for test 2 to run.</font>") except: CreateClaim_test1 = ("<font color=red>Failed, database error.</font>") CreateClaim_test2 = ("<font color=red>Test1 must succeed for test 2 to run.</font>") except: CreateClaim_test1 = ("<font color=red>Failed, there was no response from CreateClaim.</font>") CreateClaim_test2 = ("<font color=red>Test1 must succeed for test 2 to run.</font>") ########################## # InformClaimOwner Unit Testing ########################## #Reinitializes the fake blobstore and datastore for the next test self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() #For this test we need to check if we are sending mail. self.testbed.init_mail_stub() self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) params = {'x': 0, 'y': 0} #Create a fake user with 1 tile claimed day_time = datetime.today() - timedelta(1) UserData(user=user, lastemail=day_time, Number_Tiles=1).put() Claim(user=user, x=0, y=0).put() try: response = self.testapp.post('/informclaim', params) messages = self.mail_stub.get_sent_messages(to=user.email()) if len(messages) == 1: InformClaimOwner_test1 = ("<font color=green>Passed</font>") try: response = self.testapp.post('/informclaim', params) messages = self.mail_stub.get_sent_messages(to=user.email()) if len(messages) == 1: InformClaimOwner_test2 = ("<font color=green>Passed</font>") else: InformClaimOwner_test2 = ("<font color=red>Failed, a second message was sent on the same day.</font>") except: InformClaimOwner_test2 = ("<font color=red>Failed, there was no response from InformClaimOwner.</font>") else: InformClaimOwner_test1 = ("<font color=red>Failed, the informing email was not sent to the target user.</font>") InformClaimOwner_test2 = ("<font color=red>Test 2 requires test 1 to succeed.</font>") except: InformClaimOwner_test1 = ("<font color=red>Failed, there was no response from InformClaimOwner.</font>") InformClaimOwner_test2 = ("<font color=red>Test 2 requires test 1 to succeed.</font>") ########################## # RemoveClaim Unit Testing ########################## #Reinitializes the fake blobstore and datastore for the next test self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() params = {'x': 0, 'y': 0} #Create a fake user with 1 tile claimed day_time = datetime.today() - timedelta(1) UserData(user=user, lastemail=day_time, Number_Tiles=1).put() Claim(user=user, x=0, y=0).put() try: response = self.testapp.post('/unclaim', params) query = Claim.gql("WHERE user = :1 AND x=:2 AND y=:3", user, 0, 0) thisClaimData = query.get() if thisClaimData is None: RemoveClaim_test1 = ("<font color=green>Passed</font>") else: RemoveClaim_test1 = ("<font color=red> The claim was not removed.</font>") except: RemoveClaim_test1 = ("<font color=red>Failed, there was no response from RemoveClaim.</font>") try: query = UserData.gql("WHERE user = :1", user) thisUserData = query.get() if thisUserData.Number_Tiles == 0: RemoveClaim_test2 = ("<font color=green>Passed</font>") else: RemoveClaim_test2 = ("<font color=red>Failed, The user's Number_Tiles was not decremented correctly.</font>") except: RemoveClaim_test2 = ("<font color=red>Failed, there was no response from the mock database.</font>") ########################## # TileClaimedByUser Unit Testing ########################## #Reinitializes the fake blobstore and datastore for the next test self.testbed.init_blobstore_stub() self.testbed.init_datastore_v3_stub() params = {'x': 0, 'y': 0} #Create a fake user with 1 tile claimed day_time = datetime.today() - timedelta(1) UserData(user=user, lastemail=day_time, Number_Tiles=1).put() Claim(user=user, x=0, y=0).put() try: response = self.testapp.get('/hasclaimontile', params) try: response.mustcontain(1) TileClaimedByUser_test1 = ("<font color=green>Passed</font>") except: TileClaimedByUser_test1 = ("<font color=red>Failed, did not detect user's claim.</font>") except: TileClaimedByUser_test1 = ("<font color=red>Failed, there was no response from TileClaimedByUser.</font>") params = {'x': 1, 'y': 0} try: response = self.testapp.get('/hasclaimontile', params) try: response.mustcontain(0) TileClaimedByUser_test2 = ("<font color=green>Passed</font>") except: TileClaimedByUser_test2 = ("<font color=red>Failed, did not detect user's claim.</font>") except: TileClaimedByUser_test2 = ("<font color=red>Failed, there was no response from TileClaimedByUser.</font>") #Swaps the real systems back in, #and deactivates the fake testing system. self.testbed.deactivate() template = jinja_environment.get_template('PYUnitTest.html') self.response.out.write(template.render( MainPage_test1=MainPage_test1, MainPage_test2=MainPage_test2, MainPage_test3=MainPage_test3, MainPage_test4=MainPage_test4, MainPage_test5=MainPage_test5, GetTile_test1=GetTile_test1, GetTile_test2=GetTile_test2, GetTile_test3=GetTile_test3, GetTile_test4=GetTile_test4, SaveTile_test1=SaveTile_test1, SaveTile_test2=SaveTile_test2, UserTileClaimNumber_test1=UserTileClaimNumber_test1, UserTileClaimNumber_test2=UserTileClaimNumber_test2, CreateClaim_test1=CreateClaim_test1, CreateClaim_test2=CreateClaim_test2, InformClaimOwner_test1=InformClaimOwner_test1, InformClaimOwner_test2=InformClaimOwner_test2, RemoveClaim_test1=RemoveClaim_test1, RemoveClaim_test2=RemoveClaim_test2, TileClaimedByUser_test1=TileClaimedByUser_test1, TileClaimedByUser_test2=TileClaimedByUser_test2 )) else: #If not, show login button template = jinja_environment.get_template('PYUnitTestLogin.html') self.response.out.write(template.render())
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import models from models import Character, Tile Base.metadata.create_all(bind=engine) # Seed characters in the database medic = Character( "Medic", "The ships medic. Not much of a fighter, but he has regenerating health.", 1000, 4, 5, 2) infiltrator = Character( "Infiltrator", "The infiltrator was just hitching a ride. Greater movement speed.", 1000, 6, 5, 0) engineer = Character( "Engineer", "The chief engineer on board the ship. Decreased hacking times.", 1000, 4, 3, 0) security = Character( "Security", "The head of security aboard the ship. He benefits from additional health.", 1250, 4, 5, 0) captain = Character( "Captain", "The ships captain. Jack of all trades, master of none.", 1100, 5, 4, 1) hal = Character("HAL", "The homicidal computer causing this mess!", 1000, 100, 0, 10) db_session.add(medic) db_session.add(infiltrator) db_session.add(engineer) db_session.add(security) db_session.add(captain) db_session.add(hal) # Seed the game map tile00 = Tile(0, 0, 3, 0) tile01 = Tile(0, 1, 3, 0) tile02 = Tile(0, 2, 3, 0) tile03 = Tile(0, 3, 3, 0) tile10 = Tile(1, 0, 3, 0) tile11 = Tile(1, 1, 6, 0) tile12 = Tile(1, 2, 6, 0) tile13 = Tile(1, 3, 3, 0) tile20 = Tile(2, 0, 3, 0) tile21 = Tile(2, 1, 6, 0) tile22 = Tile(2, 2, 1, 1) tile23 = Tile(2, 3, 3, 0) tile30 = Tile(3, 0, 3, 0) tile31 = Tile(3, 1, 3, 0) tile32 = Tile(3, 2, 3, 0) tile33 = Tile(3, 3, 3, 0) db_session.add(tile00) db_session.add(tile01) db_session.add(tile02) db_session.add(tile03) db_session.add(tile10) db_session.add(tile11) db_session.add(tile12) db_session.add(tile13) db_session.add(tile20) db_session.add(tile21) db_session.add(tile22) db_session.add(tile23) db_session.add(tile30) db_session.add(tile31) db_session.add(tile32) db_session.add(tile33) # Commit seeds db_session.commit()
def post(self): """ Saves the image sent via JSON in the blobstore. If an entry for (x, y) is not in the Tile table of the datastore, create it with the blob key for the image. Otherwise update the entry with the new blob key and delete the existing associated blob. Send messages to any open channel that a change has been made to the tile. Delete any channels that may have been open for more than two hours. """ #Get JSON data x = int(self.request.get('x')) y = int(self.request.get('y')) data = self.request.get('data') #base64 decode image data = base64.b64decode(data) #Write image to blobstore file_name = files.blobstore.create(mime_type='image/png') with files.open(file_name, 'a') as f: f.write(data) files.finalize(file_name) #Get blob key for newly created blob in blobstore blob_key = files.blobstore.get_blob_key(file_name) # Check if tile is already in database query = Tile.gql("WHERE x = :1 AND y = :2", x, y) myTile = query.get() if myTile is None: #Create new tile entry in database with key to new blob myTile = Tile(x=x, y=y, blob_key=blob_key, rand_num=random.random()) myTile.put() else: #Update the blob key in the entry for this tile old_key = myTile.blob_key myTile.blob_key = blob_key myTile.put() #Delete the blob previously associated with the tile google.appengine.ext.blobstore.delete(old_key) #For live updates: #Send a message to the channels indicating this tile has changed. channels = UpdateChannel.gql("").fetch(100) message = json.dumps({"x": x, "y": y, "Type": "Tile"}) for ch in channels: ch_id = ch.channel_id #if a channel is two hours old, delete it. d = parse_datetime(ch_id.split(",")[0]) if d < datetime.now() + timedelta(hours=-2): ch.key.delete() elif ch_id != self.session.get("channel_id"): channel.send_message(ch.channel_id, message) #No response data to send. self.response.set_status(200)