GVKun编程网logo

js 翻牌小游戏(js翻牌小游戏)

9

这篇文章主要围绕js翻牌小游戏和js翻牌小游戏展开,旨在为您提供一份详细的参考资料。我们将全面介绍js翻牌小游戏的优缺点,解答js翻牌小游戏的相关问题,同时也会为您带来construct2制作小游戏—

这篇文章主要围绕js 翻牌小游戏js翻牌小游戏展开,旨在为您提供一份详细的参考资料。我们将全面介绍js 翻牌小游戏的优缺点,解答js翻牌小游戏的相关问题,同时也会为您带来construct2制作小游戏——捉老鼠小游戏、FinClip 支持小游戏能力,可上架小游戏到任何App、JavaScript小游戏之迷宫小游戏的实例、Java小游戏实战开发——贪吃蛇小游戏的实用方法。

本文目录一览:

js 翻牌小游戏(js翻牌小游戏)

js 翻牌小游戏(js翻牌小游戏)

js 翻牌小游戏

效果图

在这里插入图片描述

需求分析

  1. 生成两组顺序随机的1-8数据
  2. 卡片需要有翻转效果
  3. 两次翻转数据不相等,回复原状
  4. 两次翻转数据相等,卡片相等,不能再被点击
  5. 当所有卡片不能被点击游戏结束
  6. 限制最大点击次数50次

HTML结构

<div class="wrap">
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
        <div>
            <p class="top"></p>
            <p class="bottom"></p>
        </div>
    </div>

css布局

    实现卡片翻转效果需要3个关键属性

  1. perspective: 1000px; 透视深度,形成3d视角
  2. transform: rotateY(180deg);旋转
  3. backface-visibility: hidden; 元素背面不可见
* {
            margin: 0;
            padding: 0;
        }

        body,
        html {
            height: 100%;
        }

        .wrap {
            perspective: 1000px;
            width: 320px;
            height: 320px;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            display: flex;
            justify-content: center;
            text-align: center;
            flex-wrap: wrap;
        }

        .wrap div {
            /* box-shadow: 5px 5px 10px #000; */
            transition: 1s;
            position: relative;
            text-align: center;
            line-height: 60px;
            height: 60px;
            width: 60px;
            border-radius: 10px;

            margin: 10px 10px;
        }

        .wrap div .active1 {
            transform: rotateY(180deg);
        }

        .wrap div .active2 {
            transform: rotateY(360deg);
        }

        .wrap p {
            border-radius: 10px;
            background-color: blueviolet;
            transition: 1s;
            backface-visibility: hidden;
            display: block;
            height: 60px;
            width: 60px;
            position: absolute;
            /* transform: rotateY(180deg); */
        }

        .wrap .bottom {
            transform: rotateY(180deg);
        }
        h3{
            text-align: center;
            width: 200px;
            height: 30px;
            margin: 150px auto;
        }

js

class Game {
            constructor(selector) {
                this.init(selector);
            }
            init(selector) {
                let arr = this.randomArr();
                this.nodes = [...document.querySelectorAll(selector)];//获取每一个卡片
                this.step = 50;//定义可以被点击的次数
                this.tit = document.querySelector("h3");
                this.nodes.forEach((item,index) => {//初始化卡片的值,并保存在num属性中
                    item.children[1].innerHTML = arr[index];
                    item.num =  arr[index];
                    var that = this
                    item.onclick = function () {//给每一个卡片绑定事件
                        that.handle(this);
                    }
                })
            }
            handle(ele) {
                if(this.step === 0){
                    alert(''游戏结束'')
                    return
                }
                if(ele.active !== true){
                    this.step--;
                    this.tit.innerText = `剩余步数:${this.step}`
                }
                ele.children[0].classList.add(''active1'');//卡片翻转
                ele.children[1].classList.add(''active2'');      
                let res = this.nodes.filter(item => item.children[0].classList.contains(''active1'')&& item.active !== true); //获取翻过来的且没有配对成功的卡片
                if(res.length === 2 && res[0].num !== res[1].num){//如果有两张并且数值不相等,恢复原状  
                   setTimeout(()=>{
                        res[0].children[0].classList.remove(''active1'');
                        res[0].children[1].classList.remove(''active2'');
                        res[1].children[0].classList.remove(''active1'');
                        res[1].children[1].classList.remove(''active2'');  
                    },1000)//延迟一秒形成动画    
                }else if(res.length === 2 && res[0].num === res[1].num){//如果数值相等则配对成功
                     res[0].active = true;//锁定卡片
                     res[1].active = true;
                }
            }
            randomArr() {
                let arr = [];
                for (let i = 0, n = 8; i < n; i++) {
                    do {
                        var item = randomInt(1, 8);
                    } while (arr.indexOf(item) !== -1)
                    arr.push(item);
                }
                arr.push(...arr);
                return arr;
            }
        }
        new Game(''.wrap div'')
        function randomInt(min, max) {//产生[min,max]范围内的整数
    return Math.round(Math.random() * (max - min)) + min
}

construct2制作小游戏——捉老鼠小游戏

construct2制作小游戏——捉老鼠小游戏

游戏测试链接

http://1.kk123.applinzi.com/New%20project/index.html

开发工具:construct2

游戏介绍:上下左右按钮控制飞机,中间按钮放出子弹捕捉老鼠,灰老鼠比白老鼠厉害且移动速度快,还有一个穿梭门一样,老鼠经过那里就消失了

游戏运行效果截图:

游戏制作步骤

1.收集素材(play,enemy,button,others)
2.导入素材,布置场景
3.添加玩家,并给玩家添加行为和事件
4.添加敌人、子弹、按钮,并给敌人、子弹、按钮添加行为和事件
5.创建HUD图层,实现交互
6.测试发布

一、收集素材(部分素材通过PS二次加工)

二、导入素材,布置场景(两人构思剧情和布局)

1.新建工程

1.capx

2.修改布局

layou size

windows size

3.插入背景

同理插入其他背景素材,Ctrl+拖拽可以对物体进行复制

4.添加keyboard,mouse,touch(这些对象不会在画布中显示)

三、添加行为和事件

1.给对象添加行为

选中对象,左侧菜单点击behaviors

2.给对象添加事件

打开eventsheet1界面,给对象添加特定事件与action

四、创建HUD图层,实现交互

1.点击hud图层,设置parallax为(0,0)

2.创建对象(创建方式同上,无需添加行为)

添加文本,双击空白处,选择text

3.打开eventsheet1面板

在空白处右键,添加全局变量

记录得分

上下左右控制移动

五、测试发布

1.导出工程文件

1.导出文件包

2.注册新浪云账号,创建一个新的sae云应用

FinClip 支持小游戏能力,可上架小游戏到任何App

FinClip 支持小游戏能力,可上架小游戏到任何App

自FinClip  诞生以来,一直有不少开发者询问官方 FinClip 什么时候可以支持微信小游戏?实际上,从去年开始我们就把支持微信小游戏的计划做进了产品的 Roadmap。2022年底,我们终于在新年之前实现了对小游戏的支持!

目前,开发者通过FinClip 可以将小程序游戏上架到任何APP(不局限于微信),实现小游戏导流、变现。2023年2月,我们正式面向开发者们发起功能内测,FinClip官方为开发者提供开发工具(IDE)、APP与小游戏demo,帮助大家体验核心功能。诚挚的邀请各位开发者参与FinClip  支持小游戏的内测体验活动!

欢迎大家来试用、体验、拍砖~官方还有丰厚的内测福利等着你哦!

参与方式:

1、注册FinClip,并在 FinClip 成功上架并运行一款小游戏。上架的小游戏可以是自研,也可以是开源小游戏。
2、输出关于小游戏上架体验评测报告,反馈意见和建议,提交至 FinClip GitHub 仓库 Issues 列表
3、参与对象:企业开发者、个人开发者、开源团队、高校学生、新技术极客、只要你喜欢开发、门槛不限
4、活动时间:2023年02月06日-2023年03月20日

活动奖品:

小游戏上架APP流程简介

任何一款小程序游戏,均可上线至任何APP(不再局限于微信),FinClip官网为开发者提供开发工具(IDE)、APP与小游戏demo。

体验上架流程如下:

  1. 注册 FinClip 账户,成为小游戏开发者。
  2. 设置域名白名单。
  3. 选择一款游戏引擎(推荐 Cocos,Egret,Laya),完成小游戏的本地开发,调试与测试。
  4. 如果选择的游戏引擎已经可以导出为小游戏,那就可以直接导出并上传(FinClip 在小游戏部分依然提供了微信小游戏的兼容,并且提供兼容检查工具。)
  5. 参照目录结构和配置说明,对小游戏进行一部分的微调。
  6. 安装开发者工具(FIDE),并且对游戏进行本地调试。
  7. 上传小游戏,在后台扫码进行真机预览。
  8. 提交审核上线。

⚠️注意事项:

参与内测的开发者需将FIDE升级到最新版本。点击下载最新FIDE

官方小游戏开发指南:

官方文档小游戏开发指南

手把手系列:如何将小程序游戏引入自有APP?(iOS篇)

手把手系列:如何将小程序游戏引入自有APP?(Android篇)

JavaScript小游戏之迷宫小游戏的实例

JavaScript小游戏之迷宫小游戏的实例

这篇文章主要介绍了js实现的走迷宫小游戏,涉及javascript键盘事件响应及页面元素动态变换相关操作技巧,需要的朋友可以参考下

本文实例讲述了JS实现的走迷宫小游戏。分享给大家供大家参考,具体如下:

先来看看运行效果截图:

完整实例代码如下:

立即学习“Java免费学习笔记(深入)”;


<!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">
<head>
<title>JS打造的走迷宫游戏</title>
</head>
<body>
<SCRIPT>
function ShowMenu(bMenu) {
document.all.idFinder.style.display = (bMenu) ? "none" : "block"
document.all.idMenu.style.display = (bMenu) ? "block" : "none"
idML.className = (bMenu) ? "cOn" : "cOff"
idRL.className = (bMenu) ? "cOff" : "cOn"
return false
}
</SCRIPT>
<STYLE>
<!--
A.cOn {text-decoration:none;font-weight:bolder}
#article {font: 12pt Verdana, geneva, arial, sans-serif; background: white; color: black; padding: 10pt 15pt 0 5pt}
#article P.start {text-indent: 0pt}
#article P {margin-top:0pt;font-size:10pt;text-indent:12pt}
#article #author {margin-bottom:5pt;text-indent:0pt;font-style: italic}
#pageList P {padding-top:10pt}
#article H3 {font-weight:bold}
#article DL, UL, OL {font-size: 10pt}
-->
</STYLE>
<SCRIPT>
<!--
function addList(url,desc) {
if ((navigator.appName=="Netscape") || (parseInt(navigator.appVersion)>=4)) {
var w=window.open("","_IDHTML_LIST_","top=0,left=0,width=475,height=150,history=no,menubar=no,status=no,resizable=no")
var d=w.document
if (!w._init) {
d.open()
d.write("<TITLE>Loading...</TITLE><EM>Loading...</EM>")
d.close()
w.opener=self
window.status="Personal Assistant (Adding): " + desc
} else {
window.status=w.addOption(url,desc)
w.focus()
}
}
else
alert("Your browser does not support the personal assistant.")
return false
}
// -->
</SCRIPT>
<STYLE TYPE="text/css">
#board TD {width: 15pt; height: 15pt; font-size: 2pt; }
TD.foot {font-size: 10pt;}
#board TD.start {font-size: 8pt; border-left: 2px black solid; background:yellow; border-top: 2px black solid;text-align: center; color: red}
#board TD.end {font-size: 8pt; text-align: center; color: green}
#message {margin: 0pt; padding: 0pt; text-align: center}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
var maze = new Array()
var sides = new Array("Border-Top", "Border-Right")
for (var rows=0; rows<13; rows++)
maze[rows] = new Array()
maze[0][0] = new Array(1,1,1,1,1,1,1,1,1,1,1,1)
maze[0][1] = new Array(0,0,1,0,1,0,0,0,0,1,0,1)
maze[1][0] = new Array(1,0,0,0,1,0,1,1,1,0,1,1)
maze[1][1] = new Array(0,1,1,0,0,1,1,0,0,1,0,1)
maze[2][0] = new Array(1,0,1,0,1,0,0,1,1,0,1,1)
maze[2][1] = new Array(0,0,0,0,1,1,1,0,0,0,0,1)
maze[3][0] = new Array(0,1,1,1,1,1,0,0,0,0,1,1)
maze[3][1] = new Array(1,0,0,1,0,0,0,1,1,0,0,1)
maze[4][0] = new Array(0,0,0,0,0,0,1,1,1,1,1,1)
maze[4][1] = new Array(1,1,1,1,1,0,0,0,0,0,1,1)
maze[5][0] = new Array(0,0,0,0,1,0,1,1,1,1,0,0)
maze[5][1] = new Array(1,1,1,1,1,1,0,0,0,1,0,1)
maze[6][0] = new Array(0,0,0,0,0,0,1,1,0,1,0,1)
maze[6][1] = new Array(1,1,1,1,1,1,0,0,0,1,0,1)
maze[7][0] = new Array(1,0,1,0,0,0,1,0,1,1,0,1)
maze[7][1] = new Array(1,1,1,0,1,0,0,1,0,1,1,1)
maze[8][0] = new Array(0,0,0,1,0,0,1,1,0,0,0,0)
maze[8][1] = new Array(0,1,0,1,1,0,0,0,1,1,0,1)
maze[9][0] = new Array(0,0,0,0,0,1,1,1,1,0,1,1)
maze[9][1] = new Array(1,1,1,1,0,0,0,0,0,1,1,1)
maze[10][0] = new Array(0,0,0,0,0,1,1,1,1,1,0,0)
maze[10][1] = new Array(1,1,1,0,1,0,0,0,0,1,0,1)
maze[11][0] = new Array(0,0,1,1,1,1,1,1,1,0,0,0)
maze[11][1] = new Array(1,0,1,0,0,0,0,0,0,0,1,1)
maze[12][0] = new Array(0,0,0,0,0,1,1,1,1,0,1,0)
maze[12][1] = new Array(1,1,0,1,0,0,0,1,0,0,1,1)
function testNext(nxt) {
if ((board.rows[start.rows].cells[start.cols].style.backgroundColor=="yellow") && (nxt.style.backgroundColor==&#39;yellow&#39;)) {
message.innerText="I see you changed your mind."
board.rows[start.rows].cells[start.cols].style.backgroundColor=""
return false
}
return true
}
function moveIt() {
if (!progress) return
switch (event.keyCode) {
case 37: // left
if (maze[start.rows][1][start.cols-1]==0) {
if (testNext(board.rows[start.rows].cells[start.cols-1]))
message.innerText="Going west..."
start.cols--
document.all.board.rows[start.rows].cells[start.cols].style.backgroundColor="yellow"
} else
message.innerText="Ouch... you can&#39;t go west."
break;
case 38: // up
if (maze[start.rows][0][start.cols]==0) {
if (testNext(board.rows[start.rows-1].cells[start.cols]))
message.innerText="Going north..."
start.rows--
document.all.board.rows[start.rows].cells[start.cols].style.backgroundColor="yellow"
} else
message.innerText="Ouch... you can&#39;t go north."
break;
case 39: // right
if (maze[start.rows][1][start.cols]==0) {
if (testNext(board.rows[start.rows].cells[start.cols+1]))
message.innerText="Going east..."
start.cols++
document.all.board.rows[start.rows].cells[start.cols].style.backgroundColor="yellow"
}
else
message.innerText="Ouch... you can&#39;t go east."
break;
case 40: //down
if (maze[start.rows+1]==null) return
if (maze[start.rows+1][0][start.cols]==0) {
if (testNext(board.rows[start.rows+1].cells[start.cols]))
message.innerText="Going south..."
start.rows++
document.all.board.rows[start.rows].cells[start.cols].style.backgroundColor="yellow"
} else
message.innerText="Ouch... you can&#39;t go south."
break;
}
if (document.all.board.rows[start.rows].cells[start.cols].innerText=="end") {
message.innerText="You Win!"
progress=false
}
}
</SCRIPT>
<P ALIGN=center>请使用键盘上的→←↑↓键进行游戏</P><BR>
<p><TABLE ID=board ALIGN=CENTER CELLSPACING=0 CELLPADDING=0>
<SCRIPT LANGUAGE="JavaScript">
for (var row = 0; row<maze.length; row++) {
document.write("<TR>")
for (var col = 0; col<maze[row][0].length; col++) {
document.write("<TD STYLE=&#39;")
for (var cell = 0; cell<2; cell++) {
if (maze[row][cell][col]==1)
document.write(sides[cell]+": 2px black solid;")
}
if ((0==col) && (0!=row))
document.write("border-left: 2px black solid;")
if (row==maze.length-1)
document.write("border-bottom: 2px black solid;")
if ((0==row) && (0==col))
document.write(" background-color:yellow;&#39; class=start>start</TD>")
else
if ((row==maze.length-1) && (col==maze[row][0].length-1))
document.write("&#39; class=end>end</TD>")
else
document.write("&#39;> </TD>")
}
document.write("</TR>")
}
var start = new Object
start.rows = 0
start.cols = 0
progress=true
document.onkeydown = moveIt;
</SCRIPT>
</TABLE>
<P ID="message"> </P>
<br />
</body>
</html>
登录后复制

以上就是JavaScript小游戏之迷宫小游戏的实例的详细内容,更多请关注php中文网其它相关文章!

Java小游戏实战开发——贪吃蛇小游戏

Java小游戏实战开发——贪吃蛇小游戏

Java小游戏实战开发——贪吃蛇网络游戏 1、Direction类

Direction:用于存放上下左右四个键。
package com.games;

/*
 *枚举:就是几个固定的常量
 */
public enum  Direction{
    UP,DOWN,LEFT,RIGHT
 }

2、Snake类

Snake,蛇类:一条蛇有多个节点,使用LinkedList集合出储存Node节点
初始化蛇身体,蛇出生地有6个节点
package com.games;

import java.util.LinkedList;

/**
 *Snake类表示蛇
 * 一条蛇有多个节点,使用LinkedList集合存储Node节点
 * 蛇出生的地方有6个节点
 */
public class Snake {
    //蛇的身体
    private LinkedList<Node> body;
    //蛇的运动方向
    private Direction direction = Direction.LEFT;
    //蛇是否活着
    private boolean isLiving = true;

    //构造方法,在创造Snake对象时执行
    public Snake(){
        //初始化蛇身体
        initSnake();
    }

    //初始化蛇身体
    private void initSnake(){
        //创建集合
        body= new LinkedList<>();
        //创建6个节点放在集合中
        body.add(new Node(16,20));
        body.add(new Node(17,20));
        body.add(new Node(18,20));
        body.add(new Node(19,20));
        body.add(new Node(20,20));
        body.add(new Node(21,20));
    }

    //蛇会沿着蛇头的方向移动
    //控制蛇移动:在蛇头的运动方向添加一个节点,然后把蛇尾的最后一个节点删除
    public void move(){
        if(isLiving) {

            //获取蛇头
            Node head = body.getFirst();
            switch (direction) {
                case UP:
                    //在蛇头上边头添加节点
                    body.addFirst(new Node(head.getX(), head.getY() - 1));
                    break;
                case DOWN:
                    body.addFirst(new Node(head.getX(), head.getY() + 1));
                    break;
                case LEFT:
                    body.addFirst(new Node(head.getX() - 1, head.getY()));
                    break;
                case RIGHT:
                    body.addFirst(new Node(head.getX() + 1, head.getY()));
                    break;
            }

            //删除蛇尾的最后节点
            body.removeLast();

            //判断蛇是否撞墙
            head = body.getFirst();
            if(head.getX() < 0 || head.getY() < 0 || head.getX() >= 40 || head.getY() >= 40){
                isLiving = false;
            }

            //判断蛇是否碰到自己的身体
            for(int i = 1; i < body.size(); i++){
                Node node = body.get(i);
                if(head.getX() == node.getX() && head.getY() == node.getY()){
                    isLiving = false;
                }
            }


        }
    }



    public LinkedList<Node> getBody() {
        return body;
    }

    public void setBody(LinkedList<Node> body) {
        this.body = body;
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    //吃食物;沿着蛇头的移动方向添加一个节点
    public void eat(Node food){
        //获取蛇头
        Node head = body.getFirst();
        switch (direction) {
            case UP:
                //在蛇头上边头添加节点
                body.addFirst(new Node(head.getX(), head.getY() - 1));
                break;
            case DOWN:
                body.addFirst(new Node(head.getX(), head.getY() + 1));
                break;
            case LEFT:
                body.addFirst(new Node(head.getX() - 1, head.getY()));
                break;
            case RIGHT:
                body.addFirst(new Node(head.getX() + 1, head.getY()));
                break;
        }
    }
}

3、Node类

节点类:每一条蛇是由若干个节点组成的,每一个节点有横纵坐标来确定位置
package com.games;

import java.util.Random;

/**
 *节点类:每一条蛇是由若干个节点组成的,每一个节点有横纵坐标来确定位置
 */
public class Node {
    private int x;
    private int y;

    public Node(){

    }

    public Node(int x,int y){
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    //随机生成位置
    public void random(){
        //创建Random对象
        Random r = new Random();
        //随机生成横坐标
        this.x = r.nextInt(40);
        //随机生成纵坐标
        this.y = r.nextInt(40);
    }
}

4、MainFrame类
实现:
(1)initFrame()方法:初始化窗体参数;设置窗体宽高、窗体默认位置、关闭按钮的作用和窗体大小不可变。
(2)initGamePanel()方法:继承JPanel()类,重写paint()方法,初始化游戏棋盘,在paint()方法中绘制棋盘中的内容,即清空棋盘、绘制横竖线条、绘制蛇和食物,最后把棋盘添加到窗体中。
(3)initSnake()方法:初始化蛇;创建Snake类,在Snake类中初始化蛇的初始位置、构造move()方法和eat()方法。move()方法实现蛇沿着蛇头方向移动、判断蛇是否撞墙和碰到自己身体的功能;eat()方法实现当食物与蛇头重合,会沿蛇头的移动方向添加一个节点。。
(4)initFood()方法:初始化食物;创建Node类,在Node类中用随机数实现食物位置的随机生成。
(5)initTimer()方法:初始化定时器;设置定时任务,根据游戏状态和direction变量设置蛇移动操作,进行食物判定,判断食物与蛇头是否重合,如果重合调用eat()方法并再次随机生成食物。使用定时器,调用repaint()方法实时更新界面。
(6)setKeyListener()方法:设置键盘监听,当键盘按下时,调用keyPressed(KeyEvent e)方法,获取键盘输入,根据键盘输入让蛇随着Direction方向移动。
代码如下:

package com.games;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.LinkedList;
import java.util.TimerTask;

public class MainFrame extends JFrame {
    //蛇
    private Snake snake;
    //游戏棋盘
    private JPanel jPanel;
    //定时器,在规定时间内调用蛇移动的方法
    private Timer timer;
    //食物
    private Node food;

    public MainFrame() throws HeadlessException {
        //初始化窗体参数
        initFrame();
        //初始化游戏棋盘
        initGamePanel();
        //初始化蛇
        initSnake();
        //初始化食物
        initFood();
        //初始化定时器
        initTimer();
        //设置键盘监听,让蛇随着上下左右方向移动
        setKeyListener();
    }

    private void initFood(){
        food = new Node();
        food.random();
    }

    private void setKeyListener(){
        addKeyListener(new KeyAdapter() {
            //当键盘按下时,会自动调用此方法
            @Override
            public void keyPressed(KeyEvent e) {
                //键盘中的每一个键都有一个自己的编号
                switch (e.getKeyCode()){
                    case KeyEvent.VK_UP://上键
                        if(snake.getDirection() != Direction.DOWN){
                            //修改蛇的运动方向
                            snake.setDirection(Direction.UP);
                        }
                        break;
                    case KeyEvent.VK_DOWN://下键
                        if(snake.getDirection() != Direction.UP){
                            snake.setDirection(Direction.DOWN);
                        }
                        break;
                    case KeyEvent.VK_LEFT://左键
                        if(snake.getDirection() != Direction.RIGHT){
                            snake.setDirection(Direction.LEFT);
                        }
                        break;
                    case KeyEvent.VK_RIGHT://右键
                        if(snake.getDirection() != Direction.LEFT){
                            snake.setDirection(Direction.RIGHT);
                        }
                        break;
                }
            }
        });
    }

    private void initTimer(){
        timer = new Timer();

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                snake.move();
                //判断食物与蛇头是否重合
                Node head = snake.getBody().getFirst();
                if(head.getX() == food.getX() && head.getY() == food.getY()){
                    snake.eat(food);
                    food.random();
                }
                //重绘游戏棋盘
                jPanel.repaint();
            }
        };

        //每100毫秒,执行一次定时任务
        //蛇的移动速度,如果想改变移动速度,改变最后一个参数即可
        timer.scheduleAtFixedRate(timerTask,0,200);
    }

    private void initSnake(){
        snake = new Snake();
    }

    public void initGamePanel(){
         jPanel = new JPanel(){

            //绘制棋盘中的内容
            public void paint(Graphics g){
                //清空棋盘
                g.clearRect(0,0,600,600);

                //Graphics g    可以看做是一个画笔,提供了很多方法可以来绘制一些基本图形(直线、矩形)
                //绘制40条横线
                for(int i = 0;i <= 40; i++){
                    g.drawLine(0,i*15,600,i*15);
                }

                //绘制40条竖线
                for(int i = 0; i <= 40; i++){
                    g.drawLine(i*15,0,i*15,600);
                }

                //绘制蛇
                LinkedList<Node> body = snake.getBody();
                for(Node node : body){
                    g.fillRect(node.getX()*15,node.getY()*15,15,15);
                }

                //绘制食物
                g.fillRect(food.getX()*15,food.getY()*15,15,15);

            }

        };

        //把棋盘添加到窗体中
        add(jPanel);

    }

    //初始化窗体参数
    public void initFrame(){
        //设置窗体宽高
        setSize(610,640);
        //设置窗体默认位置
        setLocation(408,408);
        //设置关闭按钮的作用
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置窗体大小不可变
        setResizable(false);
    }

    public static void main(String[] args) {
        //创建窗体对象,并显示
        new MainFrame().setVisible(true);
    }
}

关于js 翻牌小游戏js翻牌小游戏的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于construct2制作小游戏——捉老鼠小游戏、FinClip 支持小游戏能力,可上架小游戏到任何App、JavaScript小游戏之迷宫小游戏的实例、Java小游戏实战开发——贪吃蛇小游戏的相关知识,请在本站寻找。

本文标签: