Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize gluttonous Snake Game with Java

Shulou Source: shulou.com Published: 2022-06-02 05:36:45 10月03日 Update

This article introduces the relevant knowledge of "how to use Java to achieve gluttonous snake game". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Execution program: the entrance to the startup of the program

Package cn.hncu

Public?class?GreedySnake {

Public static void main (String [] args) {

Model model=new Model (80 and 50)

Control control=new Control (model)

View view=new View (model,control)

Model.addObserver (view)

(new Thread (model)) .start ()

}

}

Control class: mainly for keyboard keystroke collection and transmission

Package cn.hncu

Import java.awt.event.KeyEvent

Import java.awt.event.KeyListener

Public class Control implements KeyListener {

Model model

Public Control (Model?model) {

This.model=model

}

Public void keyPressed (KeyEvent?e) {

/ / this method collects buttons

Int key=e.getKeyCode ()

If (model.running) {

Switch (key) {

Case KeyEvent.VK_UP:

Model.changeDirection (model.up)

Break

Case KeyEvent.VK_DOWN:

Model.changeDirection (model.down)

Break

Case KeyEvent.VK_LEFT:

Model.changeDirection (model.left)

Break

Case KeyEvent.VK_RIGHT:

Model.changeDirection (model.right)

Break

Default:

Break

}

}

If (key==KeyEvent.VK_ENTER) {

Model.reset ()

}

}

Public void keyReleased (KeyEvent?e) {

}

Public void keyTyped (KeyEvent e) {

}

}

Model class: the implementation of creating snake bodies and snake movements, using threads.

Import java.util.Arrays

Import java.util.LinkedList

Import java.util.Observable

Import java.util.Random

Import javax.swing.JOptionPane

Public class Model extends Observable implements Runnable {

Public static final int left=1

Public static final int up=2

Public static final int right=3

Public?static?final?int?down=4

Public?boolean?coordinate [] []; / / use this as the coordinates of the interface

Public?LinkedList?node=new?LinkedList ()

Public?int?direction=2

Boolean?running=false

Public?int?maxX,maxY

Node?food

Public?int?sleeptime=200

Public?Model (int?maxX,int?maxY) {

This.maxX=maxX

This.maxY=maxY

Reset ()

}

Public?void?reset ()? {

Direction=this.up

Sleeptime=200

Coordinate=new?boolean [maxX] []

For? (int?i?=?0;?i?

Tags: Interface content keystrokes more knowledge programs movement practicality learning next entry dilemma graphics coordinates reality situation articles ways cases models Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Xiaomi Docker macOS MariaDB