우연히 youtube를 보다가 java로 만든 뱀 게임이 있길래 새벽에 심심해서 따라해 봤다...하하하하하
영상의 길이는 40분이 살짝 넘어서 따라해볼만 한 것 같았다.
혹시나 궁금해하는 분들이 있을 수도 있으니 아래 링크와 코드의 흔적을 남겨놓겠다,,, 간단하면서 나름 재밌는 프로그램이니 따라해봐도 좋을 것??? 같다
Main
public class SnakeGame {
public static void main(String[] args) {
GameFrame frame = new GameFrame();
}
}
Frame
import javax.swing.*;
public class GameFrame extends JFrame {
GameFrame(){
this.add(new GamePanel());
this.setTitle("Snake");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
Panel
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener {
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 600;
static final int UNIT_SIZE = 25;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
static final int DELAY = 75;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX, appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
GamePanel(){
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
draw(graphics);
}
public void draw(Graphics graphics){
if(running) {
/*
for (int i = 0; i < SCREEN_HEIGHT / UNIT_SIZE; i++) {
graphics.setColor(Color.GRAY);
graphics.drawLine(i * UNIT_SIZE, 0, i * UNIT_SIZE, SCREEN_HEIGHT);
graphics.drawLine(0, i * UNIT_SIZE, SCREEN_WIDTH, i * UNIT_SIZE);
}*/
graphics.setColor(Color.red);
graphics.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
for (int i = 0; i < bodyParts; i++) {
if (i == 0) {
graphics.setColor(Color.green);
graphics.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
} else {
//graphics.setColor(new Color(45, 180, 0));
graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
graphics.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
// Score Board
graphics.setColor(Color.red);
graphics.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(graphics.getFont());
graphics.drawString("Score : " + applesEaten,
(SCREEN_WIDTH - metrics.stringWidth("Score : " + applesEaten))/2,
graphics.getFont().getSize());
} else {
gameOver(graphics);
}
}
public void move() {
for(int i = bodyParts; i>0; i--){
x[i] = x[i-1];
y[i] = y[i-1];
}
switch (direction){
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
}
}
public void newApple() {
appleX = random.nextInt(SCREEN_WIDTH/UNIT_SIZE)*UNIT_SIZE;
appleY = random.nextInt(SCREEN_HEIGHT/UNIT_SIZE)*UNIT_SIZE;
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
public void checkCollisions() {
// check if head collids with body
for(int i = bodyParts; i > 0; i--){
if((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
break;
}
}
// check if head touches left, right border
if(x[0] < 0 || x[0] > SCREEN_WIDTH) {
running = false;
}
// check if head touches top, bottom border
if(y[0] < 0 || y[0] > SCREEN_HEIGHT){
running = false;
}
if(!running){
timer.stop();
}
}
public void gameOver(Graphics graphics){
// Score
graphics.setColor(Color.red);
graphics.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(graphics.getFont());
graphics.drawString("Score : " + applesEaten,
(SCREEN_WIDTH - metrics.stringWidth("Score : " + applesEaten))/2,
graphics.getFont().getSize());
// Game Over Text
//graphics.setColor(Color.red);
graphics.setFont(new Font("Ink Free", Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(graphics.getFont());
graphics.drawString("Game Over",
(SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2,
SCREEN_HEIGHT/2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(running){
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e){
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R'){
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}
참고로 Apple은 Snake가 먹는 먹이이며, 먹으면 뱀의 길이가 1 증가한다.
- 참고
'JAVA' 카테고리의 다른 글
[Java 8] Optional (0) | 2022.10.07 |
---|---|
[JAVA 8] Stream (0) | 2022.10.06 |
[JAVA 8] 인터페이스의 변화 (0) | 2022.10.06 |
[JAVA 8] 함수형 인터페이스와 람다 표현식 (0) | 2022.09.23 |
ListIterator (0) | 2022.09.23 |