java-swing贪吃蛇游戏

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);
    }
}

 

效果:

 

posted @ 2024-09-02 13:41  河北大学-徐小波  阅读(8)  评论(0编辑  收藏  举报