蚂蚁爬杆问题js实现
运行效果
代码
<!DOCTYPE html>
<html>
<head>
<title>蚂蚁爬杆实验</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div style="margin: auto">
<h1 align="center" style="margin-bottom: 50px">蚂蚁爬杆实验</h1>
<div class="card">
<h3>说明</h3>
<ul>
<li>蚂蚁从杆子左边爬到右边需要两分钟</li>
<li>现在一共有20只蚂蚁</li>
<li>每只蚂蚁出现位置随机</li>
<li>每只蚂蚁初始移动方向随机</li>
<li>两只蚂蚁相遇则折返</li>
<li>问多长时间后杆子上没有蚂蚁</li>
</ul>
</div> <div class="card">
<h3>参照杆</h3>
<div class="box" id='box_reference'></div>
</div>
<div class="card">
<h3>实验杆</h3>
<div class="box" id='box'></div>
</div>
<div class="card">
<h3>控制台</h3>
<div>
<div class="card-console">
<label>蚂蚁数量:<input type="text" id='ant_num' value="20"></label>
<label>移动步长(px):<input type="text" id='speed' value="1"></label>
<label>移动时间间隔(ms):<input type="text" id='time_interval' value="20"></label>
</div>
<div class="card-console">
<button class="btn-console" id='start'>暂停</button>
<button class="btn-console" id='restart'>重新开始</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
window.TIMER = 'no_timer'//-1代表没有定时器
window.SPEED = 3
window.COLORS = ['yellow', 'white', 'cyan', 'Red', '#FF00FF', '#00FF00', '#FFA500']
function compare(o1, o2){//特定的比较器,比较style中的left
return o1.position().left - o2.position().left
} $(document).ready(function(){ let base_left = $('#box').position().left
let div_len = parseInt($('#box').css('width'))
let dom_str = '<span class="ant" id="ant_{id}" style="left:{left}px; background-color: {color};">{v}</span>' $('#start').click(function(){//启动暂停按钮何二为一了
if($(this).text()=='继续'){//继续程序
create_timer()
$(this).text('暂停')
return
}
delete_timer()
$(this).text('继续')
}) $('#restart').click(function(){//启动定时器
$('#start').text('暂停')
init()
delete_timer()
create_timer()
}) function create_timer(){
if(TIMER != 'no_timer')
return
TIMER = window.setInterval(ants_move, TIME_INTERVAL)//生成定时器
} function delete_timer(){
if(TIMER == 'no_timer')
return
window.clearInterval(TIMER)//清除定时器
window.TIMER = 'no_timer'
} function init(){
let ant_num = parseInt($('#ant_num').val())
let speed = parseInt($('#speed').val())
window.SPEED = speed//因为碰撞检测有用到速度,为了方便就挂在window下了
window.TIME_INTERVAL = parseInt($('#time_interval').val())
create_ants(ant_num, speed)
}
init()
create_timer() $(window).resize(function(){//窗口变化检测,因为水平居中,div相对像素点会变
base_left = $('#box').position().left
}) function create_ant(id, left, v, color){//生成单只蚂蚁
let temp_dom = dom_str.replace('{id}', id).replace('{left}', left).replace('{v}', v).replace('{color}', color)
return temp_dom
} function create_ants(n, speed){//生成蚂蚁
let box_html = ''
for(let i=0; i<n; i++){
let temp_left = base_left + Math.random()*div_len//随机位置
let v = speed
if(Math.random()>0.5)//随机方向
v = -v
let color = COLORS[Math.floor(COLORS.length * Math.random())]
box_html += create_ant(i, temp_left, v, color)
}
$('#box').html(box_html)//生成实验杆蚂蚁
$('#box_reference').html(create_ant(999, base_left+0, speed, 'yellow'))//生成对照杆蚂蚁
} function single_move(dom){//单个蚂蚁移动
let v = parseInt(dom.text())
let left = dom.position().left
dom.css('left', left + v)
} function ants_move(){//所有蚂蚁移动
let ants = []
$('#box>.ant').each(function(){//实验杆移动
let dom = $(this)
single_move(dom)
destroy_dom(dom)
ants.push(dom)
})
reference_ant = $('#box_reference>.ant:first')
if(reference_ant.length > 0 ){//如果元素存在
single_move(reference_ant)//对照杆蚂蚁移动
destroy_dom(reference_ant)//爬出杆子清除
}
ants = ants.sort(compare)
scan_array(ants)
} function destroy_dom(dom){//删除不在杆上的蚂蚁
let r = parseInt(dom.width())/2
let left = dom.position().left
if(left<base_left-r || left>base_left+div_len-r)
dom.remove()
} function scan_array(ants){//扫描数组
for(let i=0; i<ants.length-1; i++){
bump(ants[i], ants[i+1])
}
} function bump(ant1, ant2){//碰撞
let left1 = parseInt(ant1.position().left)
let left2 = parseInt(ant2.position().left)
if(Math.abs(left1-left2) > SPEED)//如果两球相距大于速度,不会相撞
return false let v1 = parseInt(ant1.text())
let v2 = parseInt(ant2.text())
if((v1 * v2) > 0)//如果移动方向一样,不会相撞
return false if(((left1 - left2)/(v1 - v2)) > 0)//速度相向但位置相背
return false ant1.text(-v1)
ant2.text(-v2)
// alert(1)
return true
}
})
</script>
<style type="text/css">
body{
display: flex;
align-items: center;
}
.box{
height: 20px;
width: 1000px;
background-color: black;
}
.ant{
position: absolute;
height: 20px;
width: 20px;
border-radius: 10px;
font-size: 10px;
text-align: center;
}
.card{
background: #8be88038;
padding: 10px;
margin: 10px;
border-radius: 10px;
box-shadow: 0px 0px 2px #000;
}
.card-console{
margin: 10px
}
.btn-console{
width: 100px;
height: 30px;
border: 0px;
background: black;
border-radius: 5px;
color: white;
font-weight: bold;
cursor: pointer;
}
</style>
</body>
</html>
关键点
1. 生成随机圆球(蚂蚁)
2. js操作dom移动
3. js根据某一数据排序(因为相撞只可能发生在相邻两个球中,排序减少计算量)
4. 删除超出边界的dom节点
5. js引用传递
蚂蚁爬杆问题js实现的更多相关文章
- 蚂蚁爬杆问题 UVA 10881
算法入门经典训练指南上的题. 这里有必要讲一下蚂蚁爬杆问题:每只蚂蚁都有一个初始方向,相撞会转向,关键就是相撞的处理,由于速度并不会改变,两只蚂蚁相撞,可以看做,两只蚂蚁穿过对方,继续沿原方向前进,经 ...
- LightOJ 1323 Billiard Balls(找规律(蚂蚁爬木棍))
题目链接:https://vjudge.net/contest/28079#problem/M 题目大意: 一个边界长为L宽为W的平面同时发射n个台球,运动K秒,台球碰到桌面及两(多)个台球相撞情况如 ...
- 爬虫 selenium+Xpath 爬取动态js页面元素内容
介绍 selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如 ...
- Python反爬:利用js逆向和woff文件爬取猫眼电影评分信息
首先:看看运行结果效果如何! 1. 实现思路 小编基本实现思路如下: 利用js逆向模拟请求得到电影评分的页面(就是猫眼电影的评分信息并不是我们上述看到的那个页面上,应该它的实现是在一个页面上插入另外一 ...
- CATALOGUE 目录
1 语言基础 1.1 c/c++ [转]C/C++ 存储类型 作用域 连接类型 [转]C/C++内存划分 [转]C/C++除法实现方式及负数取模详解 [转]为什么C++编译器不能支持对模板的分离式编译 ...
- 整理自百度知道提问的几道Java编程题
蚂蚁爬杆 问题描述: 有一根27厘米的细木杆,在第3厘米.7厘米.11厘米.17厘米.23厘米这五个位置上各有一只蚂蚁.木杆很细,不能同时通过一只蚂蚁.开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝 ...
- 9月最新184道阿里、百度、腾讯、头条Java面试题合集
阿里面试题 1. 如何实现一个高效的单向链表逆序输出? 2. 已知sqrt(2)约等于1.414,要求不用数学库,求sqrt(2)精确到小数点后10位 3. 给定一个二叉搜索树(BST),找到树中第 ...
- c++后台开发面试常见知识点总结(五)场景设计
搜索引擎的实现,会用到哪些重要的数据结构 设计实现一个HTTP代理服务器 / web服务器 / FTP服务器/ 设计实现cache缓存web服务器的网页访问记录 把一个文件快速下发到100w个服务器 ...
- 爬虫05 /js加密/js逆向、常用抓包工具、移动端数据爬取
爬虫05 /js加密/js逆向.常用抓包工具.移动端数据爬取 目录 爬虫05 /js加密/js逆向.常用抓包工具.移动端数据爬取 1. js加密.js逆向:案例1 2. js加密.js逆向:案例2 3 ...
随机推荐
- ASP.NET没有魔法——目录(完结)
ASP.NET没有魔法——开篇-用VS创建一个ASP.NET Web程序 ASP.NET没有魔法——为什么使用ASP.NET ASP.NET没有魔法——第一个ASP.NET应用<MyBlog&g ...
- Neo4j之坑
10个月前,我开始用neo4j做cmdb. 初体验下去neo4j很美好. 但是一年中发现一些问题, 仅仅是个人的体验.经供参考 查询语言 如果接触过Neo4j,都会为Cypher的简单和易用感觉到惊叹 ...
- C#自定义控件添加到工具箱
1.在需要使用这个自定义控件的项目中,在引用中,右键,添加引用,浏览,找到dll(如:ComButton.dll),进行添加,这时候,控件应该是能够自动添加到工具箱的. 2.在Visual Studi ...
- 如何学好java
今天发现这么一篇文章,对于笔者谈的:"一方面很努力学习,一方面又觉得不踏实",我感同身受.觉得文章写得不错,在此献给一些在java中努力的朋友们,希望能有所收获. 文章原内容: 近 ...
- windowsserver 2019系统安装教程
windowsserver2019和windowsserver2016一样也分两个版本标准版和数据中心版. 1.插入系统光盘 2.选择安装版本一般选择带桌面体验的,要不安装成功后没有桌面. 3.设置分 ...
- Linux Mint如何添加windows分享的网络打印机?
1.安装samba sudo apt-get install samba 2.找到系统打印机选项 通过 Menu-->>控制中心-->>系统管理找到 Printers选项,双击 ...
- vue 利用mockJs 模拟数据
工作这几年一直用Java 开发,前端的技术自己也忘得差不多了(实际上自己也不怎么会),最近参与的项目是用VUE + Element-ui + springboot 写的,由于需求没有定,先画一个de ...
- 转自阿里云邪-如何从小白成长为 Apache Committer?
http://wuchong.me/blog/2019/02/12/how-to-become-apache-committer/ 过去三年,我一直在为 Apache Flink 开源项目贡献,也在两 ...
- win7系统IE浏览器主页被搜狗篡改问题的解决方法
IE浏览器使用一段时间后可能大家就会遇到主页被篡改的问题,篡改之后主页就变成了搜狗页面,我们常用的百度搜索也变成了搜狗搜索,这不仅使得我们操作起 来不习惯,使用起来也会感觉非常别扭.那如果在使用IE浏 ...
- upstream timed out (110: Connection timed out) while reading response header from upstream, client:
遇到的问题 之前没配置下面这段,访问时候偶尔会出现 504 gateway timeout,由于偶尔出现,所以不太好排查 proxy_connect_timeout 300s;proxy_read_t ...