我是PHP的新手。对于课堂作业,我们需要制作一个Tic Tac Toe游戏。到目前为止,这是我的代码:
<html>
<body>
<h1>Tic Tac Toe</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="input">
<input type="submit" name="submit">
</form>
<?php
//Display Determinations
//Top Left
if (!ISSET($_POST['submit'])) {
$GLOBALS['ul_truefalse'] = true;
$GLOBALS['turn'] = 1;
$this_happened = "!isset";
}
if (ISSET($_POST['submit'])) {
$GLOBALS['turn'] = $GLOBALS['turn'] + 1;
if ($GLOBALS['turn'] == 3) {
$GLOBALS['turn'] = 1;
}
}
if ($GLOBALS['ul_truefalse'] == true) {
$GLOBALS['ul_display'] = "UL";
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $GLOBALS['turn'] == 1) {
$GLOBALS['ul_display'] = "X";
$GLOBALS['ul_truefalse'] = false;
$this_happened = "p1 ul";
}
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $GLOBALS['turn'] == 2) {
$GLOBALS['ul_display'] = "O";
$GLOBALS['ul_truefalse'] = false;
}
}
echo "Player " . $GLOBALS['turn'] . ", it's your turn!";
echo $this_happened;
?>
<table border="1" width="40%">
<tr>
<td><?php echo $GLOBALS['ul_display'] ?></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
这是输出(左侧是页面加载时,右侧是玩家1进入&#34; ul&#34;):http://i.imgur.com/G0JaXYY.png
问题是当if (!ISSET($_POST['submit'])) {
变为false时,if语句中定义的字符串会丢失其值,从而导致未定义的变量错误。我尝试将它们存储在隐藏的表格框中,但它并没有解决问题。我将我的代码发送给论坛上的一个人,他说它有效。为什么会这样?我该如何解决这个问题?
答案 0 :(得分:-1)
试试这个:
<html>
<body>
<h1>Tic Tac Toe</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="input">
<input type="submit" name="submit">
</form>
<?php
if(!session_id())
session_start();
//Display Determinations
//Top Left
if (!ISSET($_POST['submit'])) {
$_SESSION['ul_truefalse'] = true;
$_SESSION['turn'] = 1;
$this_happened = "!isset";
}
if (ISSET($_POST['submit'])) {
$_SESSION['turn'] = $_SESSION['turn'] + 1;
if ($_SESSION['turn'] == 3) {
$_SESSION['turn'] = 1;
}
}
if ($_SESSION['ul_truefalse'] == true) {
$_SESSION['ul_display'] = "UL";
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $_SESSION['turn'] == 1) {
$_SESSION['ul_display'] = "X";
$_SESSION['ul_truefalse'] = false;
$this_happened = "p1 ul";
}
if (ISSET($_POST['input']) and $_POST['input'] == "ul" and $_SESSION['turn'] == 2) {
$_SESSION['ul_display'] = "O";
$_SESSION['ul_truefalse'] = false;
}
}
echo "Player " . $_SESSION['turn'] . ", it's your turn!";
echo $this_happened;
?>
<table border="1" width="40%">
<tr>
<td><?php echo $_SESSION['ul_display'] ?></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>