用opensocial开发sns游戏 (5)

数据存储的Google App Engine实现

在开始之前先回顾一下目前的情况,已经做到的——将flash游戏放在GAE的空间上、在51上申请OpenSocial应用、通过xml描述页面、通过javascript调用OpenSocial得到好友信息供游戏使用。
最后要做的是——为用户提供游戏分数的存储以实现分数排行榜。

这一部分你可以参考Google App Engine 使用入门的数据库部分

首先定义要存储的数据模型。
在你的这个GAE项目的路径下,也就是app.yaml所在的目录,建立一个文件用于描述数据。我仿照示例建立一个db_model.py文件,内容如下:

0
1
2
3
4
5
from google.appengine.ext import db
 
class Scores(db.Model):
    owner_id = db.StringProperty()
    owner_name = db.StringProperty()
    owner_score = db.IntegerProperty()

这里我建立了一个名为Scores的数据类型,它有三个属性,分别是id(String)、name(String)和score(Int)。

其次加入向数据库中新建数据的方法。
javascript端要做的事情:
在游戏运行结束,显示了玩家的分数以后,我们加入一个“参加排行”的按钮。通过按下这个按钮调用javascript中自定义的submitScore函数,向其中传入三个参数,分别为玩家姓名、玩家:

0
1
2
3
4
5
6
7
8
9
10
11
function submitScore(id, name, score) {
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	post_data = gadgets.io.encodeValues({
		'owner_id' : id,
		'owner_name' : name,
		'score' : score.toString()});
	params[gadgets.io.RequestParameters.POST_DATA] = post_data;
	var url = 'http://yourappname.appspot.com/scores';
 
	gadgets.io.makeRequest(url, onLoad, params);
}

这一整段代码向我们的GAE项目的[url地址+“/scores”]发送了一个POST请求,同时附带了我们的姓名、ID和分数的数据。(在流程上,接下来应该是GAE的服务端处理这个POST请求并将数据存入数据库,但是为了开发的连贯性,先把javascript的东西都写完)
在上面的最后一行,gadgets.io.makeRequest(url, onLoad, params); 这一句是实际发出请求的语句,其中第一个是目标url,最后一个参数指定了我们访问的类型是POST,并且用户分数信息也包含在这里。第二个参数onLoad指定了一个回调函数,这个回调函数会返回可能的错误信息,表示POST请求是否成功。
下面是onLoad函数的具体内容:

0
1
2
3
4
5
6
function onLoad(response) {
	var params = {};
	params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	var url = 'http://yourappname.appspot.com/scores';
	gadgets.io.makeRequest(url, onLoadRecords, params);
}

我这里为了简单,并没有做错误检查,只是假定成功,然后做接下来的事情:得到分数排名信息。同样是对相同的url发出一个请求,所不同的是这次是一个GET请求(默认),同时指定返回JSON格式的数据。(不用管是什么格式,只要知道怎么用就好^_^)最后一样又指定了一个回调函数onLoadRecords,在这个回调函数里将得到返回的排行榜信息,解析以后返回给flash显示。

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function onLoadRecords(response) {
  var records = response.data;
 
	  var scorelist = new Array();
	  var namelist = new Array();
	  for (var i=0; i<records.length ; i++)
	  {
		  scorelist.push(records[i].uscore);
		  namelist.push(records[i].uname);
	  }
	  try{
			thisMovie('myFlashContent').sendScoreToAS(scorelist, namelist);
	  }catch (e) {
			alert(e.name + ": " + e.message);
	  } 
}

这里的操作步骤其实和之前文章(3)中的onLoadFriends很相似,通过一个sendScoreToAS将数据传给flash的actionscript。
总结一下flash和javascript的交互流程就是:按下提交分数的按钮->通过POST请求向GAE端写入分数->通过GET请求得到目前的分数排行信息->将信息返回通过flash显示。

GAE端要做的事情:
要做的事情其实就是实现对'http://yourappname.appspot.com/scores'这个URL的POST和GET请求。POST请求用于写入一个分数记录,GET请求用于返回分数排行。
在文章(2)的代码中有这么一句:

0
1
application = webapp.WSGIApplication([('/', MainHandler)],
                                       debug=True)

这句代码的意思是对于我们URL的任何访问都交给MainHandler来处理。那么现在我们加入用于处理"/scores"路径的函数。

0
1
application_paths = [('/', MainHandler), ('/scores', api.ApiServer)]
application = webapp.WSGIApplication(application_paths, debug=True)

这样就指定了,如果所访问的URL是以"/scores"开头,那么就交给api.ApiServer来访问。新建一个api.py文件,其中新建一个ApiServer类用于处理post和get请求。

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from google.appengine.ext import webapp
from google.appengine.ext import db
import logging
import json
# 之前定义的Scores数据模型
from db_model import Scores
class ApiServer(webapp.RequestHandler):
  def get(self):
    records = []
    topscores = []
    topscores = db.GqlQuery("SELECT * FROM Scores ORDER BY owner_score DESC LIMIT 10")
    for score in topscores:
      item = {'uid' : score.owner_id,
              'uname' : score.owner_name,
              'uscore' : score.owner_score
        }
      records.append(item)
    self.response.out.write(json.write(records))
  def post(self):
    gettedname = self.request.get('owner_name')
    gettedid = self.request.get('owner_id')
    gettedscore = self.request.get('score')
    new_score = Scores()
    new_score.owner_name = gettedname
    new_score.owner_id = gettedid
    new_score.owner_score = int(gettedscore)
    new_score.put()

在第5行导入了之前定义了分数的数据模型。7~17行实现对GET的请求,之后是对POST的请求。在处理POST是,所调用的三句self.request.get('key')中的key是和之前javascript中的submitScore中的三个键值对是对应的。得到这些信息后,新建一个Scores对象,赋值,最后通过put存入数据库中。
对GET请求的处理是通过执行一个数据库查询语句来得到分数最高的10个记录,也就是按分数降序排列的前10个记录。

0
("SELECT * FROM Scores ORDER BY owner_score DESC LIMIT 10")

通过这一句类似SQL的查询语句来完成。得到记录的查询结果后再依次访问每条记录,将记录信息写入一个数组通过json格式返回。返回的数据是由javascript中的onLoadRecords处理并传入flash。
以上内容可以参考GAE文档中的gql部分。

114条评论

  1. christophorgel:

    auto insurance quotes 0715 health insurance 8OOO health insurance quotes xwobdo auto insurance 85479

  2. beschriftung1:

    etna health insurance oiueir free health care insurance 035816 cheap life insurance ochp auto insurance 215860

  3. shilien:

    home insurance 62386 health insurance 97418 health insurance :DDD life insurance 428023

  4. tabunselbg:

    tramadol online in florida 8P ambien dgice discount phentermine wwxqdf xanax no prescription :OOO aciphex aciphex phentermine discount pharmacy inxovf cheap online aciphex %-[[[

  5. lowcarbdiettips:

    buy phentermine %[ are ultram pain pills addictive vzv buy tramadol us pharmacies %-) 2003 cialis levitra market sales viagra 8-[ ultram online gambling 8-[[[

  6. formatvorlage20:

    purchase xanax 36907 buy cialis kjy phentermine rbdvg valium npzrtq valium mbit accutane jtpo xanax xr >:-))) viagra 991445

  7. tarik:

    buy tramadol :-OO ultram 903 propecia 8038 xanax 8( tramadol :-D accutane 809529 ultram as antidepressant xoj

  8. druid:

    long term effects of xanax %))) accutane hghbph nasacort aciphex phentermine pharmacy pittsburgh bcf health insurance providers neqg supplemental health insurance >:] ultram >:]

  9. jochen:

    cialis sales 8PP cialis 73884 ultram 58159 cialis tadalafil =)) tramadol lkrvvg auto insurance quotes >:-((( aciphex :OO

  10. nataliya:

    diet pills phentermine 8-[[[ valium =(( levitra %-OOO xanax 68763 accutane =-]]] levitra =P

  11. desiree:

    ultram pill identifier udze buy propecia at discount price %-]]] accutane >:))) cialis levitra viagra >:-[[ buy cialis bjbix levitra levitra ooikw texas health insurance :-D

  12. traudl:

    ambien :-)) buy geneeric xanax 974861 actos phentermine aciphex imitrex 12887

  13. juliana:

    ultram %-OO aciphex phentermine pharmacy 534 health insurance zzkovr auto insurance quotes %-]

  14. dateline:

    online casino 63525 affordable health insurance 518 auto insurance xehokl health insurance 115 auto owners insurance 7146

  15. julian:

    prednisone online :-P buy phentermine lkh aciphex ewkd xanax 59509 carisoprodol 794237

  16. aarik:

    valium without a prescription etdlu retin a %-]]] ultram 744 retin a 420032

  17. wentylatory:

    xanax tmn ambien cr %[ ultram =PPP tramadol apap >:-((

  18. ludmila:

    valium 8-OO aciphex phentermine alprazolam online pharmacy hrgyf retin zoloft 155948 doxycycline 561789

  19. dylan:

    acomplia miracle diet pill qjo retin vplrrf plavix and aciphex 4922 accutane 388136

  20. bernard:

    buy prednisone zhmeck valium 038 retin a 378

  21. scottie:

    tramadol online in florida 550 tramadol lhalhr buy accutane qumvlu antivert pravachol aciphex actos nexium 18691

  22. liquid:

    propecia 47263 what is ambien vea buy ultram :-) cialis tadalafil 68712

  23. personalised:

    tramadol 88417 buy accutane %-[[ xanax online >:) ambien sleeping pill 583183

  24. chiara:

    accutane knfsre crownpills valium american express pay %-OO doxycycline xcfq ambien dosage %-O

  25. vrijemp3:

    buy intravenous tramadol sav propecia ncc accutane rari cialis 07859

  26. sovereign:

    buy accutane %[[ valium :-DDD buy prednisone vgfl

  27. msonormal:

    viagra propecia online gt %OOO ambien dosage komlb xanax withdrawal ksthww cialis %]]

  28. skyron:

    affordable health insurance ecpmus online casino fugq auto insurance 8))

  29. shilien:

    supplemental health insurance 43385 online casinos 31281 car insurance 321470 car insurance online 690

  30. tasisdorado:

    pennsylvania health insurance ncx online casino 360 auto insurance quotes =((( auto insurance =]]

  31. Pharmg327:

    Hello! eakcbgk interesting eakcbgk site!

  32. Pharmg69:

    Very nice site! [url=http://opeaixy.com/qsqasa/2.html]cheap cialis[/url]

  33. Pharme6:

    Very nice site!

  34. wally:

    online casino 603046 health insurance providers zgdlvv auto insurance 4848 auto insurance quotes oihfdu

  35. seo lace:

    I am havnig a difficult timeseeing your pags in SeaMonkey 1.2, just figuree I ight tell you abgotu it.

  36. icdexfjvky:

    ackxnlnler
    qtivkahvsv

  37. qzboacznxy:

    kfcftxiepb
    zgnbjtblrf

  38. dmfjhrhvnl:

    vgruyggkex
    yppoyckyiy

  39. ohfdremvqc:

    ctruyjrudu
    nriyftquih

  40. fikrgjhldw:

    qlziqxetvh
    fqbyyyjndq

  41. dvpskzinwy:

    txfqfqpcuv
    zfdatpdjvx

  42. ztsolzocly:

    vksbujdwrh
    qcvogskkey

  43. cooking videos:

    isolde video staind epiphany video magistrates yuo tube changing diaper video.

  44. dwarfs videos:

    geminid video grabba video tamaki hiroshi video groove video.

  45. feith videos:

    heaven yu tube locket video handbrake jerky video boss hoss yu tube.

  46. vidoe game mp3:

    glebe video ottawa halaka 2ftk video messianic vidoes verne lundquist u tube.

  47. Pharmk569:

    Hello! degdecd interesting degdecd site!

  48. Pharmf312:

    Very nice site! [url=http://opeyixa.com/rvqatx/2.html]cheap cialis[/url]

  49. Pharme229:

    Very nice site!

  50. payday loans canada:

    Your website is very the most interesting. I liked your website a lot. Thank you.

  51. payday loans toronto:

    Your website is very the most interesting. I loved your website a lot. Thank you.

  52. jazvplws:

    jazvplws...

    jazvplws...

  53. toronto payday loans:

    gameandvision.com is great! Having the internet around has changed our lives in a huge way Getting a loan through the web is now easier than having to go to Internet payday loans are easy to come by and the requirements arent as cumbersome as you think The most important thing is to shop around for the lowest interest

  54. peachmoofinz:

    counting cards in hold'em poker 32737 generic viagra cialis pills >:P celebrex effectiveness and use =-[[[ cheap phentermine pills us licensed pharmacies dcekkd credit card consolidation agencies 77416

  55. flash gae:

    flash gae...

    Great article! I really enjoyed reading this....

  56. neilbetter:

    bare necessities midi file >:-OO richard wagner midis eslius black jack gamble 802 fake prepaid credit cards 8834 auto quote insurance gwe

  57. GWGOSS:

    weaning off effexor :-(( mortgage loan qualifer 16303 add electronic forms in adobe contribute ljnztf dogs playing poker shower curtain =-O adobe pdf editor program nwxvk

  58. Pharmg114:

    Hello! fkdadfk interesting fkdadfk site!

  59. Pharmk660:

    Very nice site! [url=http://opxaiey.com/oyyrsry/2.html]cheap cialis[/url]

  60. Pharmd583:

    Very nice site!

  61. payday loan:

    Your blog page is excellent. Give thanks to you truly for sharing a lot interesting insight. I will bookmark bookmark your website and will be certainly coming back. Once again, I admire all your work additionally providing lots of vital facts for the readers.

  62. payday loans:

    Thanks for good news! Your site is very useful for me. I bookmarked your site!

  63. bc loans:

    pnqpjakiqpowoijqeknqrtvmsacayvcpplv

  64. Critical Illness Insurance:

    Critical Illness Insurance...

    How can you be so sure about 用opensocial开发sns游戏 (5) | 游戏边玩边做 ? Although most of the information provided is true as per my knowledge but I don't agree fully. I think it should be more practical. I visited your website while searc...

  65. Mr. Payday Easy Loans Inc.:

    Greetings everyone, This webpage is exceptional and so is how the matter was expanded. I like some of the comments too although I would prefer we all maintain it on topic in order add value to the subject. wndkayvxmdlalxlnnymcevvsotnghqewdpl
    Mr. Payday Easy Loans Inc.

发表评论