<template><view class="index"><div @keydown="onKeyDown" tabindex="0" ref="container"><view class="SXZY" :style="styleObject"></view><view class="content_For" v-for="(item, index) in items" :key="index":style="{ left: item.left + 'rpx', top: item.top + 'rpx' }"><image src="../../static/ex1.png" style="width: 100%;height: 100%;"></image></view><div>计数: {{ count }}</div> <!-- 显示计数 --></div></view>
</template><script>export default {data() {return {items: [],count: 0,left: 0,top: 0,moveStep: 10, // 每次移动的步长 styleObject: {left: this.left + 'rpx',top: this.top + 'rpx',position: 'absolute',},};},mounted() {this.generateRandomPositions(20); // 根据需要生成 20 个随机位置 window.addEventListener('keydown', this.onKeyDown);},beforeDestroy() {window.removeEventListener('keydown', this.onKeyDown);},methods: {generateRandomPositions(count) {const positions = new Set();while (positions.size < count) {const left = Math.floor(Math.random() * (2500 - 100)); // 假设容器宽2500rpx const top = Math.floor(Math.random() * (2000 - 100)); // 假设容器高2000rpx const positionKey = `${left},${top}`;if (!positions.has(positionKey)) {positions.add(positionKey);this.items.push({left,top});}}},onKeyDown(event) {// 处理键盘按下事件,移动 SXZY switch (event.keyCode) {case 38: // 上箭头 this.top = Math.max(0, this.top - this.moveStep);break;case 40: // 下箭头 this.top = Math.min(2000 - 50, this.top + this.moveStep); // 假设容器高度限制 break;case 37: // 左箭头 this.left = Math.max(0, this.left - this.moveStep);break;case 39: // 右箭头 this.left = Math.min(2500 - 50, this.left + this.moveStep); // 假设容器宽度限制 break;}this.styleObject = {left: this.left + 'rpx',top: this.top + 'rpx',position: 'absolute',};this.checkCollision();},checkCollision() {// 检测 SXZY 是否与 content_For 碰撞 this.items.forEach((item, index) => {if (this.left < item.left + 50 && // SXZY 右边界大于 content_For 左边界 this.left + 50 > item.left && // SXZY 左边界小于 content_For 右边界 this.top < item.top + 50 && // SXZY 下边界大于 content_For 上边界 this.top + 50 > item.top // SXZY 上边界小于 content_For 下边界 ) {// 碰撞发生,移除此 content_For this.items.splice(index, 1);this.count += 1; // 计数器加1 }});},},};
</script><style>.index{width: 100vw;height: 100vh;background: paleturquoise;position: relative;overflow: hidden;}.SXZY {width: 100rpx;height: 100rpx;position: absolute;/* background: blue; */border-radius: 10rpx;background-image: url('../../static/copy.png');background-size: 100% 100%;}.content_For {width: 70rpx;height: 70rpx;/* background: red; */border-radius: 50%;position: absolute;z-index: 8;}
</style>
