droe9376 2018-08-29 06:45
浏览 32

PHP限制可用的游戏卡数量

I'm working on a scratch card game for a website. The game is simple, win or lose.

I found this code in php for the game, it's working great :

function winningChance(int $percentage): string
{
if ($percentage < 0 || $percentage > 100) {
    throw new \Exception('Invalid percentage');
}
return rand(1, 100) <= $percentage ? 'won' : 'lost';
}
echo "You've " . winningChance(1) . '!';

But I have a problem, I need to limit the number of playing cards and generate randomly just one time a winning card and don't know how to do that.

For exemple :

I limit the game to 150 playing cards, so I have 150 players, 149 losers, 1 winner ?

How can i do that in php ? Can someone help me ?

Thank you !

  • 写回答

1条回答 默认 最新

  • drny20290570 2018-08-29 07:43
    关注

    You'd probably need something like this:

    <?php
    
    /**
     * Gets a random result for a given min-max pair and
     * remember the result until the provided database is
     * removed / truncated.
     *
     * @param PDO $db
     *   Database connected to store result.
     * @param int $min
     *   Minimum integer for the result.
     * @param int $max
     *   Maximum integer for the result.
     */
    function remember_or_new_result(PDO $db, int $min, int $max):int {
      // create and prepare a database file to store past results.
      $db->query('CREATE TABLE IF NOT EXISTS result (card INT PRIMARY KEY, min INT, max, INT)');
    
      // search existing result
      $search = $db->prepare('SELECT COUNT(*) AS count, card FROM result WHERE min=:min AND max=:max');
      if ($search && $search->execute([':min' => $min, ':max' => $max])) {
        $result = $search->fetch(PDO::FETCH_OBJ);
        if ($result->count > 0) return $result->card; // return past result
      }
    
      // randomize and remember the result.
      $rand = rand($min, $max);
      $insert = $db->prepare('INSERT INTO result (min, max, card) VALUES (:min, :max, :card)');
      $insert->execute([
        ':min' => $min,
        ':max' => $max,
        ':card' => $rand,
      ]);
    
      return $rand;
    }
    
    // connect to an SQLite database. Require php-sqlite3 installed.
    // or simply change the database connection string.
    $db = new PDO('sqlite:local.db');
    echo ($your_card == remember_or_new_result($db, 1, 150)) ? 'win' : 'lost';
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题