我这里用一个html+js的例子,这样大家可以更好的去看效果
这次春晚需要执行的逻辑就是:
1.根据名字的长度n,把数组的第一位放到最后,一次执行n次
2.取出前三张牌,随机插入到牌组中的任意一项中
3.最上面一张取走
4.南方人北方人:随机数 1-3,插入中间
5.男生女生:随机数1-2,去除
6.见证奇迹的时刻,七个字,依次放在最后一位
7.好运留下来,烦恼丢出去,依次保留放在最后,丢出牌
好,下面直接上代码,就是一个html,直接粘出去就能用了,这里说白了就是,你名字有几位,最终得到的就是第几张牌,超出四位就循环往复
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>见证奇迹的时刻</title>
</head>
<body>
<div>见证奇迹的时刻</div>
<!-- 名字,南北方,男女生 -->
<input type="text" id="name" placeholder="名字">
<select id="gender">
<option value="1">男</option>
<option value="2">女</option>
</select>
<select id="direction">
<option value="1">南方</option>
<option value="2">北方</option>
<option value="3">我也不知道</option>
</select>
<button onclick="magicstart()">开始</button>
<div id="result"></div>
</body>
<script>
// 八张卡片
var a = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
//藏起来的牌
var first = ''
//是否弃牌
var flag = true
var result = document.getElementById('result')
// 随机数
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
// 给定一个数字n,把数组的第一位放到最后,一次执行n次
function shuffle(arr, n) {
for (let i = 0; i < n; i++) {
const nums = arr.shift()
arr.push(nums)
}
return arr
}
// 取出前三位,随机插入到数组中的任意一项中
function nameChanges(arr) {
const nums = arr.splice(0, 3)
const index = randomNum(1, 2)
arr.splice(index, 0, ...nums)
return arr
}
// 换牌扔牌步骤
function getOne(arr, name, gender, direction) {
// 最上面一张取走--名字
first = nameChanges(shuffle(arr, name)).shift()
// 南方人北方人:随机数 1-3,插入中间
const nums = arr.splice(0, direction)
const index = randomNum(1, 3)
arr.splice(index, 0, ...nums)
// 男生女生:随机数1-2,去除
const nums2 = arr.splice(0, gender)
// 见证奇迹的时刻,依次放在最后一位
const newArr = shuffle(arr, 7)
//好运留下来,烦恼丢出去
console.log(happyNewYear(newArr)[0], first);
result.innerHTML = `
<div>幸运牌:${first}</div>
<div>幸运牌:${happyNewYear(newArr)[0]}</div>
`
// 初始化
a = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
flag = true
}
// 好运留下来,烦恼丢出去
function happyNewYear(arr) {
// 数组第一项放在最后,第二项扔掉,直到数组只剩下一位
while (arr.length > 1) {
// 判断是否需要放在最后一位
if (flag) {
const nums = arr.shift()
arr.push(nums)
flag = !flag
} else {
arr.shift()
flag = !flag
}
}
return arr
}
function magicstart() {
// 获取各输入框的值
const name = document.getElementById("name").value.length;
const gender = document.getElementById("gender").value;
const direction = document.getElementById("direction").value;
getOne(a, name, gender, direction)
}
</script>
</html>