0

我正在练习构建二十一点游戏,但我无法击中两次。这是我的代码:

if (empty($_POST)) {
  for ($i=0; $i<2; $i++) {
    $pHand[] = array_shift($deck);
    $dHand[] = array_shift($deck);
  }
  $deck2 = serialize($deck);
  $pHand2 = serialize($pHand);
  $dHand2 = serialize($dHand);
}


elseif ($_POST['hit'] == "Hit") {
  $deck = unserialize($_POST['deck']);
  $pHand = unserialize($_POST['pHand']);
  $dHand = unserialize($_POST['dHand']);
  $pHand[] = array_shift($deck);
  $deck2 = serialize($pHand);
  $pHand2 = serialize($dHand);
  $dHand2 = serialize($deck);
}


<form method="post">
<input type="hidden" name="pHand" value="<?php echo htmlspecialchars($pHand2, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="dHand" value="<?php echo htmlspecialchars($dHand2, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="deck" value="<?php echo htmlspecialchars($deck2, ENT_QUOTES, 'UTF-8'); ?>">

这一切都很好,但如果我再次按下“Hit”,我的 $pHand 数组就会变成完全不同的东西。如何从第一个“命中”中保持相同的值,以便可以将其添加到第二个、第三个等“命中”?

4

1 回答 1

0

考虑使用 $_SESSION 在提交之间存储数据服务器端。

类似于以下内容:

<?php
session_start();

if (empty($_POST)) 
{
  for ($i=0; $i<2; $i++) 
  {
    $pHand[] = array_shift($deck);
    $dHand[] = array_shift($deck);
  }

  $_SESSION['deck']  = $deck;
  $_SESSION['pHand'] = $pHand;
  $_SESSION['dHand'] = $dHand;
}
elseif ($_POST['hit'] == "Hit") 
{
  $deck    = $_SESSION['deck'];
  $pHand   = $_SESSION['pHand'];
  $dHand   = $_SESSION['dHand'];
  $pHand[] = array_shift($deck);
  $_SESSION['deck']  = $deck;
  $_SESSION['pHand'] = $pHand;
  $_SESSION['dHand'] = $dHand;
}
于 2013-08-08T02:00:11.973 回答