示例#1
0
	def run(self):
		print 'ai thread called ##################################################'
		# 玩家输入名称
		aiInfo = 'Player'

		conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

		try:
			conn.connect((sio.HOST,sio.AI_PORT))
		except:
			print 'failed to connect, the program will exit...'
			time.sleep(2)
			exit(1)

		mapInfo = sio._recvs(conn)
		
		#此处向玩家展示地图
		
		sio._sends(conn,(aiInfo,self.GetHeroType(mapInfo)))

		while True:
			rBeginInfo = sio._recvs(conn)
			print 'rbInfo got'
			if rBeginInfo != '|':
				sio._sends(conn,self.AI(rBeginInfo))
				print 'cmd sent'
			else:
				break
		conn.close()
    def run(self):
        sio._sends(self.conn, (sio.PLAYER_VS_AI, self.gameMapPath, self.gameAIPath))
        print "1"
        (mapInfo, aiInfo, baseInfo) = sio._recvs(self.conn)  # add base info
        print "5"
        frInfo = sio._recvs(self.conn)
        print "6"
        self.emit(SIGNAL("firstRecv"), mapInfo, frInfo, aiInfo, baseInfo)

        rCommand, reInfo = sio._recvs(self.conn)
        self.emit(SIGNAL("reRecv"), rCommand, reInfo)
        while reInfo.over == -1 and not self.isStopped():
            rbInfo = sio._recvs(self.conn)
            if self.isStopped():
                break
            self.emit(SIGNAL("rbRecv"), rbInfo)
            readFlag = 0
            while not readFlag:
                ready = select.select([self.conn], [], [], WAIT_TIME)
                if ready[0]:
                    rCommand, reInfo = sio._recvs(self.conn)
                    readFlag = 1

                if self.isStopped():
                    print "break by stop"
                    break
            if self.isStopped():
                break

            self.emit(SIGNAL("reRecv"), rCommand, reInfo)
        if not self.isStopped():
            winner = sio._recvs(self.conn)
            self.emit(SIGNAL("gameWinner"), winner)
        self.conn.close()
示例#3
0
	def run(self):
		mapInfo,base = sio._recvs(self.conn)
	#	mapInfo = mapReverse(mapInfo)#debugging
		self.emit(SIGNAL("mapRecv"), mapInfo, base)
		result = self.GetHeroType(mapInfo)
		sio._sends(self.conn, (result[0],result[1][0]))
		#time.sleep(5)
		while True and not self.isStopped():
			try:
				rBeginInfo = sio._recvs(self.conn)
				print 'rbInfo recv in UI_PLAYER!!!!!!!'
				#time.sleep(4)
			except sio.ConnException:
				#self.quit()
				self.stop()
				pass
				#raise sio.ConnException
			if self.isStopped():
				break
			self.AI(rBeginInfo)
			if rBeginInfo != '|':
			#	try:	
				sio._sends(self.conn,self.command)
				self.cmdNum += 1
		#		except sio.ConnException:
		#			self.stop()
		#			pass
			else:
				break
		self.conn.close()
    def run(self):
        mapInfo = sio._recvs(self.conn)
        print "2"
        self.emit(SIGNAL("mapRecv"), mapInfo)
        print "3"
        sio._sends(self.conn, self.GetHeroType(mapInfo))
        print "4"

        while True and not self.isStopped():
            readFlag2 = 0
            while not readFlag2:
                ready2 = select.select([self.conn], [], [], WAIT_TIME)
                if ready2[0]:
                    rBeginInfo = sio._recvs(self.conn)
                    readFlag2 = 1
                if self.isStopped():
                    break
            print "rbInfo got"
            if rBeginInfo != "|":
                sio._sends(self.conn, self.AI(rBeginInfo))
                print "cmd sent"
                self.cmdNum += 1
            else:
                break
        self.conn.close()
示例#5
0
	def initialize(self, gameAIPath, gameMapPath):
		if not sio.DEBUG_MODE:
			self.serverProg = sio.Prog_Run(os.getcwd() + sio.SERV_FILE_NAME)
		self.conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		try:
			self.conn.connect((sio.HOST,sio.UI_PORT))
		except:
			self.conn.close()
			raise ConnectionError()
		else:
			sio._sends(self.conn,(sio.PLAYER_VS_AI, unicode(gameMapPath),(unicode(gameAIPath),None),[DEBUG_MODE, False]))
示例#6
0
 def initialize(self, gameAIPath, gameMapPath):
     self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     try:
         self.conn.connect((sio.HOST, sio.UI_PORT))
     except:
         print 'failed to connect, the program will exit...'
         time.sleep(2)
         exit(1)
     sio._sends(self.conn, (sio.AI_VS_AI, gameMapPath, gameAIPath))
     mapInfo, aiInfo = sio._recvs(conn)
     frInfo = sio._recvs(self.conn)
     #在ai_vs_ai模式里,平台并没有给用户设置自己士兵类型和英雄类型的函数,用默认的吗?
     self.emit(SIGNAL("firstRecv"), mapInfo, frInfo, aiInfo)
示例#7
0
 def initialize(self, gameAIPath, gameMapPath):
     self.conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
     try:
         self.conn.connect((sio.HOST,sio.UI_PORT))
     except:
         print 'failed to connect, the program will exit...'
         time.sleep(2)
         exit(1)
     sio._sends(self.conn,(sio.AI_VS_AI, gameMapPath,gameAIPath))
     mapInfo,aiInfo = sio._recvs(conn)
     frInfo = sio._recvs(self.conn)
      #在ai_vs_ai模式里,平台并没有给用户设置自己士兵类型和英雄类型的函数,用默认的吗?
     self.emit(SIGNAL("firstRecv"),mapInfo, frInfo, aiInfo)
示例#8
0
	def run(self):
		temp = sio._recvs(self.conn)
		self.emit(SIGNAL("tmpRecv()"))

		mapInfo,baseInfo,aiInfo = sio._recvs(self.conn)
		frInfo = sio._recvs(self.conn)

		self.emit(SIGNAL("firstRecv"),mapInfo, frInfo, aiInfo, baseInfo)
		try:
			rCommand, reInfo = sio._recvs(self.conn)
		except sio.ConnException:
			self.stop()
			pass
		self.emit(SIGNAL("reRecv"), rCommand, reInfo)
		while not reInfo.over and not self.isStopped():
			try:
				rbInfo = sio._recvs(self.conn)
			except sio.ConnException:
				#self.quit()
				self.stop()
				pass
				#raise sio.ConnException
			if self.isStopped():
				break
			self.emit(SIGNAL("rbRecv"),rbInfo)
			try:
				rCommand,reInfo = sio._recvs(self.conn)
			except sio.ConnException:
				#self.quit()
				self.stop()
				pass
				#raise sio.ConnException
			
			if self.isStopped():
				break

			self.emit(SIGNAL("reRecv"),rCommand, reInfo)
		if not self.isStopped():
			winner = sio._recvs(self.conn)
			self.emit(SIGNAL("gameWinner"),winner)
	#	是否存储回放文件
		if not self.isStopped():
			global WaitForReplay

			self.mutex.lock()
			WaitForReplay.wait(self.mutex)

			sio._sends(self.conn, self.replay_mode)


		self.conn.close()
示例#9
0
	def run(self):
		#先用QProcess打开平台程序
		self.platProcess = sio.Prog_Run(os.getcwd() + sio.SERV_FILE_NAME)
		
		self.conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		try:
			self.conn.connect((sio.HOST,sio.UI_PORT))
		except:
			self.emit(SIGNAL("connectError()"))
		else:
			sio._sends(self.conn,(sio.AI_VS_AI, self.map ,[self.ai1, self.ai2], DEBUG_MODE))

			mapInfo,baseInfo,aiInfo = sio._recvs(self.conn)
			try:
				rbInfo = sio._recvs(self.conn)
				self.emit(SIGNAL("firstRecv"), mapInfo, rbInfo, aiInfo, baseInfo)
			except:
				self.stop()
			try:
				rCommand,reInfo = sio._recvs(self.conn)
				self.emit(SIGNAL("reRecv"), rCommand, reInfo)
			except:
				self.stop()
			self.emit(SIGNAL("round()"))

			while not reInfo.over and not self.isStopped():
				try:
					rbInfo = sio._recvs(self.conn)
					self.emit(SIGNAL("rbRecv"), rbInfo)
				except:
					self.stop()
				try:
					rCommand,reInfo = sio._recvs(self.conn)
					self.emit(SIGNAL("reRecv"), rCommand, reInfo)
				except:
					self.stop()
					pass
				self.emit(SIGNAL("round()"))
			if not self.isStopped():
				global Score
				Score = reInfo.score
				winner = sio._recvs(self.conn)
				self.emit(SIGNAL("gameEnd"),winner)
			if not self.isStopped():
				sio._sends(self.conn, True)
				self.sleep(2)
		finally:
			self.platProcess.kill()
			self.conn.close()
示例#10
0
def ConnectWithLogic(lv, aiPath):
	global sock
	global testScore
	global gameAiPath
	for i in range(10):
		print 'stage %d: ' % (i), testScore[i]
			


	# select stage
	# stage = raw_input('stage(enter 0 to quit): ')###########################界面组修改#########################
	# if stage == '0':
	#	exit()

	# choose ai file path here ###########################界面组修改#########################
	gameAIPath = aiPath

	# run game here
	serverProg = sio.Prog_Run(os.getcwd() + sio.SERV_FILE_NAME)
	conn = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	try:
		time.sleep(0.2)
		conn.connect((sio.HOST,sio.UI_PORT))
	except:
		conn.close()
		print 'fail to connect with platform'
		raise ConnectionError()

	sio._sends(conn, (sio.TEST_BATTLE, lv,(None,unicode(gameAIPath)),[0,0]))
	sio._sends(conn, lv)

	# receive score
	#score = raw_input('score: ')
			
	score = sio._recvs(conn)
	winner = sio._recvs(conn)
	
	if winner == 0:
		score = 0
		print 'You lose'

	newScore = [str(lv),str(score)]
	newScore = ' '.join(newScore)

	#sock.sendall(newScore)
	return winner, score
示例#11
0
	def run(self):
		global gp
		
		#与UI连接
		connUI,address = _SocketConnect(sio.HOST,sio.UI_PORT,'UI')
		connUI.settimeout(1)
		
		#接收游戏模式、地图和AI信息
		gp.gameMode, gp.gameMapPath, gp.gameAIPath, gp.AI_Debug=sio._recvs(connUI)
		
		#设置AI超时开关
		for i in range(2):
			if gp.gameAIPath[i] == None or gp.AI_Debug[i]:
				gp.timeoutSwitch[i] = 0
			else:
				gp.timeoutSwitch[i] = 1
		
		if gp.gameMode <= sio.PLAYER_VS_PLAYER:
			if not sio.DEBUG_MODE:
				sio.Prog_Run(os.getcwd() + sio.LOGIC_FILE_NAME)
				time.sleep(0.1)
			logic_thread.start()
			
		#读取地图
		(gp.mapInfo,gp.base)=sio._ReadFile(gp.gameMapPath)
		gp.base[0].sort()
		gp.base[1].sort()
		
		#运行AI线程及文件
		AIProg = []
		
		for i in range(2):
			while gp.gProc.acquire():
				if gp.gProcess != sio.LOGIC_CONNECTED + i:
					gp.gProc.wait()
				else:
					#运行AI连接线程
					if not ai_thread.isAlive():
						ai_thread.start()
					#运行AI1
					AIProg.append(self.run_AI(connUI,gp.gameAIPath[i],i))
					gp.gProc.release()
					break
				gp.gProc.release()

		#所有连接建立后,将游戏进度前调
		while gp.gProc.acquire():
			if gp.gProcess != sio.CONNECTED:
				gp.gProc.wait()
			else:
				gp.gProcess = sio.MAP_SET
				gp.gProc.notifyAll()
				gp.gProc.release()
				break
			gp.gProc.release()

		#AI返回gp.heroType后将其传回界面
		while gp.gProc.acquire():
			if gp.gProcess != sio.HERO_TYPE_SET:
				gp.gProc.wait()
			else:
				try:
					
					sio._sends(connUI,(gp.mapInfo,gp.base,gp.aiInfo))
				except:
					connUI.shutdown(socket.SHUT_RDWR)
					sys.exit(1)
				gp.replayInfo.append((gp.mapInfo,gp.base,gp.aiInfo))
				gp.gProcess = sio.ROUND
				gp.gProc.notifyAll()
				gp.gProc.release()
				break
			gp.gProc.release()
		
		#初始化完毕,进入回合==============================================================
		#print 'ui in game'#for test
		gp.uiOverFlag = False
		#等待回合初始信息产生完毕
		while gp.gProcess < sio.OVER:
			while gp.rProc.acquire():
				if gp.rProcess != sio.RBINFO_SET:
					gp.rProc.wait()
				else:
					#发送回合信息
					try:
						sio._sends(connUI,gp.rbInfo)
					except:
						connUI.shutdown(socket.SHUT_RDWR)
						sys.exit(1)
					gp.rProcess = sio.RBINFO_SENT_TO_UI
					gp.rProc.notifyAll()
					gp.rProc.release()
					break
				gp.rProc.release()
			
			#等待回合所有信息产生完毕
			while gp.rProc.acquire():
				if gp.rProcess != sio.REINFO_SET:
					gp.rProc.wait()
				else:
					gp.reInfo.timeused = (gp.cmdEnd - gp.cmdBegin) * 1000
					
					#发送回合信息
					try:	
						sio._sends(connUI,(gp.rCommand,gp.reInfo))
					except:
						connUI.shutdown(socket.SHUT_RDWR)
						sys.exit(1)
					#回合信息存至回放列表中
					gp.replayInfo.append([gp.rbInfo,gp.rCommand,gp.reInfo])
					gp.rProcess = sio.START
					gp.rProc.notifyAll()
					#若游戏结束则跳出循环
					if gp.reInfo.over:
						gp.uiOverFlag = True
					gp.rProc.release()
					break
				gp.rProc.release()
			if gp.uiOverFlag:
				break
		
		#向UI发送胜利方
		while gp.gProc.acquire():
			if gp.gProcess != sio.WINNER_SET:
				gp.gProc.wait()
			else:
				try:
					sio._sends(connUI,gp.winner)
				except:
					connUI.shutdown(socket.SHUT_RDWR)
					sys.exit(1)
				connUI.settimeout(None)
				replay_mode = sio._recvs(connUI)
				gp.gProc.notifyAll()
				gp.gProc.release()
				break
			gp.gProc.release()
		
		#存回放文件
		if replay_mode == True:	
			#检验回放文件目录
			try:
				os.mkdir(os.getcwd() + sio.REPLAY_FILE_PATH)
			except:
				pass
			#写入回放
			sio._WriteFile(gp.replayInfo,os.getcwd() + sio.REPLAY_FILE_PATH + sio._ReplayFileName(gp.aiInfo))
			
		connUI.shutdown(socket.SHUT_RDWR)
示例#12
0
	def run(self):
		global gp
		try:
			connLogic,address = _SocketConnect(sio.HOST,sio.LOGIC_PORT,'Logic')
			print 'Logic connected'
		except:
			print 'logic connection failed, the program will exit...'
			time.sleep(2)
			sys.exit(1)
			
		sio._sends(connLogic,gp.timeoutSwitch)
		
		#发送游戏初始信息
		while gp.gProc.acquire():
			if gp.gProcess < sio.HERO_TYPE_SET:
				gp.gProc.wait()
			else:
				sio._sends(connLogic,basic.Begin_Info(gp.mapInfo,gp.base,gp.heroType))
				gp.gProc.release()
				break
			gp.gProc.release()	
		
		#等待其他线程初始化完毕
		while gp.gProc.acquire():
			if gp.gProcess != sio.ROUND:
				gp.gProc.wait()
			else:
				gp.gProc.release()
				break
			gp.gProc.release()
		
		#初始化完毕,进入回合==============================================================	
		#print 'logic in game'#for test
		
		while gp.gProcess != sio.OVER:
			#接收回合开始信息
			if gp.gameMode != sio.AI_VS_AI:
				time.sleep(1) #time delay
			while gp.rProc.acquire():
				if gp.rProcess != sio.START:
					gp.rProc.wait()
				else:
					gp.rbInfo = sio._recvs(connLogic)
					
					gp.rProcess = sio.RBINFO_SET
					gp.rProc.notifyAll()
					gp.rProc.release()
					break
				gp.rProc.release()
				
			#将命令发送至AI
			while gp.rProc.acquire():
				#print 'logic acquired',gp.rProcess
				if gp.rProcess != sio.RCOMMAND_SET:
					gp.rProc.wait()
				else:	
					sio._sends(connLogic,gp.rCommand)
					gp.reInfo = sio._recvs(connLogic)
					if gp.aiConnErr[gp.rbInfo.id[0]]:
						gp.reInfo.over = sio.AI_BREAKDOWN
					gp.rProc.release()
					break
				gp.rProc.release()

			#判断游戏是否结束,并调整游戏进度标记
			if gp.reInfo.over != sio.CONTINUE:
				gp.gProc.acquire()
				gp.gProcess = sio.OVER
				gp.gProc.notifyAll()
				gp.gProc.release()

			#调整回合进度标记
			while gp.rProc.acquire():
				gp.rProcess = sio.REINFO_SET
				gp.rProc.notifyAll()
				gp.rProc.release()
				break	
		
		if gp.reInfo.over == sio.NORMAL_OVER:
			gp.winner = sio._recvs(connLogic)
		if gp.reInfo.over == sio.AI_BREAKDOWN:
			for i in range(2):
				if gp.aiConnErr[i] == True:
					gp.winner = i
		
		#接收胜利方信息
		gp.gProc.acquire()
		gp.gProcess = sio.WINNER_SET
		gp.gProc.notifyAll()
		gp.gProc.release()
		
		connLogic.shutdown(socket.SHUT_RDWR)
示例#13
0
	def run(self):
		global gp
		
		#与AI进行socket连接
		[(connAI1,address1),(connAI2,address2)] = _SocketConnect(sio.HOST,sio.AI_PORT,'AI',2)
		connAI=[connAI1,connAI2]
		
		#设置命令限时
		for i in range(2):
			if gp.timeoutSwitch[i]==1:
				connAI[i].settimeout(sio.AI_CMD_TIMEOUT)
			else:
				connAI[i].settimeout(None)

		#向AI传输游戏初始信息并接收AI的反馈
		while gp.gProc.acquire():
			if gp.gProcess != sio.MAP_SET:
				gp.gProc.wait()
			else:
				for i in range(2):
					try:
						if sio.USE_CPP_AI and (gp.gameAIPath[i] != None):
							sio._cpp_sends_begin(connAI[i],i,gp.mapInfo,(len(gp.base[0]),len(gp.base[1])),gp.base)
						else:
							sio._sends(connAI[i],(gp.mapInfo,gp.base))
					except sio.ConnException:
						gp.aiConnErr[i] = True
					try:
						if sio.USE_CPP_AI and (gp.gameAIPath[i] != None):
							gp.aiInfoTemp,gp.heroTypeTemp = sio._cpp_recvs_begin(connAI[i])
						else:
							gp.aiInfoTemp,gp.heroTypeTemp = sio._recvs(connAI[i])
						gp.aiInfo.append(gp.aiInfoTemp)
						gp.heroType.append(gp.heroTypeTemp)
					except socket.timeout:
						print 'fail to receive AI',i,'\'s information, default settings will be used...'
						gp.aiInfo.append('Player'+str(i))
						gp.heroType.append(6)
						
				#调节游戏进度标记
				gp.gProcess = sio.HERO_TYPE_SET
				#print 'gp.heroType set'#for test
				
				gp.gProc.notifyAll()
				gp.gProc.release()
				break
			gp.gProc.release()

		#初始化完毕,进入回合==============================================================
		print 'ai in game'#for test 
		
		#游戏回合阶段
		roundNum = 0
		while gp.gProcess < sio.OVER:
			roundNum =  roundNum + 1
			#将回合开始信息发送至AI,并接收AI的命令
			while gp.rProc.acquire():
				if gp.rProcess != sio.RBINFO_SENT_TO_UI:
					gp.rProc.wait()
				else:
					#清空接收区缓存(其中可能有因超时而没收到的上一回合的命令)
					connAI[gp.rbInfo.id[0]].settimeout(0)
				
					try:
						connAI[gp.rbInfo.id[0]].recv(1024)
					except:
						pass
						
					if gp.timeoutSwitch[gp.rbInfo.id[0]]==1:
						connAI[gp.rbInfo.id[0]].settimeout(sio.AI_CMD_TIMEOUT)
					else:
						connAI[gp.rbInfo.id[0]].settimeout(None)
						
					#计分,用于传输
					if roundNum <= 2:
						tempScore = [0,0]
					else:
						tempScore = gp.reInfo.score
					
					#发送回合信息
					try:
						if sio.USE_CPP_AI and gp.gameAIPath[gp.rbInfo.id[0]] != None:
							sio._cpp_sends(connAI[gp.rbInfo.id[0]],gp.rbInfo.id[1],len(gp.rbInfo.temple),gp.rbInfo.temple,(len(gp.base[0]),len(gp.base[1])),gp.base,roundNum,tempScore)
						else:
							sio._sends(connAI[gp.rbInfo.id[0]],gp.rbInfo)
						print 'Round BeginInfo sent to AI'
					except sio.ConnException:
						#AI连接错误,标记至connErr中
						gp.aiConnErr[gp.rbInfo.id[0]] = True
					except:
						gp.aiConnErr[gp.rbInfo.id[0]] = True
						
					if gp.aiConnErr[gp.rbInfo.id[0]] == True:
						gp.rCommand = basic.Command()
					else:
						try:
							print 'prepare to receive cmd'
							gp.cmdBegin = time.clock()
							if sio.USE_CPP_AI and gp.gameAIPath[gp.rbInfo.id[0]] != None:
								gp.rCommand = sio._cpp_recvs(connAI[gp.rbInfo.id[0]])
								if gp.rCommand.order == 1:
									gp.rCommand.target = [1-gp.rbInfo.id[0],gp.rCommand.target]
								else:
									gp.rCommand.target = [gp.rbInfo.id[0],gp.rCommand.target]
							else:
								gp.rCommand = sio._recvs(connAI[gp.rbInfo.id[0]])
								print 'python cmd recv:::::::::'
								print gp.rCommand.target
							gp.cmdEnd = time.clock()
							#print 'AI',gp.rbInfo.id[0],'\'s command:'
							#sio.cmdDisplay(gp.rCommand)
						except socket.timeout:
							print 'fail to receive cmd, default will be used..'
							gp.rCommand = basic.Command()
						except sio.ConnException:
							print 'in gp.aiConnErr!!!!!!!!!!!!'
							gp.aiConnErr[gp.rbInfo.id[0]] = True
							gp.rCommand = basic.Command()

					gp.rProcess = sio.RCOMMAND_SET
					gp.rProc.notifyAll()
					gp.rProc.release()
					break
				gp.rProc.release()
			
			#调整回合进度标记
			while gp.rProc.acquire():
				if gp.rProcess == sio.RCOMMAND_SET:
					gp.rProc.wait()
				else:
					gp.rProc.release()
					break
				gp.rProc.release()
			
		#向AI发送结束标志
		if gp.reInfo.over == sio.NORMAL_OVER:
			for i in range(2):
				connAI[i].send('|')
				connAI[i].shutdown(socket.SHUT_RDWR)
示例#14
0
	def run(self):
		global gProcess,rProcess,mapInfo,heroType,aiInfo,rbInfo,reInfo,rCommand
		
		#与AI进行socket连接
		[(connAI1,address1),(connAI2,address2)] = _SocketConnect(sio.HOST,sio.AI_PORT,'AI',2)
		connAI=[connAI1,connAI2]
		
		#设置回合
		for i in connAI:
			i.settimeout(sio.AI_CMD_TIMEOUT)
		
		#向AI传输地图信息并接收AI的反馈
		while gProc.acquire():
			if gProcess != sio.MAP_SET:
				gProc.wait()
			else:
				for i in range(2):
					try:
						sio._sends(connAI[i],mapInfo)
						aiInfoTemp,heroTypeTemp = sio._recvs(connAI[i])
						aiInfo.append(aiInfoTemp)
						heroType.append(heroTypeTemp)
					except socket.timeout:
						print '未收到AI',i+1,'的信息,将采用默认值'
						aiInfo.append('Player'+str(i+1))
						heroType.append(6)
				
				#调节游戏进度标记
				gProcess = sio.HERO_TYPE_SET
				gProc.notifyAll()
				gProc.release()
				break
			gProc.release()

		#初始化完毕,进入回合==============================================================
		
		#游戏回合阶段
		while gProcess < sio.OVER:

			#将回合开始信息发送至AI,并接收AI的命令
			while rProc.acquire():
				if rProcess != sio.RBINFO_SET:
					rProc.wait()
				else:
					sio._sends(connAI[rbInfo.id[0]],rbInfo)
					try:
						rCommand = sio._recvs(connAI[rbInfo.id[0]])
					except socket.timeout:
						rCommand = basic.Command()
					rProcess = sio.RCOMMAND_SET
					rProc.notifyAll()
					rProc.release()
					break
				rProc.release()
			
			#调整回合进度标记
			while rProc.acquire():
				if rProcess == sio.RCOMMAND_SET:
					rProc.wait()
				else:
					rProc.release()
					break
				rProc.release()
		
		#向AI发送结束标志
		for i in range(2):
			connAI[i].send('|')
			connAI[i].close()
示例#15
0
	def run(self):
		global gProcess,rProcess,mapInfo,heroType,aiInfo,rbInfo,reInfo,rCommand,ai_thread
		
		#定义回放列表用于生成回放文件,每个元素储存一个回合的信息
		replayInfo=[]
		
		#与UI连接
		connUI,address = _SocketConnect(sio.HOST,sio.UI_PORT,'UI')
		
		#发送游戏模式、地图和AI信息
		gameMode,gameMapPath,gameAIPath=sio._recvs(connUI)
		
		#读取地图文件
		mapInfo=sio._ReadFile(gameMapPath)
			
		#运行AI线程及文件
		while gProc.acquire():
			if gProcess != sio.U_L_CONNECTED:
				gProc.wait()
			else:
				#运行AI连接线程
				ai_thread.start()
				#运行AI1
				os.system('cmd /c start %s' %(gameAIPath[0]))
				gProc.release()
				break
			gProc.release()
		
		while gProc.acquire():
			if gProcess != sio.ONE_AI_CONNECTED:
				gProc.wait()
			else:
				#运行AI2
				os.system('cmd /c start %s' %(gameAIPath[1]))
				gProc.release()
				break
			gProc.release()
		
		#所有连接建立后,将游戏进度前调
		while gProc.acquire():
			if gProcess != sio.CONNECTED:
				gProc.wait()
			else:
				gProcess = sio.MAP_SET
				gProc.notifyAll()
				gProc.release()
				break
			gProc.release()
		
		#AI返回heroType后将其传回界面
		while gProc.acquire():
			if gProcess != sio.HERO_TYPE_SET:
				gProc.wait()
			else:
				sio._sends(connUI,(mapInfo,aiInfo))
				gProcess = sio.ROUND
				gProc.notifyAll()
				gProc.release()
				break
			gProc.release()
		
		#初始化完毕,进入回合==============================================================
		flag = False
		#等待回合初始信息产生完毕
		while gProcess < sio.OVER:
			while rProc.acquire():
				if rProcess == sio.START:
					rProc.wait()
				else:
					#发送回合信息
					sio._sends(connUI,rbInfo)
					rProc.release()
					break
				rProc.release()
			
			#等待回合所有信息产生完毕
			while rProc.acquire():
				if rProcess != sio.REINFO_SET:
					rProc.wait()
				else:
					#发送回合信息
					sio._sends(connUI,(rCommand,reInfo))
					#回合信息存至回放列表中
					replayInfo.append([rbInfo,rCommand,reInfo])
					rProcess = sio.START
					rProc.notifyAll()
					#若游戏结束则跳出循环
					if reInfo.over != -1:###################################在这里改跳出二层循环!!
						flag = True
					rProc.release()
					break
				rProc.release()
			if flag:
				break
		
		#向UI发送胜利方
		while gProc.acquire():
			if gProcess != sio.WINNER_SET:
				gProc.wait()
			else:
				sio._sends(connUI,winner)
				gProc.notifyAll()
				gProc.release()
				break
			gProc.release()
		
		#存回放文件
		if sio.REPLAY_MODE:	
			#检验回放文件目录
			try:
				os.mkdir(os.getcwd() + '\\ReplayFiles')
			except:
				pass
			#写入回放
			sio._WriteFile(replayInfo,os.getcwd() + '\\ReplayFiles\\' + sio._ReplayFileName(aiInfo))
			
		connUI.close()
示例#16
0
                distance = basic.COORDINATE_X_MAX * 2
                for i in move:
                        for j in range(0,len(Info.base[1-team])):
                                target = Info.base[1-team][j]
                                if main.distance(i,target.position) < distance:
                                        distance = main.distance(i,target.position)
                                        position = i
        result = basic.Command(0,position,(0,0))
    else:
        if order == 1:
            team = 1 - team
        result = basic.Command(order,find_position(whole_map, Info.base,Info.id,(team,target_id), distance, move),(team, target_id))
    return result
	

'''
aiInfo = 'TestBattle_AI'
conn=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    conn.connect((sio.HOST,sio.AI_PORT))
    print 'connected!'
except:
    print 'failed to connect, the program will exit...'
    time.sleep(2)
    exit(1)
mapInfo,base=sio._recvs(conn)
sio._sends(conn,(aiInfo,GetHeroType(mapInfo,base)))
print 'info sent'
while True:
    rBeginInfo=sio._recvs(conn)
    print 'rbInfo got'
示例#17
0
	def run(self):
		global gProcess,rProcess,mapInfo,heroType,aiInfo,rbInfo,reInfo,rCommand,winner

		connLogic,address = _SocketConnect(sio.HOST,sio.LOGIC_PORT,'Logic')
		
		#发送游戏初始信息
		while gProc.acquire():
			if gProcess < sio.HERO_TYPE_SET:
				gProc.wait()
			else:
				base = sio.construct_base(mapInfo,heroType)###########################
				sio._sends(connLogic,basic.Begin_Info(mapInfo,base,heroType))
				gProc.release()
				break
			gProc.release()	
		
		#等待其他线程初始化完毕
		while gProc.acquire():
			if gProcess != sio.ROUND:
				gProc.wait()
			else:
				gProc.release()
				break
			gProc.release()
		
		#初始化完毕,进入回合==============================================================	
		
		while gProcess != sio.OVER:
			
			#接收回合开始信息
			while rProc.acquire():
				if rProcess != sio.START:
					rProc.wait()
				else:
					rbInfo = sio._recvs(connLogic)
					rProcess = sio.RBINFO_SET
					rProc.notifyAll()
					rProc.release()
					break
				rProc.release()
				
			#将命令发送至AI
			while rProc.acquire():
				#print 'logic acquired',rProcess
				if rProcess != sio.RCOMMAND_SET:
					rProc.wait()
				else:
					sio._sends(connLogic,rCommand)
					reInfo = sio._recvs(connLogic)
					rProc.release()
					break
				rProc.release()
			
			#判断游戏是否结束,并调整游戏进度标记
			if reInfo.over != -1:
				gProc.acquire()
				gProcess = sio.OVER
				gProc.notifyAll()
				gProc.release()

			#调整回合进度标记
			while rProc.acquire():
				rProcess = sio.REINFO_SET
				rProc.notifyAll()
				rProc.release()
				break	
		winner = sio._recvs(connLogic)
		
		#接收胜利方信息
		gProc.acquire()
		gProcess = sio.WINNER_SET
		gProc.notifyAll()
		gProc.release()
		
		connLogic.close()
示例#18
0
                                                position = i
                result = basic.Command(0,position,(0,0))
	else:
                if order == 1:
                        team = 1 - team
		result = basic.Command(order,find_position(whole_map, Info.base,Info.id,(team,target_id), distance, move),(team, target_id))
	return result

aiInfo = 'Sample_AI'
conn=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
	conn.connect((sio.HOST,sio.AI_PORT))
	print 'connected!'
except:
	print 'failed to connect, the program will exit...'
	time.sleep(2)
	exit(1)
mapInfo,base=sio._recvs(conn)
sio._sends(conn,(aiInfo,GetHeroType(mapInfo,base)))
print 'info sent'
while True:
	rBeginInfo=sio._recvs(conn)
	print 'rbInfo got'
	if rBeginInfo != '|':
		sio._sends(conn,AI(mapInfo,rBeginInfo))
		print 'cmd sent\n\n'
	else:
		break

conn.close()
print ('ai end')
示例#19
0
conn=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
	conn.connect((sio.HOST,sio.UI_PORT))
except:
	print 'failed to connect, the program will exit...'
	time.sleep(2)
	exit(1)
	
gameMode='ai_vs_ai'
gameMapPath='C:\\Users\\woinck\\Documents\\GitHub\\platform\\SampleMap.Map'
gameAIPath=[]

gameAIPath.append('C:\\Users\\woinck\\Documents\\GitHub\\platform\\sclientai.py')
gameAIPath.append('C:\\Users\\woinck\\Documents\\GitHub\\platform\\sclientai.py')

sio._sends(conn,(gameMode,gameMapPath,gameAIPath))

#接收AI与地图信息
mapInfo,aiInfo=sio._recvs(conn)
print 'map recv'
#接收每回合信息
rbInfo=sio._recvs(conn)
rCommand,reInfo=sio._recvs(conn)
while reInfo.over == -1:
	print 'rInfo recv'
	print 'over=',reInfo.over
	#展示
	rbInfo=sio._recvs(conn)
	rCommand,reInfo=sio._recvs(conn)
winner=sio._recvs(conn)
print 'Player ',winner,' win!'
示例#20
0
	def run(self):
		global gp
		
		#与UI连接
		connUI,address = _SocketConnect(sio.HOST,sio.UI_PORT,'UI')
		connUI.settimeout(1)
		
		#接收游戏模式、地图和AI信息
		gp.gameMode, gp.gameMapPath, gp.gameAIPath, gp.AI_Debug = sio._recvs(connUI)

		if gp.gameMode == sio.TEST_BATTLE:
			gp.testBattleStage = sio._recvs(connUI)
			gp.TestBattleStageInit()
		elif gp.gameMode == sio.NET_GAME_CLIENT:
			gp.serverInfo = sio._recvs(connUI) #[IP,PORT]
			try:
				gp.netClient.connect(serverInfo)
			except:
				print 'Connecting to game host failed'


		#设置AI超时开关
		for i in range(2):
			if gp.gameAIPath[i] == None or gp.AI_Debug[i]:
				gp.timeoutSwitch[i] = 0
			else:
				gp.timeoutSwitch[i] = 1
		
		if gp.gameMode <= sio.NET_GAME_SERVER:
			if not sio.DEBUG_MODE:
				LogicProg = sio.Prog_Run(os.getcwd() + sio.LOGIC_FILE_NAME)
				time.sleep(0.1)
			logic_thread.start()

		#读取地图

		if gp.gameMode <= sio.PLAYER_VS_PLAYER or gp.gameMode == sio.NET_GAME_SERVER:
			(gp.mapInfo,gp.base) = sio._ReadFile(gp.gameMapPath)
		elif gp.gameMode == sio.TEST_BATTLE:
			fieldTest.get_map(TestBattle_Map.testBattleMap[gp.testBattleStage],gp.mapInfo,gp.base)

		gp.base[0].sort()
		gp.base[1].sort()
		'''
		try:
			for i in range(2):
				for soldier in gp.base[i]:
					soldier.life = 0
		'''
		

		#运行AI线程及文件
		AIProg = []
		
		for i in range(2):
			while gp.gProc.acquire():
				if gp.gProcess != sio.LOGIC_CONNECTED + i:
					gp.gProc.wait()
				else:
					#运行AI连接线程
					if not ai_thread.isAlive():
						ai_thread.start()
					#运行AI1
					print gp.gameAIPath[i]
					AIProg.append(self.run_AI(connUI,gp.gameAIPath[i],i))
					gp.gProc.release()
					break
				gp.gProc.release()

		#所有连接建立后,将游戏进度前调
		while gp.gProc.acquire():
			if gp.gProcess != sio.CONNECTED:
				gp.gProc.wait()
			else:
				gp.gProcess = sio.MAP_SET
				gp.gProc.notifyAll()
				gp.gProc.release()
				break
			gp.gProc.release()

		#AI返回gp.heroType后将其传回界面
		while gp.gProc.acquire():
			if gp.gProcess != sio.HERO_TYPE_SET:
				gp.gProc.wait()
			else:
				try:
					if gp.gameMode != sio.TEST_BATTLE:
						sio._sends(connUI,(gp.mapInfo,gp.base,gp.aiInfo))
				except:
					connUI.shutdown(socket.SHUT_RDWR)
					sys.exit(1)
				gp.replayInfo.append((gp.mapInfo,gp.base,gp.aiInfo))
				gp.displayInfo += sio._display_begin(gp.mapInfo, gp.base, gp.aiInfo)
				gp.gProcess = sio.ROUND
				gp.gProc.notifyAll()
				gp.gProc.release()
				break
			gp.gProc.release()
		

		
		#初始化完毕,进入回合==============================================================
		#print 'ui in game'#for test
		gp.uiOverFlag = False
		#等待回合初始信息产生完毕
		while gp.gProcess < sio.OVER:
			while gp.rProc.acquire():
				if gp.rProcess != sio.RBINFO_SET:
					gp.rProc.wait()
				else:
					#发送回合信息
					try:
						if gp.gameMode != sio.TEST_BATTLE:
							sio._sends(connUI,gp.rbInfo)
					except:
						connUI.shutdown(socket.SHUT_RDWR)
						sys.exit(1)
					gp.rProcess = sio.RBINFO_SENT_TO_UI
					gp.rProc.notifyAll()
					gp.rProc.release()
					break
				gp.rProc.release()
			
			#等待回合所有信息产生完毕
			while gp.rProc.acquire():
				if gp.rProcess != sio.REINFO_SET:
					gp.rProc.wait()
				else:
					gp.reInfo.timeused = (gp.cmdEnd - gp.cmdBegin) * 1000
					
					#发送回合信息
					try:
						if gp.gameMode != sio.TEST_BATTLE:
							sio._sends(connUI,(gp.rCommand,gp.reInfo))
					except:
						connUI.shutdown(socket.SHUT_RDWR)
						sys.exit(1)
					#回合信息存至回放列表中
					gp.replayInfo.append([gp.rbInfo,gp.rCommand,gp.reInfo])
					gp.displayInfo += sio._display_round(gp.rbInfo, gp.rCommand, gp.reInfo)
					gp.rProcess = sio.START
					gp.rProc.notifyAll()
					#若游戏结束则跳出循环
					if gp.reInfo.over:
						gp.uiOverFlag = True
					gp.rProc.release()
					break
				gp.rProc.release()
			if gp.uiOverFlag:
				break
		
		#向UI发送胜利方
		while gp.gProc.acquire():
			if gp.gProcess != sio.WINNER_SET:
				gp.gProc.wait()
			else:
				try:
					if gp.gameMode == sio.TEST_BATTLE:
						sio._sends(connUI,gp.reInfo.score[1])
					sio._sends(connUI,gp.winner)
				except:
					connUI.shutdown(socket.SHUT_RDWR)
					sys.exit(1)
				connUI.settimeout(None)

				if gp.gameMode == sio.TEST_BATTLE:
					replay_mode = False
				else:
					replay_mode = sio._recvs(connUI)

				gp.gProc.notifyAll()
				gp.gProc.release()
				break
			gp.gProc.release()
		
		#存回放文件
		if replay_mode == True:	
			#检验回放文件目录
			try:
				os.mkdir(os.getcwd() + sio.REPLAY_FILE_PATH)
			except:
				pass
			#写入回放
			sio._WriteFile(gp.replayInfo,os.getcwd() + sio.REPLAY_FILE_PATH + sio._ReplayFileName(gp.aiInfo))
			sio._WriteCppFile(gp.displayInfo, os.getcwd() + sio.DISPLAY_FILE_PATH + sio._ReplayFileName(gp.aiInfo,1))

		for i in AIProg:
			if i != None:
				i.kill()
		try:
			LogicProg.kill()
		except:
			pass


		connUI.shutdown(socket.SHUT_RDWR)
serv = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#try:
serv.bind((sio.HOST,sio.UI_PORT))
#except:
 #   print 'port occupied, the program will exit...'
  #  time.sleep(3)
  #  exit(1)

serv.listen(1)
connUI, address = serv.accept()
(gameMode,gameMapPath,gameAIPath)=sio._recvs(connUI)
print gameMode,gameMapPath,gameAIPath
aiInfo = []

sio._sends(connUI, (maps,units0,aiInfo))
#Round 1
sio._sends(connUI, begInfo0)
#time.sleep(3)
sio._sends(connUI, (cmd0, endInfo0))
print "re1 send"
#time.sleep(8)

#Round 2
sio._sends(connUI, begInfo1)
#time.sleep(3)
sio._sends(connUI, (cmd1, endInfo1))

print "re2 send"
#time.sleep(10)
示例#22
0
except:
	print 'failed to connect, the program will exit...'
	time.sleep(2)
	exit(1)

base=[]
beginInfo=sio._recvs(conn)
roundEndInfo=basic.Round_End_Info(beginInfo.base,(1,2,3),'route1',(1,0),(100,100),-1)
roundBeginInfo=basic.Round_Begin_Info((0,3),[(1,1),(2,2)],beginInfo.base)
i=0
print roundEndInfo.over

while roundEndInfo.over == -1:
	i+=1
	#发送每回合的开始信息
	sio._sends(conn,roundBeginInfo)

	#接收AI的命令
	roundCommand=sio._recvs(conn)
	print 'cmd recv'
	#do some calculation to get roundEndInfo here
	roundEndInfo=basic.Round_End_Info(beginInfo.base,(1,2,3),'route1',(1,0),(100,100),-1)
	
	if i==5:
		roundEndInfo.over=0
	#发送每回合结束时的信息
	print roundEndInfo.over
	sio._sends(conn,roundEndInfo)
	print 'reInfo sent'

#发送胜利方
示例#23
0
# -*- coding: UTF-8 -*-
import socket, cPickle, sio, time, t

conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    conn.connect((sio.HOST, sio.LOGIC_PORT))
except:
    print 'failed to connect, the program will exit...'
    time.sleep(2)
    exit(1)

mapInfo = sio._recvs(conn)
aiInfo = sio._recvs(conn)

#get roundInfo here
roundInfo = {'process': sio.GAME_CONTINUE, 'roundNumber': 1}

sio._sends(conn, (0, roundInfo))  #第0回合的信息
while True:
    roundCommand = sio._recvs(conn)
    #do some calculation: roundEffect,roundInfo=Calculate(Command)
    roundEffect = {}
    roundInfo = roundInfo
    sio._sends(conn, (roundEffect, roundInfo))

conn.send('|')

conn.close()

raw_input()
示例#24
0
	for j in range(0,len(whole_map[i])):
		if whole_map[i][j].kind == basic.TEMPLE:
			map_temple += [[(i, j), 0]]

while not over and turn < basic.TURN_MAX:
	turn += 1
	main.perparation(whole_map, base, score, map_temple)
	for i in range(0, basic.SOLDIERS_NUMBER):
		for j in range(0,2):
			if i >= len(base[j]):
				continue
			if base[j][i].life > 0:
				move_range = main.available_spots(whole_map, base, (j, i))
				roundBeginInfo = basic.Round_Begin_Info((j,i), move_range, base, map_temple)
				#发送每回合的开始信息:
				sio._sends(conn, roundBeginInfo)
				#接收AI的命令:
				roundCommand = sio._recvs(conn)
				roundEndInfo = main.calculation(roundCommand, base, whole_map, move_range, map_temple, score, (j, i))
				over = True
				if turn == basic.TURN_MAX and j == 1:
					for k in range(i + 1, len(base[j])):
						if base[j][i].life > 0:
							over = False
					if over:
						roundEndInfo.over = over
				#发送每回合结束时的信息:
				sio._sends(conn, roundEndInfo)
				over = roundEndInfo.over
				if over:
					break
示例#25
0
# -*- coding: UTF-8 -*-
import socket,cPickle,sio,time,t

conn=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
	conn.connect((sio.HOST,sio.LOGIC_PORT))
except:
	print 'failed to connect, the program will exit...'
	time.sleep(2)
	exit(1)

mapInfo=sio._recvs(conn)
aiInfo=sio._recvs(conn)

#get roundInfo here
roundInfo={'process':sio.GAME_CONTINUE,'roundNumber':1}

sio._sends(conn,(0,roundInfo)) #第0回合的信息
while True:
	roundCommand=sio._recvs(conn)
	#do some calculation: roundEffect,roundInfo=Calculate(Command)
	roundEffect={}
	roundInfo=roundInfo
	sio._sends(conn,(roundEffect,roundInfo))
	
conn.send('|')

conn.close()

raw_input()
示例#26
0
  #  exit(1)

serv.listen(1)
serv2.listen(1)

connUI, address = serv.accept()
print "abc"
connAI, address2 = serv2.accept()
print "daf"

print "9"
gameMode,gameMapPath,gameAIPath=sio._recvs(connUI)
print "10"
print gameMode,gameMapPath,gameAIPath

sio._sends(connAI, maps)
print "11"
info = sio._recvs(connAI)
print "12"
aiInfo = info[0]
print info
sio._sends(connUI, (maps,aiInfo, units0))
print "send init info"
#Round 1
sio._sends(connUI, begInfo0)
print "sent first"
sio._sends(connAI, begInfo0)
print "sent Ai first"
cmd0_ = sio._recvs(connAI)
print "movepos",cmd0_.move
print "recv command"