<?php
include "./function.php";				//调用函数文件
include "./conn/conn.php";				//调用数据源文件
$query = mysql_query("select * from tb_room where id = '".$_GET[id]."'");
$info=mysql_fetch_array($query);
if(!$info){
	header("location:index.php");				//跳转到游戏首页
	exit;
}
$name = $info[name];			//查询用户名称
$guest = $info[guest];			//查询客户端名称
$host = $info[host];			//查询服务器名称
$chess = $info[chess];			//查看游戏的房间号
$flag = $info[flag];			//查看标记
$guest_win = $info[guest_win];		//查看客户端的赢局记录
$host_win = $info[host_win];			//查看服务器端的赢局记录

if($guest != '' && $host != '' && $username != $guest && $username != $host){
	header("location:index.php");						//跳转到游戏首页
	exit;			//退出
}
if($guest == '' && $host == '' || $username != $host && $guest == '' || $username != $guest && $host == ''){
	header("location:join.php?roomid=".$_GET[id]);		//跳转到指定的游戏房间
	exit;			//退出
}
if(isset($_COOKIE[message])){			//如果信息存储到Cookie中，则输出Cookie中的聊天信息
	echo "<script>alert('".$_COOKIE[message]."');</script>";
	setcookie(message, null);			//设置Cookie中的信息
}
?>

<div id="item" style="position:absolute; left:0px; top:0px;  z-index:1; visibility: hidden;" class="message_box"></div>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>中国网络象棋游戏 -<?php echo $name."房间";?> </title>
<style>
body{
	font-size:9pt;
	margin-left: 0px;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 0px;
	background-image: url(images/bg_pic.JPG);
}
td{
	font-size:9pt;
}
A:visited {
	COLOR: #000000; TEXT-DECORATION: none
}
A:hover {
	COLOR: #000000; TEXT-DECORATION: underline
}
A:active {
	COLOR: #000000; TEXT-DECORATION: none
}
A:link {
	COLOR: #000000; TEXT-DECORATION: none
}
.message_box{
	padding:2px 2px 2px 2px;
	border:1px solid #000000;
	background:#FFFFFF no-repeat;	
	color:#000000;
	FONT-SIZE: 13px
}
.moved{
background:url(images/moved.gif);
}
.over{
background:url(over.gif);
}
.style1 {color: #FEDB05}
.message_btn{
	padding:2px 2px 2px 2px;
	border:1px solid #5A7110;
	background:#CCFF05 no-repeat;	
	color:#000000;
	FONT-SIZE:12px;
	height:19px;
}
.style4 {color: #FFFB18}
</style>
<script src="chessrule.js"></script>
<script language="javascript">
function copy_url(){				//自定义复制网址函数
	if(window.clipboardData.setData('text',document.location.href))
		alert('复制成功！Ctrl + v 把地址发送给好友');
}
</script>
<script>
var allow_load = <?php
if(($username == $guest && $flag == guest) || ($username == $host && $flag == host))
echo 0;
else
echo 1;
?>;
var site = "<?php echo $username == $guest?'guest':'host';?>";
var site_num = "<?php echo $username == $guest?'0':'1';?>";
//房主：红旗（0），客人：黑旗（1）
var flag = "<?php echo $flag;?>";
var now_chess = "";
var moved = "";
var eated = "";
var pause_time = 0;
var prompt_pause_time = 0;
var notice = 0;
var guest_win = <?php echo $guest_win;?>;
var host_win = <?php echo $host_win;?>;
var game_ended = 0;
var t3 = "";
function form_chess(chess){		
	now_chess = chess;
	var chess_split = chess.split(",");
	var pla = "<table width=542 height=602 border=3 cellpadding=0 cellspacing=0 bordercolor=#000000 background=images/bg.gif><tr><td><table border=0 cellpadding=0 cellspacing=0 width=542 height=602>";
	if(site == "host")
		for(var i = 0;i < 10;i ++){			//设置棋盘中主机的棋子10行9列，并布置主机棋子位置
			pla += "<tr>";
			for(j = 0;j < 9;j ++){
				pla += "<td><div id=chess_"+(i * 9 + j + 1)+"><input type=hidden name=chess_value_"+(i * 9 + j + 1)+" id=chess_value_"+(i * 9 + j + 1)+" value="+chess_split[i * 9 + j]+"><a href=javascript:click_chess("+(i * 9 + j + 1)+")><img alt="+chess_split[i * 9 + j]+","+(i * 9 + j + 1)+" src=images/"+chess_split[i * 9 + j]+".gif border=0 width=58px height=58px></a></div></td>";
			}
			pla += "</tr>";
		}
	else
		for(var i = 9;i >= 0;i --){			//设置棋盘中客机的棋子10行9列，并布置客机棋子位置
			pla += "<tr>";
			for(j = 8;j >= 0;j --){
				pla += "<td><div id=chess_"+(i * 9 + j + 1)+"><input type=hidden name=chess_value_"+(i * 9 + j + 1)+" id=chess_value_"+(i * 9 + j + 1)+" value="+chess_split[i * 9 + j]+"><a href=javascript:click_chess("+(i * 9 + j + 1)+")><img alt="+chess_split[i * 9 + j]+","+(i * 9 + j + 1)+"  src=images/"+chess_split[i * 9 + j]+".gif  border=0 width=58px height=58px></a></div></td>";
			}
			pla += "</tr>";
		}
	pla += "</table></td></tr></table>";
	return pla;
}
var prev_click = "";
var chess_flash = "";
var flash_status = 0;
var guest = "<?php echo $guest;?>";
var host = "<?php echo $host;?>";
var message_guest = "";
var message_host = "";
var prev_message_guest = "";
var prev_message_host = "";
function click_chess(num){				//单击棋子操作
	if(site != flag)					//如果当前的site值不等于棋子的走棋标记,弹出对方执棋提示信息
		open_prompt("对方执棋！", 260, 180 + 596);
	else{								//否则执行走棋操作
		close_prompt();					//关闭提示信息，设置为隐藏
		for(var i = 1;i < 91;i ++)
		document.getElementById("chess_"+i).style.visibility = "visible";			//设置棋子可见
		chess_flash = "";
		if(document.getElementById("chess_value_"+num).value.substr(0, 1) == site_num){
			chess_flash = num;
			prev_click = num;			//记录棋子当前位置
		}else{
			if(prev_click != ""){		//如果棋子的走棋方法不对，则弹出提示
				if(!check(document.getElementById('chess_value_'+prev_click).value, prev_click, num))
				open_prompt("您的操作有误！", 260, 180 + 596);
				else{					//执行吃棋操作，将房间号，from棋子的原始坐标点，to目标坐标点，site是当前的玩家，time是时间
					send_request("submit.php?roomid=<?php echo $_GET[id];?>&from="+prev_click+"&to="+num+"&site="+site+"&time="+Math.random());
					allow_load = 1;
					prev_click = "";
				}
			}else
			open_prompt("这不是您的棋子！", 260, 180 + 596);
		}
	}
}

var prompt_count = 0;
function open_prompt(message, top, left){				//输出提示框所在的位置
	prompt_count = 1;
	prompt_pause_time ++;								//计时按每1秒进行累计
	if(message){
		document.getElementById("item").style.visibility = "visible";
		document.getElementById("item").style.align = "center";
		document.getElementById("item").style.top = top ;
		document.getElementById("item").style.left = left ;
		document.getElementById("item").innerHTML =  '<table class=message_box onclick=close_prompt()><tr><td><img src=images/smile.gif border=0></td><td valign=middle>系统提示：<br><br>&nbsp;&nbsp;&nbsp;&nbsp;'+message+'&nbsp;</td></tr></table>';
	}
}
function close_prompt(){			//关闭提示信息，设置为隐藏
document.getElementById("item").style.visibility = "hidden";
document.getElementById("item").innerHTML =  '';
prompt_pause_time = 0;				//计时功能初始化为0
}


var http_request = false
function send_request(url) {
open_prompt((prompt_pause_time > 0?'等待对方响应（'+prompt_pause_time+'秒）':''), 260, 180 + 596);
	http_request = false;
	if (window.XMLHttpRequest) { 
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
		http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { 
		try {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
	alert('不能创建 XMLHttpRequest 对象!');
		return false;
	}
	http_request.onreadystatechange = processRequest;
	http_request.open('GET', url, true);
	http_request.send(null);
}
//处理返回的信息
function processRequest() {				//设置棋盘中的提示信息框
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			if(http_request.responseText == "ended")
			document.location.href = "index.php";
			var text = http_request.responseText.split("|");
			if(http_request.responseText){
				t3 = text[3];
				message_guest = text[8];
				message_host = text[9];
				guest_win = text[6];
				host_win = text[7];
				if(text[4] != guest){
					if(text[4] == "")
					open_prompt(guest+"退出游戏房间！", 260, 180 + 596);
					else
					open_prompt(text[4]+"进入游戏房间！", 260, 180 + 596);
					guest = text[4];
				}
				if(text[5] != host)	{
					if(text[5] == "")
					open_prompt(host+"退出游戏房间！", 260, 180 + 596);
					else
					open_prompt(text[5]+"进入游戏房间！", 260, 180 + 596);
					host = text[5];
				}
			}
			if(now_chess != text[0] && text[0]){
				notice = 1;
				document.getElementById("pla").innerHTML = form_chess(text[0]);
				flag = text[1];
				moved = text[2];
				if(site == flag)
				allow_load = 0;
				if(text[3] == "000" && site == "guest" || (text[3] == "100" && site == "host")){	
					eated = text[3];
					game_ended = 1;
				}else
				if(text[3] == "000" && site == "host" || (text[3] == "100" && site == "guest")){	
					eated = text[3];
					game_ended = 1;
				}else
				if(text[3] && eated != text[3] && text[3] != 'blank'){	
					eated = text[3];
				}
			}
		}
	}
}

function send_message(){				//将聊天信息存储在数据库中
	var message = document.getElementById('message').value;
	if(message != ''){					//将聊天信息存储在数据表中
		send_request('send_message.php?roomid=<?php echo $_GET[id];?>&message='+message+'&site='+site+'&random='+Math.random());
		document.getElementById('message').value = '';							//消息框清空
		open_prompt('消息发送成功！', 260, 180 + 596);							//弹出消息框
	}
}
</script>
</head>

<body>
<table>
	<tr>
		<td width="210" rowspan="3" valign="top">
			<table width=191 height=100% border="0" cellpadding="0" cellspacing="0">
				<tr valign=top height=267>
				  <td height="6" valign="bottom" nowrap></td>
				</tr>
				<tr valign=top height=267>
				  <td height="237" valign="bottom" nowrap background="images/left1.gif"><table width="191" height="64" border="0" cellpadding="0" cellspacing="0">
                    <tr>
                      <th width="32" height="23" align="left" valign="middle"> </th>
                      <th width="130" height="23" align="left" valign="middle"><div id="top_box" width="100%" style="color:#A42E00"></div></th>
                      <th width="30" height="23" align="left" valign="middle"></th>
                    </tr>
                    <tr>
                      <td height="20" align="left" valign="middle"></td>
                      <td height="20" align="left" valign="middle"><div id="top_box_tongji" width="100%"></div></td>
                      <td height="20" align="left" valign="middle">&nbsp;</td>
                    </tr>
                    <tr>
                      <td height="21" align="right"></td>
                      <td height="21" align="left"><div id="top_box_flag" width="100%"></div></td>
                      <td height="21" align="right">&nbsp;</td>
                    </tr>
			      </table>
			      <br></td>
			  </tr>
				<tr><td width="191" height=88 align="center" valign=middle background="images/left4.gif"><img src="images/left3.gif" width="191" height="73" border="0" usemap="#Map"><a href="index.php"><img src="images/btn_exit.gif" width="73" height="27" border="0" /></a>
				  <script>if(site == "host") document.write("<a href=end.php?roomid=<?php echo $_GET[id];?>><img src='images/btn_end.gif' width=73 height=27 border=0></a>");</script><br>
<br>
</td></tr>
				<tr valign=bottom height=267>
				  <td height="237" nowrap background="images/left1.gif"><table width="191" border="0" cellpadding="0" cellspacing="0">
				    <tr><th width="32" height="20" align=right></th>
				      <th width="126" align=left><div id=bottom_box width=100% style="color:#A42E00"></div></th>
				      <th width="30" align=right></th>
				    </tr>
				    <tr><td height="20" align=right></td>
				      <td height="20" align=left><div id=bottom_box_tongji width=100%></div></td>
				      <td height="20" align=right></td>
				    </tr><tr><td height="20"></td>
				      <td height="20" align="left"><div id=bottom_box_flag width=100%></div></td>
				      <td height="20"></td>
				    </tr></table>
				  <br></td>
				</tr>
	  </table>	  </td>
		<td width="3" rowspan="3">
			<!--显示棋盘及背景音乐-->
			<div id="pla"></div><div style="display:none" id="sound"></div>
		    <br></td>
		<td width="220" align="right" valign=top>
		  <br><img src="images/sign.gif" width="208" height="63"></td>
	</tr>
	<tr>
 <td width="220" height="201" valign=bottom><table width="220" border="0" cellspacing="0" cellpadding="0">
   <tr align="left">
     <td height="39" colspan="3" scope="col" valign=middle background="images/right1.gif">&nbsp;<img src="images/fig2.gif" width="25" height="21" />&nbsp;<span class="style1">&nbsp;本棋盘室欢迎您发言！</span></td>
   </tr>
   <tr>
     <td height="15" colspan="3" background="images/right2.gif"><p>&nbsp;</p>
       <p>&nbsp;</p></td>
   </tr>
   <tr>
     <td width="10" background="images/right2.gif"></td>
     <td width="197" valign="bottom" bgcolor="#E0F7C1"><div id="message_pla" style="color:#506E26"></div></td>
     <td width="9" bgcolor="#E0F7C1"></td>
   </tr>
   <tr>
     <td height="10" colspan="3" background="images/right2.gif"></td>
   </tr>
   <tr>
     <td height="40" colspan="3" background="images/right3.gif">&nbsp;
       <input type="text" name="message" size="20"  class="message_box" onBlur="this.focus();" onKeyPress="if(event.keyCode==13) {document.getElementById('button').click();}" />
       <input name="button" type="button" class="message_btn" onClick="send_message()" value="发送"  /></td>
   </tr>
 </table></td>
  </tr>
	<tr>
	  <td valign=top height="8"><table width="220" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td class="style4" scope="col">注意：输入信息后单击回车即可直接发送消息给对方。</td>
        </tr>
      </table>	    </td>
  </tr>
</table>
<script>
var message_sum = 5;										//每屏显示5条信息
var message_arr = new Array();
function show_message(message){							//输出聊天记录信息
	if(message_arr.length < message_sum){					//如果聊天记录的条数小于5条，那么输出全部的聊天信息
		document.getElementById("message_pla").innerHTML += message;
		message_arr[message_arr.length] = message;
	}else{													//如果聊天记录条数大于5条，那么将
		for(var i = 1;i < message_sum;i ++){				//获取聊天记录的数组从0到4的下标，
			message_arr[i - 1] = message_arr[i];
		}
		message_arr[message_sum - 1] = message;				//将聊天信息存储在数组中，存取5条聊天记录
		document.getElementById("message_pla").innerHTML = "";		//聊天记录设置为空
		for(var i = 0;i < message_sum;i ++){						//应用For循环语句输出数组中的5条聊天记录
			document.getElementById("message_pla").innerHTML += message_arr[i];
		}
	}
}

function get_info(){					//获取聊天信息
if(guest && message_guest && prev_message_guest != message_guest){	//输出客户端玩家及留言信息
	show_message(guest + "：" + message_guest+"<br />");
	prev_message_guest = message_guest;
}
if(host && message_host && prev_message_host != message_host){	//输出服务器端玩家及留言信息
	show_message(host + "：" + message_host+"<br />");
	prev_message_host = message_host;
}


if(notice == 1){
	for(var i = 1;i <= 90;i ++){
		var chess_value = document.getElementById("chess_value_"+i).value;
		if(chess_value == "blank")
		continue;

		if(site == "guest" && chess_value.substr(0, 1) == "1" && check(chess_value, i, get_aga_num()))	{
			notice = 0;
			break;
		}
	}
}

function get_aga_num(){
	if(site == "guest"){
		for(var i = 4;i <= 24;i ++){
			if(document.getElementById("chess_value_"+i).value == "000")
			return i;
		}
	}else{
		for(var i = 67;i <= 87;i ++){
			if(document.getElementById("chess_value_"+i).value == "100")
			return i;
		}
	}
}

if(site == "guest"){						//获取客户端玩家的信息
	document.getElementById('top_box').innerHTML = "红方："+host;
	document.getElementById('bottom_box').innerHTML = "黑方："+guest;
	document.getElementById('top_box_tongji').innerHTML = "获胜："+host_win+" 局";
	document.getElementById('bottom_box_tongji').innerHTML = "获胜："+guest_win+" 局";
	if(flag == "guest")	{					//如果当前的标志为“客户端”，则在客户端输出走棋图标
		document.getElementById('bottom_box_flag').innerHTML = "<img src='./images/move.gif' width='27' height='16'>";
		document.getElementById('top_box_flag').innerHTML = "";
	}
	else{									//如果当前的标志为“服务器端”，则在服务器端输出走棋图标，客户端设置为空
		document.getElementById('top_box_flag').innerHTML = "<img src='./images/move.gif' width='27' height='16'>";
		document.getElementById('bottom_box_flag').innerHTML = "";
	}
}
else if(site == "host"){					//获取客户端玩家的信息
	document.getElementById('bottom_box').innerHTML = "红方："+host;
	document.getElementById('top_box').innerHTML = "黑方："+guest;
	document.getElementById('bottom_box_tongji').innerHTML = "获胜："+host_win+" 局";
	document.getElementById('top_box_tongji').innerHTML = "获胜："+guest_win+" 局";
	if(flag == "host")	{					//如果当前的标志为“服务器端”，则在服务器端输出走棋图标
		document.getElementById('bottom_box_flag').innerHTML = "<img src='./images/move.gif' width='27' height='16'>";
		document.getElementById('top_box_flag').innerHTML = "";
	}
	else{									//如果当前的标志为“客户端”，则在客户端输出走棋图标，服务器端设置为空
		document.getElementById('top_box_flag').innerHTML = "<img src='./images/move.gif' width='27' height='16'>";
		document.getElementById('bottom_box_flag').innerHTML = "";
	}
}
	if(moved){		//获取走棋前后显示的moved.gif红色标识，通过调用样式
		var moved_split = moved.split(",");
		document.getElementById("chess_"+moved_split[0]).className = "moved";				//moved第0个下标值显示moved.gif图片标识
		document.getElementById("chess_"+moved_split[1]).className = "moved";				//moved第1个下标值显示moved.gif图片标识
	}
if(prompt_count > 0){
	if(prompt_count == 3){
		prompt_count = 0;
		close_prompt();
	}else
	prompt_count ++;
}

	if(chess_flash != ""){
		if(flash_status == 0){
			document.getElementById("chess_"+chess_flash).style.visibility = "hidden";
			flash_status = 1;
		}else{
			document.getElementById("chess_"+chess_flash).style.visibility = "visible";
			flash_status = 0;
		}		
	}
	if(allow_load == 1){
		pause_time = 0;				//初始化对方响应的时间
		send_request('get_info.php?roomid=<?php echo $_GET[id];?>&site='+site+'&random='+Math.random());
		document.getElementById("pla").innerHTML = document.getElementById("pla").innerHTML.replace(/<a(.*?)>/ig, "");
		document.getElementById("pla").innerHTML = document.getElementById("pla").innerHTML.replace(/<\/a>/ig, "");
	}
	if(pause_time == 5 || host == "" || guest == "" || t3 == "000" || t3 == "001")
	{
		pause_time = 0;
		send_request('get_info.php?roomid=<?php echo $_GET[id];?>&site='+site+'&random='+Math.random());			//获取棋盘信息
	}
		pause_time ++;				//计时器自加1操作
	if(game_ended == 1)
	game_ended ++;
	else if(game_ended == 2){
		if(site == "host"){
					if(t3 == "100")
					guest_win ++;			//浏览器方赢一场次，在数据表中加1
					else
					host_win ++;			//服务器方赢一场次，在数据表中加1
					var url = "restart.php?roomid=<?php echo $_GET[id];?>&guest_win="+guest_win+"&host_win="+host_win;		//记录当前棋盘胜负，重新开局
					send_request(url);
		}
		game_ended = 0;
	}
}
send_request('get_info.php?roomid=<?php echo $_GET[id];?>&site='+site+'&random='+Math.random());
get_info();
setInterval("get_info()", 1000);
</script>
&nbsp;
<map name="Map" id="Map">
  <area shape="rect" coords="23,21,171,48" href="javascript:void(0)" onclick=copy_url()>
</map>
</body>
</html>
