Nếu bạn đang tìm bài viết code game java thì vui lòng xem ngay những thông tin bên trong bài viết này nhé.
Nội dung bài viết
Java snake game 🐍 | code game java.
[button color=”primary” size=”medium” link=”#” icon=”” target=”false” nofollow=”false”]XEM VIDEO BÊN DƯỚI[/button]
Ngoài việc xem những mẹo vặt hay mới cập nhật này bạn có thể xem thêm nhiều nội dung mới khác do Khunganhtreotuong cung cấp tại đây nhé.
code game java và các Chia sẻ liên quan đến đề tài này.
Hướng dẫn chơi game rắn Java cho người mới bắt đầu # Java #snake # trò chơi Trại đào tạo mã hóa ghét anh ta! Hãy xem anh ấy có thể dạy bạn viết mã bằng một thủ thuật đơn giản này như thế nào … Bro Code là loạt bài hướng dẫn số 1 về viết mã bằng các ngôn ngữ lập trình khác nhau và các video hướng dẫn khác trong vũ trụ đã biết. .
Java snake game 🐍 và các hình ảnh liên quan đến chuyên mục này.
>> Ngoài việc xem đề tài này bạn có thể tìm xem thêm nhiều mẹo hay khác do chúng tôi cung cấp tại đây nhé: Xem thêm tin tức mới cập nhật tại đây.
Rất mong những Thông tin về chủ đề code game java này sẽ có giá trị cho bạn. Chân thành cảm ơn bạn.
#Java #snake #game.
Java snake game,Java snake game tutorial,java snake game eclipse,java snake tutorial,java snake code,java,snake,game,tutorial,for beginners,java snake game code eclipse,snake game in java,java snake game,snake game java,java snake,snake in java.
Java snake game 🐍.
code game java.
I didn't really expect this video to blow up. This was meant to be more of a practice project.
I probably would have spent more time optimizing the code if I knew it would get this many views lol
Well what you see is what you get I guess…
//*****************************************
public class SnakeGame {
public static void main(String[] args) {
new GameFrame();
}
}
//*****************************************
import javax.swing.JFrame;
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);
}
}
//*****************************************
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 = 1300;
static final int SCREEN_HEIGHT = 750;
static final int UNIT_SIZE = 50;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);
static final int DELAY = 175;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX;
int 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 g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if(running) {
/*
for(int i=0;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
*/
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
for(int i = 0; i< bodyParts;i++) {
if(i == 0) {
g.setColor(Color.green);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
else {
g.setColor(new Color(45,180,0));
//g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH – metrics.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
}
else {
gameOver(g);
}
}
public void newApple(){
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
}
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 'L':
x[0] = x[0] – UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
public void checkCollisions() {
//checks if head collides with body
for(int i = bodyParts;i>0;i–) {
if((x[0] == x[i])&& (y[0] == y[i])) {
running = false;
}
}
//check if head touches left border
if(x[0] < 0) {
running = false;
}
//check if head touches right border
if(x[0] > SCREEN_WIDTH) {
running = false;
}
//check if head touches top border
if(y[0] < 0) {
running = false;
}
//check if head touches bottom border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
//Score
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH – metrics1.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
//Game Over text
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.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;
}
}
}
}
//*****************************************
Awesome video! It's short, sweet, to the point; and best of all, it's fairly simple and straight forward. Thank you for sharing the knowledge!
great tutorial! even though mine didnt work properly sksksksksks
I had two problems with the snake:
Sometimes lag and sometimes it went off the edges. If someone has any of these problems, here is the solution.
The lag I resolved adding this line in the main class before call GameFrame:
System.setProperty("sun.java2d.opengl", "true");
The problem with edges I resolved modifing the next if conditions in the checkCollitions method:
//Check if head touches right border
if (x[0] > SCREEN_WIDTH – UNIT_SIZE) {
running = false;
}
//Check if head touches bottom border
if (y[0] > SCREEN_HEIGHT – UNIT_SIZE) {
running = false;
}
I work on Linux and I use Apache Netbeans.
hi bro, i want to ask if its possible to make the snake go diagonal ways?
Why my snake is not moving?
This is a comment (no cap)
in which software you are coding??
Great work bro ^^
I followed this tutorial and it worked out great, my only problem is, that I just got into Java and I don't really know why certain things work like they do in the code, I don't know if you fully understand what I mean, but could you give me some tips for understanding how certain things work because you didn't go into detail as to why you did the things you did ( I don't wanna say you should have gone into detail because this is clearly not meant for beginners but it would be great to learn from you or at least understand a bit of what you did) great work <3
Where to start coding T_T
algortirhtggahgbm
how tf did u make the snake move? I followed exactly what u did in move method but it doesn't want to move
thanks for the content creation on java man!! very cool apps
what a great explaination i will do it by self thank you
43:05 comment
I Love it!!! I am done with my code too. Superb!!!
My dream😌😌😌
bro, i did the same code but my frame is totally black after I run the program, can u give me your source code?
here is what I did to add restart functionality and add random start position for the snake :
=======================================
static final int X_UNITS = SCREEN_WIDTH/UNIT_SIZE;
static final int Y_UNITS = SCREEN_HEIGHT/UNIT_SIZE;
public void startGame() {
applesEaten=0;
direction='R';
for(int i = bodyParts;i>0;i–) // reset snake
x[i]=y[i]=-UNIT_SIZE;
bodyParts=6;
// randomize the snake starting position to start in the left quarter of the screen
x[0]=random.nextInt((int)(X_UNITS/4))*UNIT_SIZE;
y[0]=random.nextInt(Y_UNITS)*UNIT_SIZE;
newApple();
running = true;
if (timer==null) {
timer = new Timer(delay, this);
timer.start();
}
}
=========================================
Now remove timer.stop(); from checkCollisions
and add the following to the end of gameOver()
=========================================
g.setFont( new Font("Ink Free",Font.BOLD, 35));
FontMetrics metrics3 = getFontMetrics(g.getFont());
g.drawString("Press space bar to play again", (SCREEN_WIDTH – metrics3.stringWidth("Press space bar to play again"))/2, SCREEN_HEIGHT/2+50);
=========================================
and lastly, add the case to MyKeyAdapter
=========================================
case KeyEvent.VK_SPACE:
if (!running)
startGame();
break;
=========================================
Hello bro, I have an error while writing this code. I made the snake game. But when i run it the snake dosen't appear to move. But if I minimize my gameframe and maximize again the snake moves forward with respective DELAY variable value. So to see my snake moving I constantly need to mini-maxi-mize my gameframe window. Then only I see my snake moved.
Could you suggest a solution to this??
An excellent example for game's developers. And I really like it.
thanks Bro 100%
op bro
hey! how could i code a restart function for this? I keep getting stuck because after it hits the borders, im not sure how to get it to start again.
THAT'S AMAZING!!
I need some help I ran this code but the message appear that unable to launch how I solve this??
Thanks this was fun 👍
Make a chess game next time, im waiting 😀
thanks for this, it helped me a lot, greetings from Colombia.
pls someone tell me, how to control the snake? which keys in the keyBoard?
Great Tutorial. Easy to understand. I didn't play snake since 1999 on my NOKIA phone 🙂
Awsome video! You actually helped me a lot!
Uh mine does not move as fast as yours does i dont know why
Thank you thank you so much
HEY BRO, when I pass in the arguments for timer, it says that I have to remove the arguments to match the 'Timer()'
It's a great channel! I learn a lot with you. Thank you so much.
Best YouTube channel ever..
can u explain the GAME_UNITS var? pls (sr for my english) ._.
Thank you so much, dude. You explained it well and it worked for me. You earned a new fellow bro
Is there anything to fix in eclipse?. I have copied full code but only background come. please let me know.
Thank you so much, your channel helps me in many ways!
I added a check in newApple(), so the apple doesn't get planted underneath the body:
public void newApple() {
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE)) * UNIT_SIZE;
appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE)) * UNIT_SIZE;
for(int i = bodyParts; i > 0; i–) {
if((x[i] == appleX) && (y[i] == appleY)) {
newApple();
}
}
}