我对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输入“ul”时):http://i.imgur.com/G0JaXYY.png
问题是当if (!ISSET($_POST['submit'])) {变为false时,在if语句中定义的字符串会丢失它们的值,从而导致未定义的变量错误。我试着将它们存储在一个隐藏的表单框中,但它没有解决问题。我把我的代码发给了一个论坛上的人,他说它成功了。为什么会发生这种情况?我该怎么解决这个问题?
发布于 2014-10-12 20:28:51
试试这个:
<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>https://stackoverflow.com/questions/26329586
复制相似问题