首页 > 编程语言 >java-swing贪吃蛇游戏

java-swing贪吃蛇游戏

时间:2024-09-02 13:50:09浏览次数:8  
标签:java int MyRect width 贪吃蛇 swing new public

MyRect.java

package Main;

public class MyRect {
	public int x = 0;
	public int y = 0;
	public MyRgb rgb = new MyRgb();
	long createtime = 0;
	
	public MyRect() {
		
	}
	public MyRect(int mx, int my, MyRgb myrgb, long time) {
		x = mx;
		y = my;
		rgb = myrgb;
		createtime = time;
	}
}

MyRgb.java

package Main;

public class MyRgb {
    public int r = 0;
    public int g = 0;
    public int b = 0;
    
    public MyRgb() {
        
    }
    public MyRgb(int mr, int mg, int mb) {
        r = mr;
        g = mg;
        b = mb;
    }
}

TanchisheTest.java

package Main;

import java.awt.*;
import javax.swing.*;

import java.awt.image.BufferedImage;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics2D;

import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import java.awt.im.InputContext;

import java.util.Random;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Locale;

import Main.MyRgb;
import Main.MyRect;
import java.util.Date;
import java.util.Collections;

public class TanchisheTest extends JPanel {
    int lineMaxNum = 25;
    int fieldMaxNum = 25;
    int keyoffsetx = randInt(0, fieldMaxNum);
    int keyoffsety = randInt(0, lineMaxNum);
    ArrayList<MyRect> elseRectList = new ArrayList<MyRect>();
    ArrayList<MyRect> snakeList = new ArrayList<MyRect>();
    int score = 0;
    String towars = "";
    
    public long getUnixtime() {
        Date now = new Date();
        long unixTime = now.getTime() / 1000; // 将毫秒转换为秒
        
        return unixTime;
    }
    
    public int randInt(int min, int max) {
        Random rand1 = new Random();
        int randomNum = rand1.nextInt((max - min) + 1) + min;
        return randomNum;
    }
    
    public Color getColorWithRgbs(MyRgb rgbs) {
        return new Color(rgbs.r, rgbs.g, rgbs.b);
    }
    
    public void keyPressed(String key) {
        //System.out.println("keyPressed: " + key);
        if(snakeList.size() <= 0) {
            MyRgb myrgb1 = new MyRgb(255, 0, 0);
            MyRect myrect1 = new MyRect(keyoffsetx, keyoffsety, myrgb1, 0);
            snakeList.add(myrect1);
        }
        
        ArrayList<MyRect> snakeListold = new ArrayList<MyRect>();
        for(MyRect snake1:snakeList) {
            MyRect tmpRect = new MyRect();
            tmpRect.x = snake1.x;
            tmpRect.y = snake1.y;
            tmpRect.rgb = snake1.rgb;
            snakeListold.add(tmpRect);
        }
        
        MyRect firstRect = snakeList.get(0);
        
        if(key.equals("A")) {
            keyoffsetx -= 1;
        }
        if(key.equals("D")) {
            keyoffsetx += 1;
        }
        if(key.equals("W")) {
            keyoffsety -= 1;
        }
        if(key.equals("S")) {
            keyoffsety += 1;
        }
        
        if(keyoffsetx < 0) {
            keyoffsetx = 0;
        }
        if(keyoffsetx > fieldMaxNum-1) {
            keyoffsetx = fieldMaxNum-1;
        }
        if(keyoffsety < 0) {
            keyoffsety = 0;
        }
        if(keyoffsety > lineMaxNum-1) {
            keyoffsety = lineMaxNum-1;
        }
        
        //处理碰撞到的随机块
        int pengpeng = 0;
        for(int i = 0; i < elseRectList.size(); i++) {
            MyRect elseRect = elseRectList.get(i);
            if(elseRect.x == keyoffsetx && elseRect.y == keyoffsety) {
                pengpeng = 1;
                ArrayList<MyRect> tmps = new ArrayList<MyRect>();
                
                MyRect tmpRect1 = new MyRect();
                tmpRect1.x = elseRect.x;
                tmpRect1.y = elseRect.y;
                tmpRect1.rgb = elseRect.rgb;
                tmps.add(tmpRect1);
                
                for(int j = 0; j < snakeListold.size(); j++) {
                    MyRect tmp2 = snakeListold.get(j);
                    MyRect tmpRect2 = new MyRect();
                    tmpRect2.x = tmp2.x;
                    tmpRect2.y = tmp2.y;
                    tmpRect2.rgb = tmp2.rgb;
                    tmps.add(tmpRect2);
                }
                
                snakeList = tmps;
                elseRectList.remove(i);
                score++;
            }
        }
        
        if(pengpeng == 0) {
            ArrayList<MyRect> tmps = new ArrayList<MyRect>();
            for(int j = 0; j < snakeListold.size(); j++) {
                if(j == 0) {
                    MyRect tmp2 = snakeListold.get(j);
                    MyRect tmpRect2 = new MyRect();
                    
                    tmpRect2.x = keyoffsetx;
                    tmpRect2.y = keyoffsety;
                    tmpRect2.rgb = tmp2.rgb;
                    tmps.add(tmpRect2);
                } else {
                    MyRect tmp1 = snakeListold.get(j-1);
                    MyRect tmp2 = snakeListold.get(j);
                    MyRect tmpRect2 = new MyRect();
                    
                    tmpRect2.x = tmp1.x;
                    tmpRect2.y = tmp1.y;
                    tmpRect2.rgb = tmp2.rgb;
                    tmps.add(tmpRect2);
                }
            }
            snakeList = tmps;
        }
        
        this.updateUI();
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        int panel_width = getWidth();
        int panel_height = getHeight();
        System.out.println("画布宽度:"+panel_width);
        System.out.println("画布高度:"+panel_height);
        System.out.println();
        
        if(snakeList.size() <= 0) {
            MyRgb myrgb1 = new MyRgb(255, 0, 0);
            MyRect myrect1 = new MyRect(keyoffsetx, keyoffsety, myrgb1, 0);
            snakeList.add(myrect1);
        }
        
        //清除指定矩形区域的像素
        //void clearRect(int x, int y, int width, int height)
        //g.clearRect(0, 0, panel_width, panel_height);
        
        //设置画板背景颜色
        setBackground(new Color(128, 0, 128));
        
        double left_width = (double)panel_height;
        double left_height = (double)panel_height;
        double right_width = (double)(panel_width - panel_height);
        double right_height = (double)panel_height;
        
        //左边背景
        g.setColor(new Color(245,245,220));
        g.fillRect(0, 0, (int)left_width, (int)left_height);
        
        //右边背景
        g.setColor(new Color(255,239,213));
        g.fillRect((int)left_width, 0, (int)right_width, (int)right_height);
        
        double border_width = 3;
        
        //左边不包含边框的背景
        g.setColor(new Color(255,218,185));
        g.fillRect((int)border_width, (int)border_width, (int)(left_width-2*border_width), (int)(left_height-2*border_width));
        

        double perLine = (left_height - 2 * border_width) / lineMaxNum;
        double perField = (left_width - 2 * border_width) / fieldMaxNum;
        
        //横线
        for(int i = 0; i <= lineMaxNum; i++) {
            g.setColor(new Color(0,0,0));
            g.drawLine((int)border_width, (int)(border_width+i*perLine), (int)(left_width-border_width), (int)(border_width+i*perLine));
        }
        
        //竖线
        for(int i = 0; i <= fieldMaxNum; i++) {
            g.setColor(new Color(0,0,0));
            g.drawLine((int)(border_width+i*perField), (int)border_width, (int)(border_width+i*perField), (int)(left_height-border_width));
        }
        
        //删除超时随机块
        for(int i = 0; i < elseRectList.size(); i++) {
            if(getUnixtime() - elseRectList.get(i).createtime > 60) {
                elseRectList.remove(i);
            }
        }
        
        //保证随机块数量
        while(elseRectList.size() < 3) {
            MyRgb myrgb1 = new MyRgb(randInt(1,255), randInt(1,255), randInt(1,255));
            MyRect myrect1 = new MyRect(randInt(0, fieldMaxNum-1), randInt(0, lineMaxNum-1), myrgb1, getUnixtime());
            elseRectList.add(myrect1);
        }
        
        //展示随机块
        for(MyRect myrect1:elseRectList) {
            g.setColor(getColorWithRgbs(myrect1.rgb));
            g.fillRect((int)(border_width+myrect1.x*perField+2), (int)(border_width+myrect1.y*perLine+2), (int)(perLine-2), (int)(perField-2));
        }
        
        //展示指挥块
        for(MyRect myrect1:snakeList) {
            //System.out.println(myrect1.x+","+myrect1.y);
            g.setColor(getColorWithRgbs(myrect1.rgb));
            g.fillRect((int)(border_width+myrect1.x*perField+2), (int)(border_width+myrect1.y*perLine+2), (int)(perLine-2), (int)(perField-2));
        }
        System.out.println();
        
        //展示分数
        g.setColor(new Color(205,149,12));
        g.fillRect((int)(left_width+right_width/3), (int)(border_width), 80, 25);
        g.setColor(new Color(47,79,79));
        g.drawString("得分:"+String.valueOf(score), (int)(left_width+right_width/3+20), 20);
    }
    
    private static void createAndShowGUI() {
        // 获取屏幕分辨率
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        
        double percent = 0.8;
        int screen_width = screenSize.width;
        int screen_height = screenSize.height;
        System.out.println("屏幕宽度:"+screen_width);
        System.out.println("屏幕高度:"+screen_height);
        System.out.println();
        
        int window_width = (int)(screen_width * percent);
        window_width = (int)(window_width * 0.75);
        int window_height = (int)(screen_height * percent);
        System.out.println("窗体宽度:"+window_width);
        System.out.println("窗体高度:"+window_height);
        System.out.println();
        
        JFrame frame = new JFrame("贪吃蛇");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation((screen_width-window_width)/2, (screen_height-window_height)/2);
        frame.setSize(window_width, window_height);
        
        TanchisheTest gtPanel = new TanchisheTest();

        
        // 注册键盘监听器
        frame.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.isAltDown()) {
                    System.out.println("alt"+"键被按下了");
                } else if(e.isShiftDown()) {
                    System.out.println("Shift"+"键被按下了");
                } else if(e.isControlDown()) {
                    System.out.println("Control"+"键被按下了");
                } else {
                    boolean flag = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);
                    //键入某个键时调用此方法
                    if(flag) {
                        //System.out.println("现在是大写键状态");
                    }
                    else {
                        //System.out.println("现在是小写键状态");
                    }
                    char ch = e.getKeyChar();
                    //System.out.println("输入的字符是"+ch);
                }
            }
 
            @Override
            public void keyPressed(KeyEvent e) {
                //按下某个键时调用此方法
                //System.out.println("Key pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
                gtPanel.keyPressed(KeyEvent.getKeyText(e.getKeyCode()));
            }
 
            @Override
            public void keyReleased(KeyEvent e) {
                //释放某个键时调用此方法
                //System.out.println("Key Released: " + KeyEvent.getKeyText(e.getKeyCode()));
                //System.out.println();
            }
        });

        frame.add(gtPanel);
        frame.setVisible(true);
    }
    
    public static void main(String[] args) {
        //设置输入法
        Locale locale = new Locale("en", "US");
        InputContext context = InputContext.getInstance();
        context.selectInputMethod(locale);
        
        SwingUtilities.invokeLater(TanchisheTest::createAndShowGUI);
    }
}

 

效果:

 

标签:java,int,MyRect,width,贪吃蛇,swing,new,public
From: https://www.cnblogs.com/xuxiaobo/p/18392543

相关文章

  • java~重写hashcode和equals
    单字段和多字段重写hashcode在Java中,重写hashCode方法的场景通常与对象的哈希值计算有关,特别是在使用哈希表(如HashMap,HashSet等)时。下面是你提供的两种hashCode实现的具体使用场景分析:1.第一种实现@Overridepublicbooleanequals(Objecto){if(this==o)......
  • java-swing画图
    MyRect.javapackageMain;publicclassMyRect{ publicintx=0; publicinty=0; publicMyRgbrgb=newMyRgb(); longcreatetime=0; publicMyRect(){ } publicMyRect(intmx,intmy,MyRgbmyrgb,longtime){ x=mx; y=my; rgb=......
  • Java中的堆
    Java中的堆一、引言在Java中,堆是一种重要的数据结构,它通常表现为一个完全二叉树,具有一些特定的性质。堆可以是最大堆或最小堆,其中最大堆的每个节点的值都不小于其子节点,而最小堆的每个节点的值都不大于其子节点。堆在很多算法中都有应用,比如堆排序、优先队列等。本文将详......
  • Java中BigInteger类的使用
    Java中BigInteger类的使用一、引言在Java编程语言中,处理大整数是一个常见的需求,尤其是在加密、科学计算和金融领域。Java提供了BigInteger类来处理任意精度的整数运算,这使得程序员可以轻松地处理超出基本数据类型范围的数值。本文将详细介绍BigInteger类的使用,包括其构造......
  • java计算机毕业设计家具销售电商平台(开题+程序+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景:随着互联网技术的飞速发展,电子商务已成为现代商业活动不可或缺的一部分,深刻改变了人们的消费习惯。在家具市场,传统销售模式受限于地域、时间等因素,难......
  • java计算机毕业设计家庭装修套餐消费管理(开题+程序+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景随着人们生活水平的提高和居住需求的多样化,家庭装修已成为现代家庭不可或缺的重要环节。然而,传统家庭装修过程中存在信息不对称、流程繁琐、管理效率......
  • java计算机毕业设计老来福平台(开题+程序+论文)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景:随着社会的快速老龄化,老年人口比例持续上升,如何高效、人性化地管理老年人的生活与健康成为亟待解决的社会问题。老来福平台应运而生,旨在通过信息化手......
  • 无法在 Postman 中使用 JavaScript 访问发送的信息
    Postman是一个用于测试API的工具,它本身并不支持在请求中直接执行JavaScript代码。Postman主要用于发送HTTP请求并查看响应。如果你需要在发送请求时执行一些自定义的逻辑或处理请求数据,你可以考虑以下几种方法:使用Postman的预请求脚本(Pre-requestScript)或测试脚本(TestS......
  • 179java jsp SSM Springboot基于javaweb的流浪宠物管理系统流浪动物求助宠物领养管理(
    项目技术:Springboot+Maven+Vue等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个平台上运行的。其他版本理论上也可以。2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;3.tomcat环境:Tomcat7.x,8.x,9.x版本均可4.硬件环境:windows......
  • Java基于微信小程序的美食推荐小程序,附源码
    博主介绍:✌Java徐师兄、7年大厂程序员经历。全网粉丝13w+、csdn博客专家、掘金/华为云等平台优质作者、专注于Java技术领域和毕业项目实战✌......