JavaRush /Blogue Java /Random-PT /Suas próprias corridas de console)
Olegator3
Nível 37
Одесса

Suas próprias corridas de console)

Publicado no grupo Random-PT
Desde que as grandes tarefas começaram, tenho sido atormentado pela pergunta: “Será que também poderei fazer algo como Tetris, ou uma cobra, porque deveriam me dar algo assim... Bem, em geral, eu estava pensando sobre fazendo algo mais simples, como uma cobra ou Tetris, bom, a ideia veio, claro, do bom e velho console Tetris, tinha outro jogo - corrida, se você lembra, é por isso que estou escrevendo isso, sugiro postar “seus grandes projetos” aqui e avaliando\melhorando\comentando\repreendendo o código, acho que isso promove novas ideias, então se você não se importa, poste aqui seus grandes projetos, ou pelo menos ideias para eles. Enquanto isso,

meu próprio projeto é corrida de console), escrevi por cerca de 4 horas, + uma hora para depurar o código\comentários
Quem quiser, pode copiar meu código no IDEA e avaliá-lo/jogá-lo, estou esperando até críticas negativas, até agora é certamente um pouco rígido, mas considero esse progresso para mim, que pela primeira vez criei o que queria)) https://gist.github.com/Olegator3/3b15e51d683343740fb2


Classe

principal do jogo:

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(); } }
Comentários
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION