JavaRush /Blog Java /Random-FR /Vos propres courses sur console)
Olegator3
Niveau 37
Одесса

Vos propres courses sur console)

Publié dans le groupe Random-FR
Depuis le début des grandes tâches, j'ai été tourmenté par la question : « Est-ce que je pourrai aussi faire quelque chose comme Tetris, ou un serpent, parce qu'ils devraient me donner quelque chose comme ça... Eh bien, en général, je pensais à faire quelque chose de plus simple, comme un serpent ou Tetris, eh bien, l'idée est venue, bien sûr, de la bonne vieille console Tetris, il y avait un autre jeu - la course, si vous vous en souvenez, c'est pourquoi j'écris ceci, je suggère de poster "vos grands projets" ici et évaluer\améliorer\commenter\réprimander le code, je pense que cela favorise de nouvelles idées, donc si cela ne vous dérange pas, postez vos grands projets ici, ou au moins des idées pour eux. En attendant,

mon mon propre projet est une course sur console), j'ai écrit pendant environ 4 heures, + une heure pour déboguer le code\commentaires
Qui veut, peut copier mon code dans IDEA et l'évaluer/le lire, j'attends même les mauvaises critiques, pour l'instant c'est certes un peu en bois, mais je considère ce progrès par moi-même, que pour la première fois j'ai créé ce que je voulais)) https://gist.github .com


/Olegator3/3b15e51d683343740fb2

Classe principale du jeu :

package com.javarush.test.level24.Race; import java.awt.event.KeyEvent; import java.util.ArrayList; /** * Created by ПК on 23.01.2015. */ public class Track { private int height; private int width; private int points = 0; private static int life = 3; private PlayerCar playerCar; private ArrayList otherCars; private boolean isGameOver; static int[][] matrix; public static Track game; public Track(int height, int width, PlayerCar playerCar, ArrayList otherCars) { this.height = height; this.width = width; matrix = new int[height][width]; this.playerCar = playerCar; this.otherCars = otherCars; } public int getHeight() { return height; } public int getWidth() { return width; } public PlayerCar getPlayerCar() { return playerCar; } public int[][] getMatrix() { return matrix; } public ArrayList getOtherCars() { return otherCars; } public static void main(String[] args)throws InterruptedException { game = new Track(20,20,new PlayerCar(8,15),new ArrayList ()); game.otherCars.add(new OtherCars()); game.otherCars.add(new OtherCars()); game.run(); } //основая игровая логика public void run() throws InterruptedException{ KeyboardObserver keyboardObserver = new KeyboardObserver(); keyboardObserver.start(); isGameOver = false; while(!isGameOver) { if (keyboardObserver.hasKeyEvents()) { //получить самое первое событие из очереди KeyEvent event = keyboardObserver.getEventFromTop(); //Если равно символу 'q' - выйти из игры. if (event.getKeyChar() == 'q') return; //Если "стрелка влево" - сдвинуть машинку влево if (event.getKeyCode() == KeyEvent.VK_LEFT) playerCar.left(); //Если "стрелка вправо" - сдвинуть машинку вправо else if (event.getKeyCode() == KeyEvent.VK_RIGHT) playerCar.right(); } if(otherCars.get(0).getY() > height){ otherCars.set(0,new OtherCars()); points++; } if(otherCars.get(1).getY() > height) { otherCars.set(1,new OtherCars()); points++; } othersCarDown(); isTouch(playerCar, otherCars); print(); Thread.sleep(300); } //если проиграл.... for(int i = 0; i < matrix.length; i++) { for (int j = 0; j< matrix[0].length; j++) { System.out.print("Х"); } System.out.println(); } System.out.println("Ты проиграл..."); System.out.println(" **** Очки: " + points +" ****"); System.out.println(" **** Жизней:" +life +" ****"); } //движения машинок вниз public void othersCarDown() { for(OtherCars cars : otherCars) cars.move(); } //отрисовка происходящего на экран public void print(){ //копируем трэк int[][] temp = new int[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { temp[i][j] = matrix[i][j]; } } //печатаем в него другие машинки OtherCars.print(otherCars,temp); //печатаем в него машинку игрока PlayerCar.print(playerCar,temp); //печатаем поле на экран for(int i = 0; i < matrix.length; i++) { System.out.print("|"); for (int j = 0; j< matrix[0].length; j++) { if(temp[i][j] == 0) System.out.print(" "); if(temp[i][j] == 1) System.out.print("X"); } System.out.print("|"); System.out.println(); } //печать пробелов и очков System.out.println(" **** Очки: " + points +" ****"); System.out.println(" **** Жизней:" +life +" ****"); System.out.println(); System.out.println(); System.out.println(); } //Проверка на столкновения public void isTouch(PlayerCar car, ArrayList otherCars) { try { for(int i =0; i <="" car.cord.size();="" j++)="" if(othercars.get(i).cord.contains(car.cord.get(j)))="" othercars.set(i,new="" othercars());="" life--;="" }="" }catch="" (exception="" e){}="" if(life="=" 0){="" isgameover="true;" code=""> Класс машинки игрока :

package com.javarush.test.level24.Race; import java.util.ArrayList; /** * Created by ПК on 23.01.2015. */ public class PlayerCar { //координаты начальной точки int x; int y; //список координат для проверки на столкновения public ArrayList cord; //шаблон машинки public int[][] car = new int[][]{ {0,1,0}, {1,1,1}, {0,1,0}, {1,1,1}, }; public PlayerCar(int x, int y) { this.x = x; this.y = y; } public int[][] getCar() { return car; } public int getX() { return x; } public int getY() { return y; } public void left() { x--; if(!isNotEndOfTack()) x++; } public void right(){ x++; if(!isNotEndOfTack()) x--; } private boolean isNotEndOfTack(){ if(x < 0) return false; else if(x == Track.game.getWidth() - 2) return false; return true; } //Рисуем машинку в temp, которое будет нашим треком public static void print(PlayerCar car,int[][] temp){ //печатаем в него машинку игрока int[][] playercar = temp; int left = car.getX(); int top = car.getY(); int[][] carMatrix = car.getCar(); Track.game.getPlayerCar().cord = new ArrayList(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { if (top + i >= Track.game.getHeight() || left + j >= Track.game.getWidth()) continue; if (carMatrix[i][j] == 1) playercar[top + i][left + j] = 1; car.cord.add(String.valueOf(top + i) + " " + String.valueOf(left + i)); } } } }

Класс другой машинки:

package com.javarush.test.level24.Race; import java.util.ArrayList; import java.util.Random; /** * Created by ПК on 23.01.2015. */ public class OtherCars { //координаты начальной точки private int x; private int y; //список координат для проверки на столкновения public ArrayList cord; //шаблон машинки public int[][] car = new int[][]{ {0,1,0}, {1,1,1}, {1,1,1}, {1,1,1},}; public void setCord(ArrayList cord) { this.cord = cord; } //ставит случайные координаты сверху public OtherCars() { this.x = new Random().nextInt(18); this.y = new Random().nextInt(3); } //двигает машинку вниз public void move(){ y++; } public int getX() { return x; } public int getY() { return y; } public int[][] getCar() { return car; } //Все машинки передаваемые в АррэйЛисте, рисуются в передаваему матрицу "temp" из класса Track public static void print(ArrayList otherCars, int[][] temp) { //печать другой машины for(int i =0; i< otherCars.size();i++) { int left = otherCars.get(i).getX(); int top = otherCars.get(i).getY(); int[][] otherCar = otherCars.get(i).getCar(); Track.game.getOtherCars().get(i).setCord(new ArrayList ()); for (int k = 0; k < 4; k++) { for (int j = 0; j < 3; j++) { if (top + k >= Track.game.getHeight() || left + j >= Track.game.getWidth()) continue; if (otherCar[k][j] == 1) temp[top + k][left + j] = 1; otherCars.get(i).cord.add(String.valueOf(top + k) + " " + String.valueOf(left + k)); } } } } }

Ну и конечно популярный на джавераш "наблюдатель за клавиатурой":

package com.javarush.test.level24.Race; import javax.swing.*; import java.awt.*; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; /** * Created by ПК on 24.01.2015. */ public class KeyboardObserver extends Thread { private Queue keyEvents = new ArrayBlockingQueue (100); private JFrame frame; @Override public void run() { frame = new JFrame("KeyPress Tester"); frame.setTitle("Transparent JFrame Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setUndecorated(true); frame.setSize(400, 400); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setLayout(new GridBagLayout()); frame.setOpacity(0.0f); frame.setVisible(true); frame.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { //do nothing } @Override public void focusLost(FocusEvent e) { System.exit(0); } }); frame.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { //do nothing } public void keyReleased(KeyEvent e) { //do nothing } public void keyPressed(KeyEvent e) { keyEvents.add(e); } }); } public boolean hasKeyEvents() { return !keyEvents.isEmpty(); } public KeyEvent getEventFromTop() { return keyEvents.poll(); } }
Commentaires
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION