Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5119587
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2012-02-24 14:16:52

服务端 server.py
  1. # -*- coding: UTF-8 -*-
  2.   #Twisted MMORPG
  3.   from twisted.internet.protocol import Factory
  4.   from twisted.protocols.basic import LineOnlyReceiver
  5.   from twisted.internet import reactor
  6.   import random
  7.   import string
  8.     
  9.   class Game(LineOnlyReceiver):
  10.      def lineReceived(self, data):
  11.          self.factory.sendAll("%s" % (data))
  12.      def getId(self):
  13.          return str(self.transport.getPeer())
  14.      def connectionMade(self):
  15.          print "New User Login:", self.getId()
  16.          self.transport.write("欢迎来到MMO世界!\n")
  17.          self.factory.addClient(self)
  18.      def connectionLost(self, reason):
  19.          self.factory.delClient(self)
  20.             
  21. class GameFactory(Factory):
  22.      protocol = Game
  23.      def __init__(self):
  24.          self.clients = []
  25.          self.player = []
  26.          self.msg=''
  27.          self.x = range(100,700)
  28.          self.y = range(100,500)
  29.      def getPlayerId(self):
  30.          return len(self.player)
  31.      def addClient(self, newclient):
  32.             self.clients.append(newclient)
  33.      def delClient(self, client):
  34.          self.clients.remove(client)
  35.      def sendAll(self, data):
  36.          #print data
  37.          if data.find('')!=-1:
  38.              proto.transport.write('\0')
  39.          else:
  40.              arr = data.split(':')
  41.              prefix = arr[0]
  42.              content = arr[1]
  43.              if prefix.find('player')!=-1:
  44.                   newPlayer = [content,str(random.randrange(200, 600)),str(random.randrange(150,350)),str(random.randrange(1,5))]
  45.                   self.player.append(newPlayer)
  46.                   self.msg = ' 玩家 '+content+' 进入游戏!'
  47.                   #广播所有玩家的位置
  48.                   temp = []
  49.                   playerData = ':::'
  50.                   for pos in self.player:
  51.                       temp.append(string.join(pos,'---'))
  52.                   playerData = playerData+string.join(temp,'***')
  53.                   for proto in self.clients:
  54.                       proto.transport.write('[系统]: '+self.msg+'\n')
  55.                       proto.transport.write(playerData)
  56.              elif prefix.find('pos')!=-1:
  57.                  playerName,x,y = content.split('---')
  58.                  i = 0
  59.                  for p in self.player:
  60.                      if p[0]==playerName:
  61.                          p[1]=x
  62.                          p[2]=y
  63.                  for proto in self.clients:
  64.                      proto.transport.write(data)
  65.              else:
  66.                  self.msg = data
  67.                  for proto in self.clients:
  68.                       proto.transport.write(self.msg+'\n')
  69.                 
  70. reactor.listenTCP(8006, GameFactory())
  71. reactor.run()
客户端 client.mxml
 
  1. width="850" height="510" horizontalScrollPolicy="off" verticalScrollPolicy="off" applicationComplete="init();">
  2. import mx.containers.Canvas;
  3. import mx.controls.Alert;
  4. import mx.controls.TextArea;
  5. import flash.net.Socket;
  6. import flash.utils.ByteArray;
  7. import flash.events.SecurityErrorEvent;
  8. import flash.events.IOErrorEvent;
  9. import flash.events.ProgressEvent;
  10. import mx.controls.Image;
  11. import mx.effects.Move;
  12. public var oSocket:Socket = new Socket();
  13. [Bindable]
  14. public var nickName:String = '';
  15. //初始化,监听SOCKET事件
  16. private function init():void {
  17. //监听socket事件
  18. oSocket.addEventListener(Event.CLOSE,fooClosed);
  19. oSocket.addEventListener(Event.CONNECT,fooConnected);
  20. oSocket.addEventListener(IOErrorEvent.IO_ERROR,fooError);
  21. oSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,fooSecurity);
  22. oSocket.addEventListener(ProgressEvent.SOCKET_DATA,fooGetData);
  23. }
  24. //连接关闭事件响应
  25. public function fooClosed(e:Event):void{
  26. Alert.show('连接已断开!','Disconnected');
  27. game.setVisible(false);
  28. login.setVisible(true);
  29. }
  30. //登陆状态事件响应
  31. public function fooConnected(e:Event):void{
  32. text_c.setVisible(false);
  33. btn_connect.enabled = true;
  34. login.setVisible(false);
  35. game.setVisible(true);
  36. }
  37. //SOCKET错误事件响应
  38. public function fooError(e:IOErrorEvent):void{
  39. Alert.show('IO错误:'+e.text,'Socket connect Error');
  40. text_c.text = 'Socket connect Error!';
  41. btn_connect.enabled = true;
  42. }
  43. //安全沙箱事件响应
  44. public function fooSecurity(e:SecurityErrorEvent):void{
  45. Alert.show('安全错误:'+e.text,'Security Error');
  46. text_c.text = 'Security Error!';
  47. btn_connect.enabled = true;
  48. }
  49. //从服务端获取返回信息并根据不同的协议号进行不同的处理
  50. public function fooGetData(erogressEvent):void{
  51. var aMsg:Array = [];
  52. while(oSocket.bytesAvailable){
  53. aMsg.push(oSocket.readMultiByte(oSocket.bytesAvailable,'utf-8'));
  54. }
  55. var sMsg:String = aMsg.join('').replace(/\r/g,'');
  56. if(sMsg.indexOf(':::')!=-1){
  57. var Arr:Array;
  58. var Arr1:String ;
  59. var Arr2:Array ;
  60. var play:Array ;
  61. var i:int;
  62. Arr = sMsg.split(':::');
  63. fooShowMsg(Arr[0]);
  64. Arr1 = Arr[1]
  65. Arr2 = Arr1.split('***');
  66. for(i=0;i
  67. play = Arr2.split('---');
  68. //检查玩家是否已存在
  69. var tempObj:Object = game.getChildByName(play[0]);
  70. if(tempObj == null){
  71. //画玩家容器
  72. var people:Canvas = new Canvas();
  73. people.name = play[0];
  74. people.id = play[0];
  75. people.x = play[1];
  76. people.y = play[2];
  77. people.width = 80;
  78. people.height = 100;
  79. game.addChild(people);
  80. //画玩家名字
  81. var playerNameabel = new Label();
  82. playerName.text = play[0];
  83. playerName.x = 15;
  84. playerName.y = 5;
  85. people.addChild(playerName);
  86. //画玩家图片
  87. var player:Image = new Image();
  88. player.name = 'img'+play[0];
  89. player.id= 'img'+play[0];
  90. player.x = 10;
  91. player.y = 20;
  92. player.width = 64;
  93. player.height = 64;
  94. player.source = '../images/'+play[3]+'.png';
  95. people.addChild(player);
  96. //如果是自己,标注坐标
  97. if(play[0]==nickName){
  98. pos.text = '当前坐标:('+play[1]+','+play[2]+')';
  99. }
  100. }
  101. }
  102. }else if(sMsg.indexOf('pos')!=-1){
  103. //玩家移动
  104. var arr:Array;
  105. var arr2:Array;
  106. arr = sMsg.split(':');
  107. arr2 = arr[1].split('---');
  108. if(arr2[0]==nickName){
  109. //自己不用处理
  110. }else{
  111. //移动
  112. var thePlayer:Object = game.getChildByName(arr2[0]);
  113. moveTo(thePlayer,arr2[1],arr2[2])
  114. }
  115. }else{
  116. fooShowMsg(sMsg);
  117. }
  118. }
  119. //显示聊天信息
  120. public function fooShowMsg(sMsg:String):void{
  121. var sTemp:String = msg.text;
  122. msg.text = sTemp+sMsg;
  123. //聊天框自动滚动到最下面
  124. msg.verticalScrollPosition = msg.maxVerticalScrollPosition;
  125. }
  126. //发送信息到服务端
  127. public function fooCommand(sMsg:String):void{
  128. var bMsg:ByteArray = new ByteArray();
  129. if(sMsg.length>0){
  130. bMsg.writeUTFBytes(sMsg+'');
  131. oSocket.writeBytes(bMsg);
  132. oSocket.flush();
  133. }
  134. }
  135. //发送聊天
  136. public function sendChat(msg:String):void{
  137. var tempMsg:String = '['+nickName+']: '+msg;
  138. fooCommand(tempMsg);
  139. input.text='';
  140. }
  141. //登陆连接游戏
  142. public function fooConnect():void{
  143. var sIP:String = ip_text.text;
  144. var sPort:Number = Number(port_text.text);
  145. var sUser:String = user_text.text;
  146. var sCode:String = code_text.text;
  147. var sPlayer:String = user_name.text;
  148. if(!(sIP&&sPort)){
  149. Alert.show('服务器地址和端口号必填!','Warning:');
  150. }else{
  151. text_c.text = 'Connecting......';
  152. text_c.setVisible(true);
  153. btn_connect.enabled = false;
  154. oSocket.connect(sIP,sPort);
  155. if(sUser) fooCommand('user '+sUser);
  156. if(sCode) fooCommand('pass '+sCode);
  157. if(sPlayer) fooCommand('player:'+sPlayer);
  158. nickName = user_name.text;
  159. }
  160. }
  161. //断开链接,退出游戏
  162. public function fooDisConnect():void{
  163. oSocket.close();
  164. game.setVisible(false);
  165. login.setVisible(true);
  166. }
  167. //玩家移动自己
  168. private function movePlayer():void {
  169. var x:int = mou***-64;
  170. var y:int = mouseY-90;
  171. if(y<43){
  172. y = 43;
  173. }
  174. if(y>255 && x<195){
  175. return;
  176. }
  177. //发送最新坐标给服务端
  178. fooCommand('pos:'+nickName+'---'+x+'---'+y);
  179. pos.text = '当前坐标:('+x+','+y+')';
  180. var mySelf:Object = game.getChildByName(nickName);
  181. moveTo(mySelf,x,y);
  182. }
  183. //移动玩家
  184. private function moveTo(obj:Object,x:int,y:int):void{
  185. var move:Move = new Move(obj);
  186. move.duration = 1000;
  187. move.xTo = x;
  188. move.yTo = y;
  189. move.play();
  190. }
  191. ]]>



阅读(1837) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~