java 贪吃蛇,类之间的调用

想把MyFrame里面的菜单、键盘监听、事件监听、绘制界面分离出来 各自形成一个类 ,
但是弄了好久也没有做出来,所以请教各位大神们,怎么讲这些分解出来。谢谢了~!~
(由于没有C币了 , 所以。。。抱歉了)

 package zeng;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

public class MyFrame extends KeyAdapter implements ActionListener{
    JFrame frame ;
    Canvas canvas;
    Container container;
    JLabel label;           // 计分
    Snake snake = null;     // 蛇

    public static final int DEFAULT_WIDTH = 800;    // 界面宽
    public static final int DEFAULT_HEIGHT = 600;   // 界面高
    public static final int nodeWidth = 10;         // 结点宽
    public static final int nodeHeight = 10;        // 结点高

    JMenuItem start = new JMenuItem("开始");
    JMenuItem exit = new JMenuItem("退出");
    JMenuItem paused = new JMenuItem("暂停/开始");
    JMenuItem speedUp = new JMenuItem("加速");
    JMenuItem speedDown = new JMenuItem("减速");
    JMenuItem about = new JMenuItem("关于贪吃蛇");

    JMenuBar menuBar;
    JMenu file;
    JMenu function;
    JMenu help;

    // 初始化游戏界面
    public MyFrame()
    {   
        // 设置界面
        frame = new JFrame();
        frame.setTitle("贪吃蛇");
        frame.setLocation(200,200);

        container = frame.getContentPane();

        label = new JLabel("分数:", JLabel.CENTER);
        container.add(label, BorderLayout.SOUTH);

        canvas = new Canvas();
        canvas.setSize(DEFAULT_WIDTH-20, DEFAULT_HEIGHT-20);
        container.add(canvas, BorderLayout.CENTER);

        menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        file = new JMenu("文件");
        function = new JMenu("功能");
        help = new JMenu("帮助");

        file.add(start);
        start.addActionListener(this);
        file.add(exit);
        exit.addActionListener(this);

        function.add(paused);
        paused.addActionListener(this);
        function.add(speedUp);
        speedUp.addActionListener(this);
        function.add(speedDown);
        speedDown.addActionListener(this);

        help.add(about);
        about.addActionListener(this);

        menuBar.add(file);
        menuBar.add(function);
        menuBar.add(help);

        frame.addKeyListener(this);
        frame.pack();
        frame.setResizable(false);                              // 窗口大小不能变化
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   // 窗口关闭方式
        frame.setVisible(true);                                 // 显示
        begin();                    // 开始游戏
    }

    // 绘制游戏界面(包括蛇和食物)
    public void repaint(){
        Graphics g = canvas.getGraphics();
        // 背景
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        // 蛇
        g.setColor(Color.BLACK);
        LinkedList<Node> snakeNode = snake.nodeArray;
        Iterator<Node> it = snakeNode.iterator();
        while (it.hasNext()) {
            Node n = (Node) it.next();
            drawNode(g, n);
        }
        // 食物
        g.setColor(Color.RED);
        Node n = snake.food;
        drawNode(g, n);
        updateScore();
    }
    // 绘画某一结点(蛇身或食物)
    private void drawNode(Graphics g, Node n) {
        g.fillRect(n.x * nodeWidth, n.y * nodeHeight, nodeWidth - 1, nodeHeight - 1);
    }
    // 更新分数
    public void updateScore() {
        String s = "分数:" + snake.score;
        label.setText(s);
    }
    // 游戏开始,放蛇
    void begin() {
        if (snake == null || !snake.running) {
            snake = new Snake(this, DEFAULT_WIDTH / nodeWidth, DEFAULT_HEIGHT / nodeHeight);
            (new Thread(snake)).start();
        }
    }
    // 菜单监听事件
    @Override
    public void actionPerformed(ActionEvent e){
        if(snake.running){
            if(e.getSource() == start){         // 开始
                snake.running = false;
                begin();
            }
            else if(e.getSource() == exit){     // 退出
                int select=JOptionPane.showConfirmDialog(null, "确认退出", "提示", 
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
                if(select==JOptionPane.OK_OPTION){
                    System.exit(0);
                }
            }   
            else if(e.getSource() == paused){   // 暂停/继续
                snake.changePauseState();
            }
            else if(e.getSource() == speedUp){  // 加速
                snake.speedUp();
            }
            else if(e.getSource() == speedDown){// 减速
                snake.speedDown();
            }
            else if(e.getSource() == about){    // 关于贪吃蛇
                JOptionPane.showMessageDialog(null, "贪吃蛇\n"+"制作人:小曾      计本1501\n"
                                            +"    按上下左右键控制蛇的方向\n"
                                            +"    按‘+’或PageUp 加速 、按‘-’或PageDown加速\n"
                                            +"    按空格或p\t暂停/开始");
            }
        }
    }
    // 键盘监听
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (snake.running)
            switch (keyCode) {
            case KeyEvent.VK_UP:                    // 方向键:上
                snake.changeDirection(Snake.UP);
                break;
            case KeyEvent.VK_DOWN:                  // 方向键:下
                snake.changeDirection(Snake.DOWN);
                break;
            case KeyEvent.VK_LEFT:                  // 方向键:左
                snake.changeDirection(Snake.LEFT);
                break;
            case KeyEvent.VK_RIGHT:                 // 方向键:右
                snake.changeDirection(Snake.RIGHT);
                break;
            case KeyEvent.VK_ADD:                   // ‘+’键
            case KeyEvent.VK_PAGE_UP:               // PageUp键
                snake.speedUp();                    // 加速
                break;
            case KeyEvent.VK_SUBTRACT:              // ‘-’键
            case KeyEvent.VK_PAGE_DOWN:             // PageDown键
                snake.speedDown();                  // 减速
                break;
            case KeyEvent.VK_SPACE:                 // 空格键
            case KeyEvent.VK_P:                     // P键
                snake.changePauseState();           // 暂停或继续
                break;
            default:
            }
        // 重新开始(回车键、S键)
        if (keyCode == KeyEvent.VK_S || keyCode == KeyEvent.VK_ENTER) {
            snake.running = false;
            begin();
        }
    }
}

package zeng;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.JOptionPane;

public class Snake implements Runnable{
Node food;
MyFrame myFrame;
LinkedList nodeArray = new LinkedList();

int maxX;
int maxY;
boolean[][] matrix;
int timeInterval = 200;
int score = 0;
boolean running = false;
boolean paused = false;
double speedChangeRate = 0.75;
int direction = 2;
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;

// 初始化界面
public Snake(MyFrame myFrame, int maxX, int maxY){
    this.myFrame = myFrame;
    this.maxX = maxX;
    this.maxY = maxY;
    matrix = new boolean[maxX][];
    for (int i = 0; i < maxX; ++i) {
        matrix[i] = new boolean[maxY];
        Arrays.fill(matrix[i], false);
    }
    int initArrayLength = maxX > 20 ? 10 : maxX / 2;
    for (int i = 0; i < initArrayLength; ++i) {
        int x = maxX / 2 + i;
        int y = maxY / 2;
        nodeArray.addLast(new Node(x, y));
        matrix[x][y] = true;
    }
    food = createFood();
    matrix[food.x][food.y] = true;
}
// 改变方向
public void changeDirection(int newDirection) {

    if (direction % 2 != newDirection % 2) {
        direction = newDirection;
    }
}
// 生成食物和放置位置
private Node createFood() {
    int x = 0;
    int y = 0;
    do {
        Random r = new Random();
        x = r.nextInt(maxX);
        y = r.nextInt(maxY);
    } while (matrix[x][y]);
    return new Node(x, y);
}
// 蛇移动
public boolean moveOn() {
    Node n = (Node) nodeArray.getFirst();
    int x = n.x;
    int y = n.y;
    switch (direction) {
        case UP:
            y--;
            break;
        case DOWN:
            y++;
            break;
        case LEFT:
            x--;
            break;
        case RIGHT:
            x++;
            break;
    }
    if ((0 <= x && x < maxX) && (0 <= y && y < maxY)) {
        if (matrix[x][y]) {                     // 吃到食物或者撞到身体
            if (x == food.x && y == food.y) {   // 吃到食物
                nodeArray.addFirst(food);       // 在头部加上一结点
                score += 10;
                food = createFood();
                matrix[food.x][food.y] = true;
                return true;
            } else
                return false;                   // 撞到身体
        } else {                                // 什么都没有碰到
            nodeArray.addFirst(new Node(x, y)); // 加上头部
            matrix[x][y] = true;
            n = (Node) nodeArray.removeLast();  // 去掉尾部
            matrix[n.x][n.y] = false;
            return true;
        }
    }
    return false;                               // 越界(撞到墙壁)
}
// 蛇运动线程
public void run() {
    running = true;
    while (running) {
        try {
            Thread.sleep(timeInterval);
        } catch (Exception e) {
            break;
        }
        if (!paused) {
            if (moveOn()) {         // 未结束
                myFrame.repaint();
            } else {                // 游戏结束
                JOptionPane.showMessageDialog(null, "GAME OVER", "Game Over", JOptionPane.INFORMATION_MESSAGE);
                break;
            }
        }
    }
    running = false;
}
// 加速
public void speedUp() {
    timeInterval *= speedChangeRate;
}
// 减速
public void speedDown() {
    timeInterval /= speedChangeRate;
}
// 暂停/继续
public void changePauseState() {
    paused = !paused;
}

}

 package zeng;

 public class Node {
    int x;
    int y;

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

package zeng;

public class Main
{
public static void main(String[] args){
new MyFrame();
}
}


1个回答

最近正在学习java哦 哈哈。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
我的Java贪吃蛇代码,为什么蛇不显示?

图片如下: (蓝色的是蛇,黄色的是食物) ![图片1](https://img-ask.csdn.net/upload/201910/15/1571144046_475523.png) ![图片2](https://img-ask.csdn.net/upload/201910/15/1571144080_341225.png) 代码如下: ``` java import java.awt.Color; import java.awt.Container; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; public class SnakeGame extends JFrame{ String snake_dir=""; int snake_x=0; int snake_y=0; int bonus_x=10; int bonus_y=10; int score=1; int index=0; int snake[][]=new int[1024][2]; boolean started=false; boolean lose=false; boolean win=false; public void resetsnake(){ snake_dir=""; score=1; snake_x=0; snake_y=0; bonus_x=0; bonus_y=0; started=false; lose=false; index=0; snake=new int[1024][2]; } public Color color(int r,int g,int b){ Color col = new Color(r,g,b); return col; } public SnakeGame(String title){ class DrawPanel extends JPanel{ public void update_screen(Graphics g){ super.paint(g); g.setColor(color(0,0,0)); g.fillRect(0,0,900,600); g.setColor(color(255,255,0)); g.fillRect(bonus_x*20, bonus_y*20, 20, 20); g.setColor(color(0,0,255)); for(int i=0;i<=score;i++){ g.fillRect(snake[i][0]*20, snake[i][1]*20, 20, 20); } } } class MultiThread extends Thread{ public void run(){ while(started==true){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } switch(snake_dir){ case "up": snake_y--; break; case "down": snake_y++; break; case "left": snake_x--; break; case "right": snake_x++; break; } if(snake_x<0){ snake_x=0; snake_dir=""; } if(snake_x>44){ snake_x=44; snake_dir=""; } if(snake_y<0){ snake_y=0; snake_dir=""; } if(snake_y>29){ snake_y=29; snake_dir=""; } for(int i=0;i<score-1;i++){ snake[i]=snake[i+1]; } snake[score-1][0]=snake_x; snake[score-1][1]=snake_y; if(snake_x==bonus_x && snake_y==bonus_y){ bonus_x=(int)(Math.random()*45); bonus_y=(int)(Math.random()*30); score++; if(score==1024){ started=false; win=true; } } new DrawPanel().update_screen(getGraphics()); } } } addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent e){ int keyCode=e.getKeyCode(); if(started==true){ switch(keyCode){ case KeyEvent.VK_UP: snake_dir="up"; break; case KeyEvent.VK_DOWN: snake_dir="down"; break; case KeyEvent.VK_LEFT: snake_dir="left"; break; case KeyEvent.VK_RIGHT: snake_dir="right"; break; } }else if(started==false && lose==true){ lose=false; }else if(started==false && lose==false){ started=true; new MultiThread().start(); } } @Override public void keyReleased(KeyEvent e) {} @Override public void keyTyped(KeyEvent e) {} }); setTitle(title); setSize(900,600); setResizable(false); setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } public static void main(String[] args){ new SnakeGame("Java贪吃蛇"); } } ```

java贪吃蛇怎样设置向左时不能向右

package moonsake; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class MPanel extends JPanel implements KeyListener/*实现接口KeyListener开始监听键盘输入*/ ,ActionListener{ private ImageIcon title = new ImageIcon("title.jpg"); private ImageIcon right = new ImageIcon("right.png"); private ImageIcon body = new ImageIcon("body.png"); private ImageIcon down = new ImageIcon("down.png"); private ImageIcon left = new ImageIcon("left.png"); private ImageIcon up = new ImageIcon("up.png"); private ImageIcon food = new ImageIcon("food.png"); int len = 3;//长度 int score = 0;//分数 private static int speed =150; int[] snakex = new int[750]; int[] snakey = new int[750]; String fx = "R"; //反向R, L, U, D boolean isStared = false;//暂停字体 boolean isEnd = false;//结束 boolean flag = false; Timer timer = new Timer( speed,this); int foodx; int foody; Random rand = new Random(); public MPanel(){ initsnake(); //设置焦点为自己 this.setFocusable(true); //设置自己为键盘监听对象 this.addKeyListener(this); timer.start(); foodx = 25 + 25*rand.nextInt(34); foody = 75 + 25*rand.nextInt(24); } public void initsnake() { len = 3; snakex[0] = 100; snakey[0] = 100; snakex[1] = 75; snakey[1] = 100; snakex[2] = 50; snakey[2] = 100; fx = "R"; score = 0; } public void paintComponent(Graphics g) { super.paintComponent(g); this.setBackground(Color.WHITE); title.paintIcon(this, g, 25, 11); g.fillRect(25,75 , 850, 600); g.drawString("长度:"+len, 750, 35); g.drawString("分数:"+score, 750, 50); //暂停语句 if(isStared == false) { g.setColor(Color.WHITE); g.setFont(new Font("arial",Font.BOLD,40)); g.drawString("Press Space to Start!!!", 225, 300); } //结束语句 if(!isEnd == false) { g.setColor(Color.RED); g.setFont(new Font("arial",Font.BOLD,40)); g.drawString("END: Press Space to Restart!!!", 175, 300); } //画蛇头 switch (fx) { case "R": right.paintIcon(this, g, snakex[0], snakey[0]); break; case "L": left.paintIcon(this, g, snakex[0], snakey[0]); break; case "U": up.paintIcon(this, g, snakex[0], snakey[0]); break; case "D": down.paintIcon(this, g, snakex[0], snakey[0]); break; } //食物 food.paintIcon(this, g, foodx, foody); //循环画出蛇身体 for(int i=1; i<len; i++) { body.paintIcon(this, g, snakex[i], snakey[i]); } } @Override public void keyTyped(KeyEvent e) { } //监听按下空格键 @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode == KeyEvent.VK_SPACE) { if(isEnd) {//重新开始 isEnd = !isEnd; initsnake(); }else { isStared = !isStared; } repaint(); }else if(keyCode == KeyEvent.VK_RIGHT) { fx = "R"; }else if(keyCode == KeyEvent.VK_LEFT) { fx = "L"; }else if(keyCode == KeyEvent.VK_UP) { fx = "U"; }else if(keyCode == KeyEvent.VK_DOWN) { fx = "D"; } } @Override public void keyReleased(KeyEvent e) { } //移动蛇 @Override public void actionPerformed(ActionEvent e) { //实现空格暂停 if(isStared && !isEnd) { //画蛇身体 for(int i=len-1; i>0; i--) { snakex[i] = snakex[i-1]; snakey[i] = snakey[i-1]; } //画蛇头 //实现头的移动 switch (fx) { case "R": snakex[0] = snakex[0] + 25; if(snakex[0] >850) isEnd = !isEnd;//当蛇到边界时,重新开始 break; case "L": snakex[0] = snakex[0] - 25; if(snakex[0] <25) isEnd = !isEnd; break; case "U": snakey[0] = snakey[0] - 25; if(snakey[0] <75) isEnd = !isEnd; break; case "D": snakey[0] = snakey[0] + 25; if(snakey[0] >650) isEnd = !isEnd; break; } //蛇吃食物长大 if(snakex[0] == foodx && snakey[0] == foody) { len++; score +=10; speed -=30; foodx = 25 + 25*rand.nextInt(34); foody = 75 + 25*rand.nextInt(24); } //检测蛇是否重叠 for(int i=1; i<len; i++) { if(snakex[i] == snakex[0] && snakey[i] == snakey[0]) { isEnd = !isEnd; } } repaint(); } timer.start(); } }

求救啊,java贪吃蛇问题(要达到的效果是出现一个蓝色格子在动)

java贪吃蛇问题(要达到的效果是出现一个蓝色格子在动) 第一个类 import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; public class Snake { Node head = null; Node tail = null; int size = 0; Dir dir = Dir.D; Node n = new Node(30, 30, Dir.D); public Snake(){ head = n; tail = n; size = 1; } class Node{ int row, col; Dir dir; Node next = null; Node prev = null; public static final int nodeW = SnakeMain.BLOCK; public static final int nodeH = SnakeMain.BLOCK; Node(int row, int col, Dir dir ){ this.row = row; this.col = col; this.dir = dir; } void draw(Graphics g){ Color c = g.getColor(); g.setColor(Color.BLUE); g.fillRect(SnakeMain.BLOCK * col, SnakeMain.BLOCK * row, nodeW, nodeH); g.setColor(c); } } public void draw(Graphics g){ if(size <= 0) return; for(Node m = head; m != null; m = m.next){ m.draw(g); } move(); } private void move() { addToHead(); deleteFromTail(); } private void deleteFromTail() { if(size == 0) return; tail = tail.prev; tail.next = null; } public void addToTail(){ Node node = null; switch(tail.dir){ case L: node = new Node(tail.row, tail.col + 1, tail.dir); break; case R: node = new Node(tail.row, tail.col - 1, tail.dir); break; case U: node = new Node(tail.row + 1, tail.col, tail.dir); break; case D: node = new Node(tail.row - 1, tail.col, tail.dir); break; } tail.next = node; node.prev = tail; tail = node; size++; } public void addToHead(){ Node node = null; switch(head.dir){ case L: node = new Node(head.row, head.col - 1, head.dir); break; case R: node = new Node(head.row, head.col + 1, head.dir); break; case U: node = new Node(head.row - 1, head.col, head.dir); break; case D: node = new Node(head.row + 1, head.col, head.dir); break; } node.next = head; head.prev = node; head = node; size++; } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); switch(key){ case KeyEvent.VK_UP: head.dir = dir.U; break; case KeyEvent.VK_DOWN: head.dir = dir.D; break; case KeyEvent.VK_LEFT: head.dir = dir.L; break; case KeyEvent.VK_RIGHT: head.dir = dir.R; break; } } } 第二个类 import java.awt.*; import java.awt.event.*; public class SnakeMain extends Frame { public static final int BLOCK = 10; public static final int ROW = 60; public static final int COLS = 60; Snake sn = new Snake(); Image offScreenImage = null; public static void main(String[] args) { SnakeMain sm = new SnakeMain(); sm.launch(); } public void launch(){ setSize(BLOCK * ROW, BLOCK * COLS); setBackground(Color.LIGHT_GRAY); setResizable(false); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); addKeyListener(new KeyMonitor()); setVisible(true); new Thread(new PaintThread()).start(); } public void paint(Graphics g){ Color c = g.getColor(); g.setColor(Color.YELLOW); for(int i = 1; i < ROW; ++i){ g.drawLine(0, i * BLOCK, BLOCK * ROW, i * BLOCK); } for(int j = 1; j < COLS; ++j){ g.drawLine(j * BLOCK, 0, j * BLOCK, BLOCK * COLS); } g.setColor(c); sn.draw(g); } public void update (Graphics g){ if(offScreenImage == null) offScreenImage = this.createImage(BLOCK * ROW, BLOCK * COLS); Graphics gr = offScreenImage.getGraphics(); paint(gr); g.drawImage(offScreenImage, 0, 0, null); } public class PaintThread implements Runnable{ public void run() { while(true){ repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class KeyMonitor extends KeyAdapter{ @Override public void keyPressed(KeyEvent e) { sn.keyPressed(e); } } } 第三个类 public enum Dir { D, U, L, R }

Java写贪吃蛇遇到的食物生成问题

我是用线程方法让蛇和食物动起来的,不过食物和蛇一起写在paint方法里,repaint一次,食物也会随机变换位置,我想通过观察蛇长是否改变来决定是否new一个新对象,但原来的食物位置不知道怎么记录下来,求教,或者其他更好的解决的方法,谢谢。 import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Shell extends Frame { private static final int Width = 900; private static final int Height = 700; private static final int XOffset = 50; private static final int YOffset = 50; private static final int XEnd = 850; private static final int YEnd = 650; public static final int Row = 30; public static final int Col = 40; public static final int Block_Size = 20; public static Food myFood = null; private Node myNode = null; private static Snake mySnake = new Snake(); private static Shell shell = new Shell(); public Shell() { this.setTitle("贪吃蛇"); this.setSize(Width, Height); this.setResizable(false); this.setLocationRelativeTo(null); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); this.addKeyListener(new KeyHandler(mySnake)); //produceFood(); this.setVisible(true); } public void paint(Graphics g) { drawGrid(g); drawFood(g); drawSnake(g); } private void drawGrid(Graphics g) { g.setColor(Color.BLACK); for(int i=0; i<=Row; i++) { g.drawLine(XOffset, Block_Size*i+50, XEnd, Block_Size*i+50); } for(int i=0; i<=Col; i++) { g.drawLine(Block_Size*i+50, YOffset, Block_Size*i+50, YEnd); } } public void drawSnake(Graphics g) { g.setColor(Color.BLACK); for(int i=0; i<mySnake.getLength(); i++) { myNode = mySnake.getNode(i); g.fillRect(myNode.X, myNode.Y, Block_Size, Block_Size); } } private void drawFood(Graphics g) { myFood = new Food(); g.setColor(Color.RED); g.fillRect(myFood.getX(), myFood.getY(), Block_Size, Block_Size); } public Food getFood() { return myFood; } public static Food produceFood() { boolean finished; Food food; do{ finished = true; food =new Food(); for(int i=0; i<mySnake.getLength(); i++) { if(mySnake.getNode(i).X == food.getX() || mySnake.getNode(i).Y == food.getY()) { finished = false; } } } while(!finished); myFood = food; return food; } public static void main(String[] args) { produceFood(); new Updater(shell, mySnake).start(); } } class Updater extends Thread { private Shell shell = null; private Snake snake = null; public Updater(Shell shell, Snake snake) { this.shell = shell; this.snake = snake; } public void run() { while(true) { snake.move(shell); shell.repaint(); try { sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` import java.util.ArrayList; import java.util.List; public class Snake { List<Node> Nodes = null; public Direction direction = null; private Node newNode = null; private Node headNode = null; private Direction nextDirection = null; public Snake() { Nodes = new ArrayList<Node>(); reset(); } public void setDirection(Direction d) { switch(this.direction) { case LEFT : if(d == Direction.RIGHT) return ; break; case RIGHT : if(d == Direction.LEFT) return ; break; case UP : if(d == Direction.DOWN) return ; break; case DOWN : if(d == Direction.UP) return ; break; } nextDirection = d; } public void move(Shell shell) { headNode = Nodes.get(0); this.direction = nextDirection; switch(this.direction) { case LEFT: newNode = new Node(headNode.X-Shell.Block_Size, headNode.Y); break; case RIGHT: newNode = new Node(headNode.X+Shell.Block_Size, headNode.Y); break; case UP: newNode = new Node(headNode.X, headNode.Y-Shell.Block_Size); break; case DOWN: newNode = new Node(headNode.X, headNode.Y+Shell.Block_Size); break; } Food myFood = shell.getFood(); if (myFood.getX() == headNode.X && myFood.getY() == headNode.Y) { Nodes.add(0,new Node(myFood.getX(),myFood.getY())); //Shell.produceFood(); } else { Shell.myFood = null; Nodes.add(0,newNode); Nodes.remove(Nodes.size()-1); } } public int getLength() { return Nodes.size(); } public Node getNode(int index) { return Nodes.get(index); } private void reset() { Nodes.clear(); Nodes.add(new Node(Shell.Block_Size*10+50,Shell.Block_Size*10+50)); Nodes.add(new Node(Shell.Block_Size*9+50,Shell.Block_Size*10+50)); Nodes.add(new Node(Shell.Block_Size*8+50,Shell.Block_Size*10+50)); Nodes.add(new Node(Shell.Block_Size*7+50,Shell.Block_Size*10+50)); nextDirection = Direction.RIGHT; } } ``` import java.util.Random; public class Food { public static int X = 0; public static int Y = 0; Random random = new Random(); public int getX() { return Shell.Block_Size*random.nextInt(Shell.Col)+50; } public int getY() { return Shell.Block_Size*random.nextInt(Shell.Row)+50; } } ``` public enum Direction { LEFT, RIGHT, UP, DOWN } ``` import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyHandler extends KeyAdapter{ private Snake snake = null; public KeyHandler(Snake snake) { this.snake = snake; } public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_UP : snake.setDirection(Direction.UP); break; case KeyEvent.VK_DOWN : snake.setDirection(Direction.DOWN); break; case KeyEvent.VK_RIGHT : snake.setDirection(Direction.RIGHT); break; case KeyEvent.VK_LEFT : snake.setDirection(Direction.LEFT); break; } } } ``` public class Node { public int X = 0; public int Y = 0; public Node(int X, int Y) { this.X = X; this.Y = Y; } } ```

java贪吃蛇移动问题求解

当前只用到了3个类: 代表蛇:Snake.java 代表地图:Garden.java 代表方向的枚举类:Dir.java 遇到的问题:我是采取在蛇头前添加一节,然后去掉尾巴上最后一节,再重画的方式 来让蛇移动,但是去蛇尾的方法好像没起作用,问题不知道出在哪了,有大神来看看么? 想要达到的效果:只有一个格子在移动,而不是这样每动一次,原来的还在。 Snake.java------------------------------------------------------------ ```import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; public class Snake { private Node head = null; private Node tail = null; private int size; Node n = new Node(15, 10, Dir.L); private Garden gd; public Snake(Garden gd) { head = n; tail = n; size = 1; this.gd = gd; } // 添尾 public void addToTail() { Node node = null; switch (tail.dir) { case L: node = new Node(tail.x + 1, tail.y, Dir.L); break; case R: node = new Node(tail.x - 1, tail.y, Dir.R); break; case U: node = new Node(tail.x, tail.y + 1, Dir.U); break; case D: node = new Node(tail.x, tail.y - 1, Dir.L); break; } node.prev = tail; tail.next = node; tail = node; size++; } // 去尾 public void deleteTail() { if (size == 0) return; tail = tail.prev; tail.next = null; } // 添头 public void addToHead() { Node node = null; switch (head.dir) { case L: node = new Node(head.x - 1, head.y, head.dir); break; case R: node = new Node(head.x + 1, head.y, head.dir); break; case U: node = new Node(head.x, head.y - 1, head.dir); break; case D: node = new Node(head.x, head.y + 1, head.dir); break; } node.next = head; head.prev = node; head = node; size++; } public void move() { if (size == 0) return; addToHead(); deleteTail(); } Node n1 = new Node(n.x-5, n.y, n.dir); Node n2 = new Node(n.x-10, n.y, n.dir); public void draw(Graphics g) { if (size <= 0) return; move(); for (Node theNode = head; theNode != null; theNode = theNode.next) { theNode.draw(g); } } private class Node { private int x, y; Dir dir = null; private int w = Garden.wide; Node next = null; Node prev = null; public Node(int x, int y, Dir dir) { this.x = x; this.y = y; this.dir = dir; } public void draw(Graphics g) { Color c = g.getColor(); g.setColor(Color.RED); g.fillRect(x * w, y * w, w, w); g.setColor(c); } } public void KeyPressed(KeyEvent e) { int key = e.getKeyCode(); switch (key) { case KeyEvent.VK_W: head.dir = Dir.U; break; case KeyEvent.VK_S: head.dir = Dir.D; break; case KeyEvent.VK_A: head.dir = Dir.L; break; case KeyEvent.VK_D: head.dir = Dir.R; break; } } } ``` Garden.java----------------------------------------------------------------------- import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JPanel; public class Garden extends JPanel { private JFrame jf = null; // 格子大小 public static int wide = 20; // 窗口大小 private int gWidth = 500; private int gHeigth = 500; Snake s = new Snake(this); Egg e = new Egg(); public static void main(String[] args) { new Garden().init(); } // 初始化窗口 private void init() { jf = new JFrame(); jf.add(this); jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE); jf.setLocation(20, 20); jf.setSize(gWidth + 7, gHeigth + 30); jf.setResizable(false); jf.setVisible(true); jf.addKeyListener(new KeyMonitor()); new Thread(new PaintThread()).start(); } public void paint(Graphics g) { Color c = g.getColor(); g.setColor(Color.GREEN); // 画格子 for (int i = 0; i < gHeigth; i += wide) { for (int j = 0; j < gWidth; j += wide) { g.drawRect(i, j, wide, wide); } } g.setColor(c); s.draw(g); e.drawEgg(g); } private class PaintThread implements Runnable { @Override public void run() { while(true) { repaint(); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class KeyMonitor extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { s.KeyPressed(e); } } } Dir.java--------------------------------------------------------------------------- public enum Dir { L,R,U,D; }

java 贪吃蛇Snake 自定义监听器问题

比如:定义一个snakeListener接口 public interface SnakeListener {//定义接口 void snakeMove(Snake snake);//事件源是蛇· } 在Snake类里面: public class Snake{ private Set<SnakeListener> listener = new HashSet<SnakeListener>(); // 上是一个监听器组,可以注册多个监听器 public void addSnakeListener(SnakeListener l) if(l!=null){ listener.add(l); } } 疑问:为什么要用集合类注册多个监听器?监听器不就是监听蛇移动着一个功能而已吗?为什么要集合类注册多个监听器? 我感觉就是一个监听,不要注册多个啊 listener.add(l);//这句怎么理解

Java贪吃蛇图形绘制问题

* # 这里是控制蛇移动的代码 ``public void move_on() { paint p1=new paint(); Fruit fruit=new Fruit(); Snake snake=new Snake(); Move read=new Move(); /* * 对第一个元素即蛇头进行判断,根据所指方向对x,y坐标进行操作 * 完毕后重绘界面,达到动态移动效果 */ new Thread(new Runnable() { @Override public void run() { // TODO 自动生成的方法存根 while(Snake.life){ switch (Model.snake.get(0).direction) { case 8: Model.snake.get(0).point.y+=General.y_height; p1.repaint(); break; case 2: Model.snake.get(0).point.y-=General.y_height; break; case 4: Model.snake.get(0).point.x-=General.x_width; break; case 6: Model.snake.get(0).point.x+=General.x_width; break; default: break; } System.err.println(Model.snake.get(0).point.x+" "+Model.snake.get(0).point.y); //调用绘制方法进行重绘 SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // TODO 自动生成的方法存根 p1.repaint(); //对蛇体进行移动操作,即每一个节点都到了前一个节点的位置上 for(int i=1;i<Model.snake.size();i++) { Model.snake.get(i).direction=Model.snake.get(i-1).direction; Model.snake.get(i).point=Model.snake.get(i-1).point; } /* 进行完移动操作之后判断一下是否吃到果子 * 如果被吃掉,则把果子的位置和赋值给read,将原头结点的方向赋值给read * 最后将read插入snake头结点 */ if(fruit.isEaten()) { read.point=fruit.location; read.direction=Model.snake.get(0).direction; Model.snake.offerFirst(read); p1.repaint(); } }//end swing_run }); /* * 判断是否撞墙或吃到身体(结束游戏) */ snake.isAlive(); try { Thread.sleep(1500); } catch (InterruptedException e) { // TODO: handle exception } move_on(); } } }).start(); }//end move_on` # 这里是绘制蛇和果子的方法 ## ``public void paintComponent(Graphics g) { super.paintComponent(g); System.err.println("调用绘制方法"); snake_paint.drawSnake(g); /* * 当蛇长为1(即刚初始化游戏)的时候 * 或判断果子被吃掉后 * 才能绘制果子 */ if(Snake.Long==1||fruit_paint.isEaten()) { fruit_paint.drawFruit(g); } # public void drawSnake(Graphics g) { super.paintComponent(g); Model model=new Model(); g.setColor(Color.BLACK); System.err.println("调用绘制蛇体方法"); for(Move r:model.snake) g.fillRect(r.point.x,r.point.y, General.x_width, General.y_height); }` public void drawFruit(Graphics g) { g.setColor(Color.RED); g.fillRect(location.x, location.y, General.x_width,General.y_height); } 小弟现在面临的问题是:1.绘制方法调用了,但是面板毫无动静,依然是第一次值的位置。看了一下断点和输出,值是传给了绘制方法的。 是不是界面刷新问题?在move_on方法里面新建了一个线程,不知道用对没。 2.有时候值会大于定下的边界(y=700),而继续增加一点,比如到了750才停下,是不是线程冲突的问题? 3.,除了第一次调用绘制方法的时间正确以外,其他的时间都不对,不是每一个switch判定之后马上就调用。而是在判定游戏结束(蛇头位置大于容器边界)之后一直调用。

贪吃蛇数据库连接问题

package ads.com; import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; enum State{ RUN,DEAD; } public class Board extends Frame{ private static final int width = 400; private static final int height = 300; public static final int tilewidth = 16; public static final int tileheight = 16; public static final int row = 15; public static final int column = 20; public static final int xoffset = ((width-column*tilewidth)/2); public static final int yoffset = ((height-row*tileheight)/2); private Snake snake; private Food food; private State state; public int getRow(){ return row; } public int getColumn(){ return column; } public Board(String title){ super(title); setSize(width,height); setVisible(true); setResizable(false); setState(State.RUN); snake = new Snake(); food = produceFood(); addWindowListener(new BoardHandler()); addKeyListener(new KeyHandler(this,snake)); } public Snake getSnake(){ return snake; } public void drawDecoration(Graphics g){ g.setColor(Color.RED); g.drawRect(xoffset,yoffset,column*tilewidth,row*tileheight); } public void paint(Graphics g){ switch(state){ case RUN: drawDecoration(g); drawSnake(g); drawFood(g); break; case DEAD: drawDeadMessage(g); break; } } public void drawSnake(Graphics g){ g.setColor(Color.GREEN); for(int i=0;i<snake.getLength();i++){ Body body = snake.getBody(i); g.fillRect(body.col*tilewidth+xoffset,body.row*tileheight+yoffset,tilewidth,tileheight); } } public void drawFood(Graphics g){ g.setColor(Color.BLUE); g.fillRect(food.col*tilewidth+xoffset,food.row*tileheight+yoffset, tilewidth, tileheight); } public void drawDeadMessage(Graphics g){ g.drawString("GGGGGGGGGGGGGGGGGG,your score:"+ snake.score +"press F2 to retry",xoffset,height/2); } public Food produceFood(){ boolean finished = false; Food myfood = null; while(!finished){ myfood = new Food(); finished = true; for(int i=0;i<snake.getLength();i++){ if(snake.getBody(i).col==myfood.col&&snake.getBody(i).row==myfood.row) finished = false; } } food = myfood; snake.score++; return food; } public Food getFood(){ return food; } public void setState(State s){ state = s; } } package ads.com; public class Body { public int row; public int col; public Body(int row,int col){ this.row = row; this.col = col; } } package ads.com; import java.util.Random; public class Food extends Body{ public Food(){ super(0,0); Random r = new Random(); this.row = r.nextInt(Board.row); this.col = r.nextInt(Board.column); } } package ads.com; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyHandler extends KeyAdapter{ private Snake snake; private Board board; public KeyHandler(Board b,Snake s){ snake = s; board = b; } public void keyPressed(KeyEvent e){ switch(e.getKeyCode()){ case KeyEvent.VK_UP: snake.setNextDirection(Direction.UP); break; case KeyEvent.VK_DOWN: snake.setNextDirection(Direction.DOWN); break; case KeyEvent.VK_LEFT: snake.setNextDirection(Direction.LEFT); break; case KeyEvent.VK_RIGHT: snake.setNextDirection(Direction.RIGHT); break; case KeyEvent.VK_F2: snake.reset(); board.setState(State.RUN); break; } } } package ads.com; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class BoardHandler extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0); } } package ads.com; import java.util.ArrayList; import java.util.List; enum Direction { UP, DOWN, LEFT, RIGHT } public class Snake { private List<Body> mybody; private Direction mydirection; private Body head; private Direction nextdirection; private ScoreTrans st; public int score; private boolean flag; public Snake() { mybody = new ArrayList<>(); st = new ScoreTrans(score); reset(); } public void move(Board b) { mydirection = nextdirection; switch (mydirection) { case UP: head = new Body(head.row - 1, head.col); break; case DOWN: head = new Body(head.row + 1, head.col); break; case LEFT: head = new Body(head.row, head.col - 1); break; case RIGHT: head = new Body(head.row, head.col + 1); break; default: head = new Body(0, 0); break; } Food f = b.getFood(); if(f.row==head.row&&f.col==head.col){ mybody.add(0,f); b.produceFood(); } else{ mybody.add(0, head); mybody.remove(mybody.size() - 1); } if(checkBodyCollsion()||checkBoundCollsion(b)){ b.setState(State.DEAD); if(!flag) { st.trans(); flag = true; } } } public void setNextDirection(Direction d) { switch (d) { case UP: if (mydirection == Direction.DOWN) { break; } else nextdirection = d; case DOWN: if (mydirection == Direction.UP) { break; } else nextdirection = d; case LEFT: if (mydirection == Direction.RIGHT) { break; } else nextdirection = d; case RIGHT: if (mydirection == Direction.LEFT) { break; } else nextdirection = d; } } public void reset() { mybody.clear(); mybody.add(new Body(7, 4)); mybody.add(new Body(7, 3)); mybody.add(new Body(7, 2)); mybody.add(new Body(7, 1)); head = mybody.get(0); mydirection = Direction.RIGHT; nextdirection = Direction.RIGHT; score = 0; flag = false; } public Body getBody(int index) { return mybody.get(index); } public int getLength() { return mybody.size(); } public boolean checkBodyCollsion(){ for(int i=1;i<mybody.size()-1;i++){ if((mybody.get(i).col==head.col)&&(mybody.get(i).row==head.row)) return true; } return false; } public boolean checkBoundCollsion(Board b){ if(head.col<0||head.col>=b.column||head.row<0||head.row>=b.row) return true; return false; } public int getScore(){ return score; } } package ads.com; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class OracleOpen { private static String driver; private static String url; private static String username; private static String password; static { driver="oracle.jdbc.driver.OracleDriver"; url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; username="scott"; password="zhushaowei12"; } public static Connection open(){ try { Class.forName(driver); return DriverManager.getConnection(url,username,password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package ads.com; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class ScoreTrans { private Snake snake; private String name = "ads"; private int score; public ScoreTrans(int score){ this.score = score; } public void trans(){ Connection conn = OracleOpen.open(); String sql = "insert into snake values(?,?)"; try { PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1,name); pstmt.setInt(2,snake.getScore()); pstmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } OracleOpen.close(conn); } } package ads.com; public class Updater extends Thread{ private Board myboard; private Snake snake; public Updater(Board b,Snake s){ myboard = b; snake = s; } public void run(){ while(true){ snake.move(myboard); myboard.repaint(); try { sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package ads.com; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Board board = new Board("snake"); Updater myupdater = new Updater(board,board.getSnake()); myupdater.start(); } } 没加数据库前能正常运行,加了以后发现数据无法存入数据库

贪吃蛇游戏:为什么我按住方向键不放时,我的贪吃蛇像卡的一样

``` package game; import java.awt.Button; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; public class Window extends JFrame implements Runnable { static int x1 = 500;// 蛇头横坐标 static int y1 = 400;// 蛇头纵坐标 Button b[] = new Button[50];// 蛇数组 Button fruit = new Button();// 水果 boolean flag = true;// 判断是否吃到果实 int x, y;// 水果坐标 Thread t; int reverse;// 方向 boolean reve = true;// 方向标志 public Window() { t = new Thread(this); b[0] = new Button();// 蛇头 b[0].setBounds(x1, y1, 20, 20); b[0].setBackground(Color.blue); add(b[0]); for (int i = 1; i < 50; i++) { b[i] = new Button();// 蛇长度 } if (flag) {// 水果的随机位置 while (flag) { x = (int) (25 + Math.random() * 1175); y = (int) (1 + Math.random() * 800); System.out.println("x-->" + x); System.out.println("y-->" + y); fruit.setBounds(x, y, 20, 20); fruit.setBackground(Color.yellow); add(fruit); flag = false; } } setLayout(null); setTitle("Retro Snaker"); setSize(1200, 800); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } switch (reverse) { case 0:// 上 { y1 -= 20; b[0].setBounds(x1, y1, 20, 20); break; } case 1:// 下 { y1 += 20; b[0].setBounds(x1, y1, 20, 20); break; } case 2:// 左 { x1 -= 20; b[0].setBounds(x1, y1, 20, 20); break; } case 3:// 右 { x1 += 20; b[0].setBounds(x1, y1, 20, 20); break; } default: break; } } } } class Move extends Window implements ActionListener, KeyListener { Window w; Button go;// 开始按键 public Move() { go = new Button("开始"); go.setBounds(25, 0, 50, 25); go.addActionListener(this); add(go); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) {// 上 y1 -= 20; reverse = 0; System.out.println("上"); } if (e.getKeyCode() == KeyEvent.VK_DOWN) {// 下 y1 += 20; reverse = 1; System.out.println("下"); } if (e.getKeyCode() == KeyEvent.VK_LEFT) {// 左 x1 -= 20; reverse = 2; System.out.println("左"); } if (e.getKeyCode() == KeyEvent.VK_RIGHT) {// 右 x1 += 20; reverse = 3; System.out.println("右"); } this.repaint(); } public void keyReleased(KeyEvent e) { } public void actionPerformed(ActionEvent e) { if (e.getSource() == go) { t.start(); go.addKeyListener(this); } } } ```

自己用java一个贪吃蛇,但有两个小问题,希望大神解答

我使用java和swing编写了一个贪吃蛇的程序,可以顺利运行,但有两个小问题,一直不知道如何解决。第一个是当蛇吃到随机出来的点时,蛇的长度会加1,但蛇身后面会出来一个 新的点,随着蛇移动蛇身的距离而消失;第二个问题是有时候运行游戏会不能控制,希望大神费心解答一下。 ``` package game; import java.awt.Color; public class SnakeNode {//定义蛇身集合中的各个元素点 private int x; private int y; private Color color; public SnakeNode() { super(); // TODO Auto-generated constructor stub } public SnakeNode(int x, int y, Color color) { super(); this.x = x; this.y = y; this.color = color; } 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 Color getColor() { return color; } public void setColor(Color color) { this.color = color; } } ``` ``` package game; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; public class MainGame extends JPanel{ private final int length = 20;//定义画板的长 private final int width = 30;//定义画板的宽 private final int unit = 20;//定义单位长度 private ArrayList<SnakeNode> snake = new ArrayList<>();//定义蛇身的集合 private int Direction;//定义蛇头的方向 private int Length ;//定义蛇身的长度 private SnakeNode newNode = new SnakeNode(1,1,Color.BLACK);//定义随机点 Timer time = new Timer(100,new ThingsListener()); public int getDirection() { return Direction; } public void setDirection(int direction) { Direction = direction; } public int getLength() { return Length; } public void setLength(int length) { Length = length; } public SnakeNode getNewNode() { return newNode; } public void setNewNode(SnakeNode newNode) { this.newNode = newNode; } public MainGame() {//初始化各项数据与方法 snake.add(new SnakeNode(width/2,length/2,Color.GREEN)); snake.add(new SnakeNode(width/2,length/2,Color.BLUE)); snake.add(new SnakeNode(width/2,length/2,Color.RED)); Direction = 1;//定义初始方向为向上 Length = 3;//蛇身长度为3 CreateNode();//产生随机点 this.addKeyListener(new KeyAdapter() {//捕捉键盘的按键事件 public void keyPressed(KeyEvent e) { int direction = 0;//定义一个按下按钮后要去的方向 switch(e.getKeyCode()) { case KeyEvent.VK_UP://按下向上,返回1 direction = 1; break; case KeyEvent.VK_DOWN://按下向下,返回-1 direction = -1; break; case KeyEvent.VK_LEFT://按下相左,返回2 direction = 2; break; case KeyEvent.VK_RIGHT://按下向右,返回-2 direction = -2; break; default: break; } if(direction + Direction !=0) {//不能反向运动 Direction = direction; Move(direction); repaint(); } } }); time.start(); } public void Move(int direction) {//定义蛇身移动的方法 int FirstX = snake.get(0).getX();//获取蛇第一个点 int FirstY = snake.get(0).getY();//获取蛇第二个点 switch(direction) { case 1: FirstY--; break; case -1: FirstY++; break; case 2: FirstX--; break; case -2: FirstX++; break; default: break; } if(FirstX == newNode.getX()&&FirstY == newNode.getY()) {//当碰到随机点时 getNode(); repaint(); } for(int x = 0; x < Length; x++) {//当碰到蛇身自己时 if((FirstX==snake.get(x).getX())&&(FirstY == snake.get(x).getY())) { Dead("你碰到自己啦~~~"); } } if(FirstX < 0 || FirstX > width -1 || FirstY < 0 || FirstY > length -1) { Dead("菜鸡,你撞墙啦~~~~~"); } for(int x = Length - 1; x > 0; x--) { snake.get(x).setX(snake.get(x-1).getX()); snake.get(x).setY(snake.get(x-1).getY()); } snake.get(0).setX(FirstX); snake.get(0).setY(FirstY); repaint(); } public void getNode() { SnakeNode addNode = new SnakeNode(newNode.getX(),newNode.getY(),newNode.getColor()); snake.add(addNode); Length++; for(int x = Length-1; x >0; x--) { snake.get(x).setX(snake.get(x-1).getX()); snake.get(x).setY(snake.get(x-1).getY()); snake.get(x).setColor(snake.get(x-1).getColor()); } snake.get(0).setX(addNode.getX()); snake.get(0).setY(addNode.getY()); snake.get(0).setColor(addNode.getColor()); CreateNode(); repaint(); } public void Dead(String s) { Date date = new Date(); SimpleDateFormat sd = new SimpleDateFormat(); String str2 = sd.format(date); String str = s +"\n" +"所以说游戏不得已将结束了"; JOptionPane.showMessageDialog(this, str2 + "\n" + str ); System.exit(0); } public void CreateNode() {//创造随机点的方法 int newX = 0; int newY = 0; Boolean flag = true; while(flag) { newX = new Random().nextInt(width); newY = new Random().nextInt(length); for(int i = 0; i < Length; i++) { if(snake.get(i).getX()==newX && snake.get(i).getY()==newY) { flag = true; break; } flag= false; } } Color color = new Color(new Random().nextInt(255),new Random().nextInt(255),new Random().nextInt(255)); newNode.setX(newX); newNode.setY(newY); newNode.setColor(color); snake.get(0).setColor(newNode.getColor()); } class ThingsListener implements ActionListener {//设置一个监听器事件 public void actionPerformed(ActionEvent e) { Move(Direction); repaint(); } } protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(newNode.getColor()); g.fillOval(newNode.getX()*unit, newNode.getY()*unit, unit, unit); g.setColor(newNode.getColor()); g.drawRect(0, 0, width*unit, length*unit); for(int x = 0; x < Length; x++) { g.setColor(snake.get(x).getColor()); g.fillOval(snake.get(x).getX()*unit, snake.get(x).getY()*unit, unit, unit); } } } ``` ``` package game; import java.awt.Color; import javax.swing.JFrame; public class Test { public static void main(String[] args) { JFrame frame = new JFrame("贪吃蛇————————————made by chenjiaheng"); frame.setBackground(Color.white); frame.setBounds(0,0,800,500); MainGame sn = new MainGame(); frame.add(sn); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); sn.requestFocus(); } } ```

急求一个Java小程序,可用eclipse以及JDK运行,比如贪吃蛇啥啥小游戏都行,很着急!

急求一个Java小程序,可用eclipse以及JDK运行,比如贪吃蛇啥啥小游戏都行,很着急!

java方法调用的问题 这个repaint()调的是哪个 为什么啊??

public class test { public static void main(String[] args) { new test().start(); } public void start(){ new A().m(); } class A{ public void m(){ repaint(); } public void repaint(){ System.out.println("nihao"); } } public void repaint(){ System.out.println("hanzhi"); } }

贪吃蛇想弄一个暂停键按空格键不消失是为什么?

package snake; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JPanel; public class FramePanel extends JPanel implements KeyListener { int[] x=new int[750];//蛇横坐标 int[] y=new int[750];//蛇纵坐标 int len=3;//蛇长度 boolean isStarted = false; String dir="R";//蛇初始向右 public FramePanel() { this.setFocusable(true); initSnake(); this.addKeyListener(this);;;//添加监听接口 } public void initSnake()//初始化 { len=3; dir="R"; x[0]=100; y[0]=50; x[1]=75; y[1]=50; x[2]=50; y[2]=50; } public void paint(Graphics g) { this.setBackground(Color.BLACK); g.fillRect(15, 15, 850, 650); if(dir.equals("R"))//头 { g.setColor(Color.WHITE); g.fillRect(x[0], y[0],15,15); } else if(dir.equals("L")) { g.setColor(Color.WHITE); g.fillRect(x[0], y[0],15,15); } else if(dir.equals("U")) { g.setColor(Color.WHITE); g.fillRect(x[0], y[0],15,15); } else if(dir.equals("D")) { g.setColor(Color.WHITE); g.fillRect(x[0], y[0],15,15); } for(int i=1;i<len;i++)//身体 { g.setColor(Color.GRAY); g.fillRect(x[i], y[i], 15, 15); } if(!isStarted) { g.setColor(Color.RED); g.setFont(new Font("Verdana ",Font.BOLD,30)); g.drawString("Pause", 300, 300); } } @Override public void keyTyped(KeyEvent e) { int KeyCode = e.getKeyCode(); if(KeyCode == KeyEvent.VK_SPACE) { isStarted = !isStarted; repaint(); } } public void changeDir(int key) { switch(key){ case KeyEvent.VK_LEFT : if(this.dir!="R"){ this.dir = "L";} break; case KeyEvent.VK_UP : if(this.dir!="D"){ this.dir = "U";} break; case KeyEvent.VK_RIGHT : if(this.dir!="L"){ this.dir = "R";} break; case KeyEvent.VK_DOWN : if(this.dir!="U"){ this.dir = "D";} break; } } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }

游戏贪食蛇的蛇身体是怎么写的?

下面是我在书上看见的?但不太懂这里。 ----------------------- ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573103951_119022.jpg) ------------------------------------------------ ![图片说明](https://img-ask.csdn.net/upload/201911/07/1573103762_680807.jpg)

JVAV写贪吃蛇小游戏,用线程实现窗口重绘,然后用键盘指令改变小蛇的方向,请问怎么让小蛇只根据指令移动?

![图片说明](https://img-ask.csdn.net/upload/201906/05/1559710703_639058.png) 现在的程序能够实现通每隔200ms小蛇自动往前跑一格,通过键盘指令能够改变方向,但是我不想让它自动跑,只想实现给它指令它才移动,请问怎么实现? 这是蛇的活动类 ``` package com.tcs.cn; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.Timer; /** * 这个类代表贪吃蛇的活动场所 * @author * @version */ public class Yard extends Frame { /* * 画图的线程 * */ Timer timer = new Timer(); PaintThread paintThread = new PaintThread(); private boolean gameOver = false; //游戏是否结束 /** * 行数 */ public static final int ROWS = 30; /* * 列数 * */ public static final int COLS = 30; /* * 活动区域大小 * */ public static final int BLOCK_SIZE = 15; //设置显示字属性 private Font fontGameOver = new Font("宋体", Font.BOLD, 50); //分数 private int score = 0; /* * 记录开始时候的时间 * */ private long beginTime=0; /* *实例化Snake和Egg的对象 * */ Snake s = new Snake(this); Egg e = new Egg(); /* * 抽象类 Image 是表示图形图像的所有类的超类。 * 必须以特定于平台的方式获取图像。 * */ Image offScreenImage = null; /* * 此函数的功能是:设置窗口的大小、位置、可见,以及点击事件和键盘事件,最后开启了绘图线程 * */ public void launch() { /* * 指定窗口的位置,窗口的左上角的位置为(90,10).是相对父窗口的相对位置 * */ this.setLocation(90, 10); /* * 设定窗口的大小 * 宽度width:COLS*BLOCK_SIZE * 高度hight:ROWS*BLOCK_SIZE * */ this.setSize(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE); /* * 为窗口添加监听器 * */ this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); /* * 将窗口设置可见 * */ this.setVisible(true); /* * 为窗口添加键盘事件 * */ this.addKeyListener(new KeyMonitor()); new Thread(paintThread).start(); } public static void main(String[] args) { Yard y=new Yard(); y.beginTime=System.currentTimeMillis(); y.launch(); } /* * 将变量gameOver设置为true,使得在paint()函数中将使得线程停止 * */ public void stop() { gameOver = true; } @Override public void paint(Graphics g) { /* * 获取此图形上下文的颜色 * */ Color c = g.getColor(); /* * 指定图形上下文的颜色 * */ g.setColor(Color.GRAY); /* * 用当前的颜色来填充指定的区域 * */ g.fillRect(0, 0, COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE); /* * 再一次的指定颜色为:黑灰色???????为什么要再一次的设定??? * 原因在于:我们想将绘图的颜色与文字显示的不一样 * */ g.setColor(Color.DARK_GRAY); //画出横线 /* * drawLine(int x1, int y1, int x2, int y2) * 函数的功能为: * 在此图形上下文的坐标系中,使用当前颜色在点 (x1, y1) 和 (x2, y2) 之间画一条线。 * 通过下面的两个for循环就会在图形化对象上画出表格 * */ for(int i=1; i<ROWS; i++) { g.drawLine(0, BLOCK_SIZE * i, COLS * BLOCK_SIZE, BLOCK_SIZE * i); } for(int i=1; i<COLS; i++) { g.drawLine(BLOCK_SIZE * i, 0, BLOCK_SIZE * i, BLOCK_SIZE * ROWS); } g.setColor(Color.YELLOW);//设定颜色,为下面显示文字信息做准备 /* * drawString(String str, int x, int y) *使用此图形上下文的当前字体和颜色绘制由指定 string 给定的文本。 * */ g.drawString("使用说明:使用方向键控制方向,F1--停止,F2--停止后恢复,F5--重新开始" , 10, 40); g.drawString("目前分数:" + score, 10, 60); g.drawString("加分规则:每吃一个加5分,加油!" , 10, 80); g.drawString("已经使用的时间:"+(System.currentTimeMillis()-beginTime)/1000 , 10, 100); /* * 检测游戏是否结束,当游戏结束时,则提示游戏“game over”,而且将界面恢复到初始界面的状态,且终止绘图线程 * */ if(gameOver) { g.setFont(fontGameOver); g.drawString("game over!", 90, 170); g.drawString("在玩一次,请按F5", 10, 250); g.drawString(" ", 200, 230);//???这个用意何在?? paintThread.pause(); } if(score>100) { g.drawString("好棒!!!", 90, 170); g.drawString("你已经超过"+score+",继续加油", 10, 230); } /* * 将图形界面设置为刚开始的颜色 * */ g.setColor(c); s.eat(e); e.draw(g); s.draw(g); } @Override public void update(Graphics g) { if(offScreenImage == null) { /* * public Image createImage(int width, * int height) * 创建一幅用于双缓冲的、可在屏幕外绘制的图像 * */ offScreenImage = this.createImage(COLS * BLOCK_SIZE, ROWS * BLOCK_SIZE); } /* * getGraphics() *创建供绘制闭屏图像(off-screen image)使用的图形上下文。 * */ Graphics gOff = offScreenImage.getGraphics(); paint(gOff); /* * drawImage(Image img, int x, int y, ImageObserver observer) * 绘制指定图像中当前可用的图像。 * */ g.drawImage(offScreenImage, 0, 0, null); } private class PaintThread implements Runnable { private boolean running = true; private boolean pause = false; public void run() { while(running) {//线程将一直处于运行当中,只有在游戏结束的时候 if(pause) continue; else repaint();//如果组件是轻量级组件,则会尽快调用paint()方法或者是调用update() try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } public void pause() { this.pause = true; } public void reStart() { this.pause = false; s = new Snake(Yard.this); gameOver = false; score=0; } public void gameOver() { running = false; } } /* * 此函数的功能为:检测我们是否按下F2,若按下,则重新启动线程,即重新开始游戏 * */ private class KeyMonitor extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(key == KeyEvent.VK_F5) { paintThread.reStart();//重新开始游戏 } else if(key==KeyEvent.VK_F1){ paintThread.pause=true;//暂停 } else if(key==KeyEvent.VK_F2){ paintThread.pause=false;//从暂停中恢复 } s.keyPressed(e); } } /** * 拿到所得的分数 * @return 分数 */ public int getScore() { return score; } /** * 设置所得的分数 * @param score 分数 */ public void setScore(int score) { this.score = score; } } ``` 这是小蛇类 ``` package com.tcs.cn; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyEvent; /** * 代表蛇 * @author * */ public class Snake { /* * 头结点 * */ private Node head = null; /* * 尾结点 * */ private Node tail = null; /* * 大小 * */ private int size = 0; /* * 开始游戏时: * 初始位置:(20,30) * 初始运动方向:Dir.L * */ private Node n = new Node(20, 30, Dir.L); /* * Yard的对象属性; * */ private Yard y; /* * 构造函数 * */ public Snake(Yard y) { /* * 将初始结点给头结点和尾结点,size初始化为 1, * */ head = n; tail = n; size = 1; this.y = y; } /* * 节点类 * */ private class Node { int w = Yard.BLOCK_SIZE; int h = Yard.BLOCK_SIZE; int row , col; Dir dir = Dir.L; Node next = null; Node prev = null; Node(int row, int col, Dir dir) { this.row = row; this.col = col; this.dir = dir; } void draw(Graphics g) { Color c = g.getColor(); g.setColor(Color.BLACK); g.fillRect(Yard.BLOCK_SIZE * col, Yard.BLOCK_SIZE * row, w, h); g.setColor(c); } } // 从尾加,代码与下面一个函数的代码功能相似,这里不再分析 public void addToTail() { Node node = null; switch(tail.dir) { case L : node = new Node(tail.row, tail.col + 1, tail.dir); break; case U : node = new Node(tail.row + 1, tail.col, tail.dir); break; case R : node = new Node(tail.row, tail.col - 1, tail.dir); break; case D : node = new Node(tail.row - 1, tail.col, tail.dir); break; } tail.next = node; node.prev = tail; tail = node; size ++; } // 从头加,下面的代码比较简单,相信大家应该都能理解 public void addToHead() { Node node = null; switch(head.dir) { case L : node = new Node(head.row, head.col - 1, head.dir); break; case U : node = new Node(head.row - 1, head.col, head.dir); break; case R : node = new Node(head.row, head.col + 1, head.dir); break; case D : node = new Node(head.row + 1, head.col, head.dir); break; } // node.next = head; // head.prev = node; // head = node; /* * 上面这种写法与下面这种写法一致,不过下面这种写法我更容易理解 * */ head.prev=node; node.next=head; head=node; size ++; } public void draw(Graphics g) { if(size <= 0) return; move(); for(Node n = head; n != null; n = n.next) { n.draw(g); } } /* * 移动过程所要做的操作:在运动方向增加一个节点,在尾部减去一个节点,并且检测是否已经死亡 * */ private void move() { addToHead(); deleteFromTail(); checkDead(); } private void checkDead() { if(head.row < 2 || head.col < 0 || head.row > Yard.ROWS || head.col > Yard.COLS) { y.stop(); } /* * 头节点与身体的某一个节点相撞,也标志着结束 * */ for(Node n = head.next; n != null; n = n.next) { if(head.row == n.row && head.col == n.col) { y.stop(); } } } /* * 删除尾节点 * */ private void deleteFromTail() { if(size == 0) return; tail = tail.prev; tail.next = null; } public void eat(Egg e) { /* * boolean intersects(Rectangle r) * 确定此 Rectangle 是否与指定的 Rectangle 相交。 * 若相交,表示我们吃到了一个点 ,则导致蛇的长度变长并且在出现一个点,并且加5分,否则什么也不做 * */ if(this.getRect().intersects(e.getRect())) { e.reAppear(); this.addToHead(); //吃了加5分 y.setScore(y.getScore() + 5); } } private Rectangle getRect() { /* * 构造了一个格子大小的区域 * */ return new Rectangle(Yard.BLOCK_SIZE * head.col, Yard.BLOCK_SIZE * head.row, head.w, head.h); } /* * 接收从键盘的按键事件,然后采取相应的解决方案 * */ public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); switch(key) { case KeyEvent.VK_LEFT : /* * 当按键为左的时候,只要前进方向不是右,即可转向 * */ if(head.dir != Dir.R) head.dir = Dir.L; break; case KeyEvent.VK_UP : /* * 当按键为"上",只要前进方向不是"下",就可以转向 * */ if(head.dir != Dir.D) head.dir = Dir.U; break; case KeyEvent.VK_RIGHT : /* * 当按键为"右"的时候,只要前进方向不是"左",就可以转向 * */ if(head.dir != Dir.L) head.dir = Dir.R; break; case KeyEvent.VK_DOWN : /* * 当按键为"下"的时候,只要前进方向不是"上",就可以转向 * */ if(head.dir != Dir.U) head.dir = Dir.D; break; } } } ``` 求大神解答 hen'ji

repaint方法没有调用paintComponent 为啥呀

import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener { public static final int B_WIDTH = 450; public static final int B_HEIGHT = 450; public static final int DOT_SIZE = 15; public static final int ALL_DOTS = 900; public static final int DELAY = 100; private Timer timer; boolean live = true; Image offScreenImage = null; Snake mySnake = new Snake(); public static void main(String[] args) { new Board().launchGame(); } public void launchGame() { JFrame myJFrame = new JFrame(); myJFrame.setTitle("Snake"); myJFrame.setLocation(400,200); myJFrame.getContentPane().add((new Board())); myJFrame.pack(); myJFrame.addKeyListener(new Board().new KeyMonitor()); myJFrame.setVisible(true); myJFrame.setResizable(false); myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); timer = new Timer(DELAY, this); timer.start(); } public Board() { this.setBackground(Color.BLACK); this.setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT)); this.setFocusable(true); this.addKeyListener(new KeyMonitor()); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); this.setDoubleBuffered(true); this.draw(g); } public void draw(Graphics g) { mySnake.draw(g); Food f = new Food(); f.draw(g); } @Override public void actionPerformed(ActionEvent e) { repaint(); } private class KeyMonitor extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { mySnake.keyPressed(e); } } } import java.awt.Color; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.event.KeyEvent; import javax.swing.JFrame; public class Snake { Board b; Direction dir = Direction.R; int x, y, size; private int sX[] = new int[Board.ALL_DOTS]; private int sY[] = new int[Board.ALL_DOTS]; public Snake() { size = 2; sX[0] = 1 * Board.DOT_SIZE; sX[1] = 0 * Board.DOT_SIZE; sY[0] = 0 * Board.DOT_SIZE; sY[1] = 0 * Board.DOT_SIZE; } public Snake(int x, int y, Board b) { this.x = x; this.y = y; this.b = b; } public void draw(Graphics g) { move(); Color c = g.getColor(); g.setColor(Color.GREEN); for(int i=0; i<size; i++) { g.fillOval(sX[i], sY[i], Board.DOT_SIZE, Board.DOT_SIZE); } } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); switch(key) { case KeyEvent.VK_UP : if(dir == Direction.D) break; dir = Direction.U; break; case KeyEvent.VK_DOWN : if(dir == Direction.U) break; dir = Direction.D; break; case KeyEvent.VK_LEFT : if(dir == Direction.R) break; dir = Direction.L; break; case KeyEvent.VK_RIGHT : if(dir == Direction.L) break; dir = Direction.R; break; } } public void move() { for(int i=size-1; i>0; i--) { sX[i] = sX[(i-1)]; sY[i] = sY[(i-1)]; } switch(dir) { case U : sY[0] -= Board.DOT_SIZE; break; case D : sY[0] += Board.DOT_SIZE; break; case L : sX[0] -= Board.DOT_SIZE; break; case R : sX[0] += Board.DOT_SIZE; break; } } } import java.awt.Color; import java.awt.Graphics; import java.util.Random; public class Food { private int fX; private int fY; private static Random r = new Random(); public Food() { fX = r.nextInt(Board.B_WIDTH / Board.DOT_SIZE) * Board.DOT_SIZE; fY = r.nextInt(Board.B_HEIGHT / Board.DOT_SIZE) * Board.DOT_SIZE; } public void draw(Graphics g) { Color c = g.getColor(); g.setColor(Color.RED); g.fillOval(fX, fY, Board.DOT_SIZE, Board.DOT_SIZE); } } public enum Direction { U, D, L, R } 初学者写的贪吃蛇,用timer计时器,每隔一段时间调用一次repaint(),但运行起来发现,repaint是每隔一段时间被调用了,但paintComponent方法只被调用了一次(或者两次)。。求解啊这bug烦死我了

repaint不会调用paint方法

java中我把布局设置为了setlayout(null),然后重绘的时候repaint不会调用paint方法了

如何使用vs2013编写贪吃蛇详细步骤

我使用vs2013编译贪吃蛇,但一直显示错误,百度搜索不知道在那里修改属性框架 希望可以有详细一点的步骤。 这样好理解运行,谢谢你的帮助,我还是新手,希望多多指教。

贪吃蛇吃了食物怎么让身体变长

#include "stdafx.h" #include<stdio.h> #include<stdlib.h> #include <time.h> #include <windows.h> #include<conio.h> #define AC 10 int X_Y(int (*ju)[AC],int ch1);//坐标移动 void zuo(int ju[][AC],int n1);//坐标赋值 void zuo_DY(int ju[][AC],int n2);//打印坐标 int kiss_1();//产生第1个随机数 int kiss_2();//产生第2个随机数 int x=5,y=5,ann=0; int ki_ss,kis_s;//赋值=随机数 extern ki_ss=kiss_1(); extern kis_s=kiss_2(); int au=0,adc=0; int main(int argc, char* argv[]) { char ch; int chs,hw; int ju[AC][AC]; zuo(ju,hw);//坐标赋值 zuo_DY(ju,hw);//打印坐标 while(1) { printf("输入wasd移动\n"); //scanf("%c",&ch); ch=getch(); if(ch=='s') chs=1; if(ch=='a') chs=2; if(ch=='w') chs=3; if(ch=='d') chs=4; hw=X_Y(ju,chs);//坐标移动后赋值 system("cls"); zuo_DY(ju,hw);//打印坐标 printf("返回值是%d\n",hw); printf("############\n"); } return 0; } void zuo(int ju[][AC],int n1)//坐标赋值 { int f,g; for(f=0;f<AC;f++) for(g=0;g<AC;g++) ju[f][g]=f*10+g; } int X_Y(int (*ju)[AC],int ch1)//坐标移动 { int n; switch(ch1) { case 1:n=ju[x+=1][y];break;//w case 2:n=ju[x][y-=1];break;//a case 3:n=ju[x-=1][y];break;//s case 4:n=ju[x][y+=1];break;//d } return n; } void zuo_DY(int ju[][AC],int n2)//打印坐标 n2坐标移动后的值 { int www=ju[ki_ss][kis_s],ss; printf("%d\n",ju[ki_ss][kis_s]); int f,g; for(f=0;f<AC;f++) { for(g=0;g<AC;g++) { if((ju[f][g]==45&&ann==0)||ju[f][g]==n2) { printf("◎");//头 ann=1;//清空原来的显示的坐标 if(www==n2)//吃到后 www食物坐标 如果吃了食物 { ss=n2;//把上一次移动的坐标赋值给ss while(au==adc) { if(ju[f][g]==ss||au==adc)//显示身体 au adc保持循环打印 { printf("◆");//身体 au=adc;//下一次也可以显示身体 } adc+1; //心碎; } //system("cls"); //printf("胜利\n"); //心碎; } } else if(ju[f][g]==www) printf("●"); else if(ju[ki_ss][kis_s]!=n2) printf("□"); } printf("\n"); } } int kiss_1()//产生第1个随机数 { int s; srand((int)time(NULL)); s = rand() % AC; return s; } int kiss_2()//产生第2个随机数 { int i; srand((char)time(NULL)); i = rand() % AC; return i; }

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

Intellij IDEA 实用插件安利

1. 前言从2020 年 JVM 生态报告解读 可以看出Intellij IDEA 目前已经稳坐 Java IDE 头把交椅。而且统计得出付费用户已经超过了八成(国外统计)。IDEA 的...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

魂迁光刻,梦绕芯片,中芯国际终获ASML大型光刻机

据羊城晚报报道,近日中芯国际从荷兰进口的一台大型光刻机,顺利通过深圳出口加工区场站两道闸口进入厂区,中芯国际发表公告称该光刻机并非此前盛传的EUV光刻机,主要用于企业复工复产后的生产线扩容。 我们知道EUV主要用于7nm及以下制程的芯片制造,光刻机作为集成电路制造中最关键的设备,对芯片制作工艺有着决定性的影响,被誉为“超精密制造技术皇冠上的明珠”,根据之前中芯国际的公报,目...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

差点跪了...

最近微信又搞出了一个大利器,甚至都上了热搜,当然消息最敏捷的自媒体人,纷纷都开通了自己的视频号。01 视频号是什么呢?视频号是微信体系内的短视频,它不同...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

Vue回炉重造之router路由(更新中)

你好,我是Vam的金豆之路,可以叫我豆哥。2019年年度博客之星、技术领域博客专家。主要领域:前端开发。我的微信是 maomin9761,有什么疑问可以加我哦,自己创建了一个微信技术交流群,可以加我邀请你一起交流学习。最后自己也创建了一个微信公众号,里面的文章是我自己精挑细选的文章,主要介绍各种IT新技术。欢迎关注哦,微信搜索:臻美IT,等你来。 欢迎阅读本博文,本博文主要讲述【】,文字通...

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐