我正在制作纸牌游戏,我需要预先创建纸牌并将它们存储在 mysql 表中。我想弄清楚如何制作一个 php 脚本来创建它们。 好吧,有 6 个类别的值,从 0 到 12 不等,每张卡片都有每个类别的值。每张卡片中类别值的总和必须是 36。所以每张卡片是这样的:
- 6 - 9 - 2 - 10 - 6 - 3
或
- 0 - 12 - 0 - 12 - 0 - 12
甚至
- 6 - 6 - 6 - 6 - 6 - 6
我认为如果我可以随机生成 50 或 60 张卡片,那就太棒了。
提前致谢。
最佳答案
像这样的东西应该可以工作——逻辑可能有点不对劲,我还没有测试过。
function generate_card() {
$max_card = 12; // What's the highest value of a card number?
$min_card = 0; // What's the lowest value of a card number?
$num_cards = 6; // How many numbers on a card?
$total = 36; // What's the desired sum?
$numbers = array();
$running_total = 0;
for ($i = 0; $i < $num_cards; ++$i) {
$max = min($max_card, $total - $running_total); //The highest number we can choose
$min = max($min_card, $total - $running_total - ($max_card * ($num_cards - ($i + 1)))); //The lowest number we can choose
//- how much is left ? $total - $running total
//- min is amount_left - ($max_card
$number = rand($min, $max);
$running_total += $number;
$numbers[] = $number;
}
return $numbers;
}
编辑:我错放了一个括号和一个索引,它现在可以正常工作了。
关于php - 在列之间随机分布整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11422953/