美文网首页
07-JS小案例

07-JS小案例

作者: D丝学编程 | 来源:发表于2021-04-23 10:46 被阅读0次

    一、电子日历

    准备工作:实现HTML的排版

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>我的日历</title>
            <style type="text/css">
                body{text-align: center;}
                .myTable{border-collapse:collapse; margin: 10px auto 0px auto;}
                .myTable th{background-color:#eeeeff;}
                .myTable td,.myTable th{
                    border:1px solid #9999ee;
                    width:50px;
                    height:50px;
                    text-align:center;
                    font-size:18px;
                }
                #year,#month{ width: 60px;}
            </style>
        </head>
        <body>
            <div class="myDiv">
                <input type="number" id="year" value="2022"> 年
                <input type="number" id="month" value="10"> 月
            </div>
            <div id="myCalendar">
                <table class="myTable">
                    <tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>
                    <tr><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td></tr>
                    <tr><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td></tr>
                    <tr><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td></tr>
                    <tr><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td></tr>
                    <tr><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td></tr>
                    <tr><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td></tr>
                </table>
            </div>
        </body>
    </html>
    

    JS代码实现版本:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>我的日历</title>
            <style type="text/css">
                body{text-align: center;}
                .myTable{border-collapse:collapse; margin: 10px auto 0px auto;}
                .myTable th{background-color:#eeeeff;}
                .myTable td,.myTable th{
                    border:1px solid #9999ee;
                    width:50px;
                    height:50px;
                    text-align:center;
                    font-size:18px;
                }
                .ostyle{
                    color:#999999;
                }
                #year,#month{ width: 60px;}
            </style>
            <script type="text/javascript">
                function GetMaxDays(year,month)  //获取指定年份月份下的最大天数
                {
                    if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 
                    || month == 10 || month == 12)
                        return 31;
                    if(month == 4 || month == 6 || month == 9 || month == 11)
                        return 30;
                    if(month == 2)
                    {
                        if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
                            return 29;
                        else
                            return 28;
                    }
                }
                function ShowCalendar()
                {
                    var year = document.getElementById("year").value; //求年份
                    var month = document.getElementById("month").value; //求月份
                    var myDate = new Date(year,month-1,1);  //求当月的第一天
                    var weekDay = myDate.getDay();  //求当月第一天星期几,星期天为0               
                    //求上月最大天数
                    var prevEnd = 0;
                    if(month == 1)
                        prevEnd = GetMaxDays(year-1,12);
                    else
                        prevEnd = GetMaxDays(year,month-1);
                    //求上月打印的开始日期(当月第一天星期天的时候直接-6)
                    var prevStart = weekDay == 0?prevEnd-6:prevEnd-weekDay+1;
                    var nowStart = 1; //当月打印的开始日期
                    var nowEnd = GetMaxDays(year,month); //求当月最大天数
                    var nextStart = 1; //下个月打印的开始日期
                    var sysNow = new Date(); //获取系统当前时间
                    var str = ""; //用来保存日历的table表格HTML代码
                    str += "<table class=\"myTable\">";
                    str += "<tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>";
                    for(var i = 1;i<=6;i++)
                    {
                        str+="<tr>";
                        for(var j=1;j<=7;j++)
                        {
                            if(prevStart <= prevEnd)  //打印上月日期
                                str+="<td class=\"ostyle\">" + (prevStart++) + "</td>";
                            else if(nowStart <= nowEnd)  //打印当月日期
                            {
                                if(year==sysNow.getFullYear() && month==sysNow.getMonth()+1 && nowStart==sysNow.getDate()) //判断是当天
                                    str+="<td style='background-color:red;'>" + (nowStart++) + "</td>";
                                else
                                    str+="<td>" + (nowStart++) + "</td>";
                            }   
                            else  //打印下月日期
                                str+="<td class=\"ostyle\">" + (nextStart++) + "</td>";
                        }
                        str+="</tr>";
                    }
                    str += "</table>";
                    document.getElementById("myCalendar").innerHTML = str;              
                }
            </script>
        </head>
        <body>
        <div class="myDiv">
            <input type="number" id="year" min="1900"  onchange="ShowCalendar();" > 年
            <input type="number" id="month" max="12" min="1"  onchange="ShowCalendar();"> 月
        </div>
        <div id="myCalendar">
        </div>
        <script type="text/javascript">
            var now = new Date();
            document.getElementById("year").value = now.getFullYear();
            document.getElementById("year").max = now.getFullYear()+100;
            document.getElementById("month").value = now.getMonth() + 1;
            ShowCalendar();
        </script>
        </body>
    </html>
    

    二、华容道游戏

    需要完成此游戏,需要以二维数组和监听键盘为前提:

    二维数组:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>二维数组基本语法</title>
        </head>
        <body>
    <script type="text/javascript">
        //二维数组的定义   (JS中定义数组可以未知长度,所以以下代码的长度是可以省略的)
        // var arr = new Array(2); //先声明一维
        // arr[0] = new Array(5); //第一个元素又是一个数组
        // arr[1] = new Array(5); //第二个元素又是一个数组
        //也可以简写
        //var arr = new Array(new Array(5),new Array(5));
        
        //二维数组的初始化
        //var arr = new Array(new Array(1,2,3,4),new Array(5,6,7,8));
        //或者
        var arr = [[1,2,3,4],[5,6,7,8]];
        
        //引用数组的某个元素
        arr[1][2] = 666; //设置第二行第三个元素为666
    
    </script>
        </body>
    </html>
    

    键盘监听:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>键盘监听</title>
        </head>
        <body>
    <script type="text/javascript">
        document.onkeydown = function(e)
        {
            alert(e.keyCode); //打印键盘按下的键对应的编码
        }
    </script>
        </body>
    </html>
    
    

    代码:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>4*4数字华容道游戏</title>
            <style type="text/css">
                div,ul,li{margin: 0px; padding: 0px;}
                #main{ width: 750px; height: auto; overflow: hidden; margin: 0px auto;}
                #left{width: 362px; float: left;}
                #right{width: 362px; float:right;}
                .myTitle{text-align: center; height: 40px; line-height: 40px; 
                font-size: 16px; font-weight: bold;}
                #myContainer,#myAnswerContainer{width: 360px; height: 360px; 
                margin: 0px auto; border: solid 1px darkred;}
                #myContainer div,#myAnswerContainer div{ width: 80px; height: 80px; line-height: 80px; margin: 5px; float: left;
                background-color:darkred; color: white; font-weight: bold; font-size: 30px;
                text-align: center;}
                #result{ clear: both; margin-top: 20px; text-align: center; font-size: 40px; font-weight: bold;}
            </style>
            <script type="text/javascript">         
                var myArr = [["1","2","3","4"],["5","6","7","8"],["9","10","11","12"],["13","14","15","$"]]; //定义二维数组
                var $rowIndex = 3;  //记录美元符号的行号
                var $columnIndex = 3; //记录美元符号的列号
                //二维数组两个元素交换
                function swapArr(row1,col1,row2,col2)
                {
                    var temp = myArr[row1][col1];
                    myArr[row1][col1] = myArr[row2][col2];
                    myArr[row2][col2] = temp;
                }
                //产生随机数字(使用正确答案,然后将$不停上下左右移动来实现)
                function setRndNumber()
                {
                    for(var i=1;i<=1000;i++)
                    {
                        myRnd = Math.ceil(Math.random()*4);
                        if(myRnd == 1) //上移动
                        {
                            if($rowIndex == 0) continue;
                            swapArr($rowIndex,$columnIndex,$rowIndex-1,$columnIndex);
                            $rowIndex--;
                        }
                        if(myRnd == 2) //右移动
                        {
                            if($columnIndex == 3) continue;
                            swapArr($rowIndex,$columnIndex,$rowIndex,$columnIndex+1);
                            $columnIndex++;
                        }
                        if(myRnd == 3) //下移动
                        {
                            if($rowIndex == 3) continue;
                            swapArr($rowIndex,$columnIndex,$rowIndex+1,$columnIndex);
                            $rowIndex++;                        
                        }
                        if(myRnd == 4) //左移动
                        {
                            if($columnIndex == 0) continue;
                            swapArr($rowIndex,$columnIndex,$rowIndex,$columnIndex-1);
                            $columnIndex--;                     
                        }
                    }               
                }
                //生成游戏界面
                function createUI()
                {
                    var objContainer = document.getElementById("myContainer");
                    objContainer.innerHTML = "";
                    for(var i = 0;i <= 3;i++)
                    {
                        for(var j = 0;j <= 3;j++)
                        {
                            var obj = document.createElement("div");
                            obj.id = "div_" + i + "_" + j;
                            obj.innerHTML = myArr[i][j];
                            if(i==$rowIndex && j==$columnIndex)
                                obj.style.backgroundColor = "darkgreen";                        
                            objContainer.appendChild(obj);
                        }                   
                    }
                }
                //生成答案UI
                function createAnswerUI()
                {
                    var objContainer = document.getElementById("myAnswerContainer");
                    for(var i = 0;i <= 3;i++)
                    {
                        for(var j = 0;j <= 3;j++)
                        {
                            var obj = document.createElement("div");
                            obj.id = "answer_" + i + "_" + j;
                            obj.innerHTML = myArr[i][j];
                            if(i==3 && j==3)
                                obj.style.backgroundColor = "darkgreen";
                            objContainer.appendChild(obj);
                        }                   
                    }
    
                }
                function StartGame()
                {
                    window.location.reload();
                }
                //移动之后判断是否胜利
                function IsWin()
                {
                    if($rowIndex != 3 && $columnIndex != 3) return false;
                    for(var i = 0;i <= 3;i++)
                    {
                        for(var j = 0;j <= 3;j++)
                        {
                            if(i==3 && j==3) //最后一个格子不需要进行判断
                                continue;
                            if(myArr[i][j] != i*4+j+1)
                            {
                                return false;
                            }
                        }                   
                    }               
                    return true;                
                }
                //监听键盘按下事件
                document.onkeydown = function(e)
                {
                    //键盘编码w-87,s-83,a-65,d-68 
                    //方向       上-38,下-40,左-37,右-39
                    if(e.keyCode == 87 || e.keyCode == 38)  //上
                    {
                        if($rowIndex == 0) return;
                        swapArr($rowIndex,$columnIndex,$rowIndex-1,$columnIndex);
                        $rowIndex--;
                    }
                    if(e.keyCode == 83 || e.keyCode == 40)  //下
                    {
                        if($rowIndex == 3) return;
                        swapArr($rowIndex,$columnIndex,$rowIndex+1,$columnIndex);               
                        $rowIndex++;
                    }
                    if(e.keyCode == 65 || e.keyCode == 37)  //左
                    {
                        if($columnIndex == 0) return;
                        swapArr($rowIndex,$columnIndex,$rowIndex,$columnIndex-1);
                        $columnIndex--;
                    }
                    if(e.keyCode == 68 || e.keyCode == 39)  //右
                    {
                        if($columnIndex == 3) return;
                        swapArr($rowIndex,$columnIndex,$rowIndex,$columnIndex+1);
                        $columnIndex++;
                    }
                    createUI();
                    var result = IsWin();
                    if(result == true); //如果游戏胜利
                    {
                        document.getElementById("result").innerText = "胜利!";
                        document.getElementById("result").style.color = "darkred";
                    }
                    if(result == false) //如果没有胜利
                    {
                        document.getElementById("result").innerText = "游戏进行中......";
                        document.getElementById("result").style.color = "black";                    
                    }               
                }
            </script>
        </head>
        <body>
            <div id="main">
                <div id="left">
                    <div class="myTitle">
                        <input type="button" id="startGame" value="重新开始游戏" onclick="StartGame();" />
                        (wsad或上下左右来移动$)
                    </div>
                    <div id="myContainer">
                        
                    </div>              
                </div>
                <div id="right">
                    <div class="myTitle">正确答案</div>
                    <div id="myAnswerContainer">
                        
                    </div>
                </div>
            </div>
            <div id="result">
                游戏进行中......
            </div>
        </body>
    </html>
    <script type="text/javascript">
        createAnswerUI();
        setRndNumber();
        createUI();
    </script>
    <!--
    解法:
    步骤一:
    第一排:1 2 3 4,如遇到4无法归位,则先变成如下
    1 3 * _ 
    * 2 * 4 
    步骤二:同理排第二排和第三排
    步骤三:第二排和第三排弄好后,可能第四排也自动好了,如果没有好,则先变成如下:
    *    9    *    *
    10   —    *    *
    左边4个数字,9下移转一圈,如下:
    10   *    *    *
    9    —    *    *
    然后:
    10   *    —    12
    9    *    11    *
    右边4个数字,11上移转一圈,如下:
    10   *    —    11
    9    *    *    12
    然后:
    10  __  15  11
    9   13  14  12
    然后将10往右移动
    -->
    

    三、贪吃蛇

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <html>
        <head>
            <meta charset="UTF-8">
            <title>贪吃蛇</title>
            <style type="text/css">
                body,div{ margin:0px; padding: 0px;}
                #main{ width: 800px; height: 700px; margin: 20px auto; text-align: center;}
                #startDiv{ width: 100px; height: 30px; margin: 10px auto;}
                #startGame{ width: 100px; height: 30px; }
                #map{width: 800px; height: 600px; position: relative; border:solid 1px pink;}
                #map div{ border-radius: 50%; position: absolute;}
            </style>
        </head>
        <body>
            <div id="main">
                <div id="startDiv">
                    <input id="startGame" type="button" value="开始游戏" onclick="StartGame();" />
                </div>
                <div id="map">
                    
                </div>
            </div>
        </body>
    </html>
    <script type="text/javascript">
        var map = document.getElementById("map");
        var width= 20;
        var height= 20;
        var direction = 4;  //1,2,3,4分别代表上右下左
        var snakebody = []; //默认蛇有三节身体
        var cakePosition={};
        var MyInterval;  //用来控制定时器的变量
        function PrepareGame()
        {
            map = document.getElementById("map");
            width = 20;
            height = 20;
            direction = 4;  //1,2,3,4分别代表上右下左
            snakebody = [{x:800-width*3,y:0,color:GetRndColor()},
            {x:800-width*2,y:0,color:GetRndColor()},
            {x:800-width,y:0,color:GetRndColor()}]; //默认蛇有三节身体
    cakePosition={x:width*(Math.floor(Math.random()*40)),y:height*(Math.floor(Math.random()*30)),color:GetRndColor()};
        }
        //显示蛇和食物
        function showSnakeAndCake()
        {
            map.innerHTML = "";
            //显示蛇
            for(var i = 0;i< snakebody.length;i++)
            {
                var snake = document.createElement("div");
                snake.id = "s" + i;
                snake.style.width = width + "px";
                snake.style.height = height + "px";
                snake.style.backgroundColor=snakebody[i].color;
                snake.style.left = snakebody[i].x + "px";
                snake.style.top = snakebody[i].y + "px";
                snake.innerHTML = i;
                map.appendChild(snake);
            }
            //显示食物
            var cake = document.createElement("div");
            cake.id = "divCake";
            cake.style.width = width + "px";
            cake.style.height = height + "px";
            cake.style.backgroundColor=cakePosition.color;
            cake.style.left = cakePosition.x + "px";
            cake.style.top = cakePosition.y + "px";
            map.appendChild(cake);
        }
        
        //蛇的移动
        function moveSnake()
        {
            //移动蛇之前记录蛇尾巴的坐标
            var SnakeTail = {x:snakebody[snakebody.length-1].x,y:snakebody[snakebody.length-1].y,color:cakePosition.color};
            //除了蛇头之外,其它的部门向前移动一格
            for(var i = snakebody.length-1;i > 0 ;i--)
            {
                snakebody[i].x = snakebody[i-1].x;
                snakebody[i].y = snakebody[i-1].y;
            }
            //根据方向处理蛇头的移动
            switch(direction)
            {
                case 1:snakebody[0].y -= height;break;  //上
                case 2:snakebody[0].x += width;break;  //右
                case 3:snakebody[0].y += height;break;  //下
                case 4:snakebody[0].x -= width;break;  //左
            }
            //判断吃到食物,将食物添加到蛇尾巴
            if(snakebody[0].x == cakePosition.x && snakebody[0].y == cakePosition.y)
            {
                snakebody.push(SnakeTail);
                cakePosition.color = GetRndColor();
                cakePosition.x = width*(Math.floor(Math.random()*40));
                cakePosition.y = height*(Math.floor(Math.random()*30));     
            }
            showSnakeAndCake(); //移动完成后显示
            //判断蛇是否出界(只要蛇头出界则出界)
            if(snakebody[0].x < 0 || snakebody[0].x > 800-width 
                || snakebody[0].y < 0 || snakebody[0].y > 600-height)
            {
                CloseGame("撞墙了!");
            }
            //判断蛇是否吃了自己
            for(var i=1;i<snakebody.length;i++)
            {
                if(snakebody[0].x == snakebody[i].x && snakebody[0].y == snakebody[i].y)
                {
                    CloseGame("自己把自己吃了!");
                    break;
                }
            }
            
        }
        //产生随机颜色
        function GetRndColor()
        {
            var red = Math.floor(Math.random()*256);
            var green = Math.floor(Math.random()*256);
            var blue = Math.floor(Math.random()*256);
            return "RGB("+red+","+green+","+blue+")";       
        }
        //键盘监听
        document.body.onkeydown = function(e)
        {
            //获取事件对象
            var ev = e || window.event;
            switch(ev.keyCode) //38上,39右,40下,37左
            {
                //后面一个条件判断头和第一个元素是否在横轴或者纵轴,解决快速两个方向键的情况
                case 38: 
                    if(direction!=3 && snakebody[0].x != snakebody[1].x) 
                        direction = 1;  break;
                case 39: 
                    if(direction!=4 && snakebody[0].y != snakebody[1].y) 
                        direction = 2; break;
                case 40: 
                    if(direction!=1 && snakebody[0].x != snakebody[1].x) 
                        direction = 3; break;
                case 37: 
                    if(direction!=2 && snakebody[0].y != snakebody[1].y) 
                        direction = 4; break;
            }
        }
        
        function CloseGame(ErrInfo)
        {
            clearInterval(MyInterval);
            map.innerHTML = "";
            PrepareGame();
            alert(ErrInfo + ",Game Over!");
        }   
        //开始游戏
        function StartGame()
        {
            clearInterval(MyInterval);
            map.innerHTML = "";
            PrepareGame();
            showSnakeAndCake(); //显示蛇和食物    
            MyInterval=setInterval("moveSnake()",100);
        }   
    </script>
    

    相关文章

      网友评论

          本文标题:07-JS小案例

          本文链接:https://www.haomeiwen.com/subject/tnhzkltx.html