Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Formatter;
- import java.util.Random;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner read = new Scanner(System.in);
- game(read, 5, 5);
- }
- public static StringBuilder drawField(char emptySector, char target, int colSize, int rowSize) {
- StringBuilder targetCoords = new StringBuilder();
- Formatter f = new Formatter();
- int targetX = new Random().nextInt(rowSize);
- int targetY = new Random().nextInt(colSize);
- for (int i = 0; i < colSize; i++) {
- for (int j = 0; j < rowSize; j++) {
- if (targetX == j && targetY == i) {
- System.out.print(target + " ");
- } else {
- System.out.print(emptySector + " ");
- }
- }
- System.out.println();
- }
- return targetCoords.append(f.format("%02d %02d", targetX, targetY));
- }
- public static StringBuilder shot(Scanner scanner) {
- Formatter f = new Formatter();
- StringBuilder shotCoords = new StringBuilder();
- System.out.println("Введите координаты выстрела: ");
- int shotX = scanner.nextInt();
- int shotY = scanner.nextInt();
- return shotCoords.append(f.format("%02d %02d", shotX, shotY));
- }
- public static StringBuilder botShot(int colSize, int rowSize) {
- Formatter f = new Formatter();
- StringBuilder shotCoords = new StringBuilder();
- int shotX = new Random().nextInt(rowSize);
- int shotY = new Random().nextInt(colSize);
- return shotCoords.append(f.format("%02d %02d", shotX, shotY));
- }
- public static boolean checkShot(StringBuilder targetCoords, StringBuilder shot, String attacker) {
- System.out.printf("%S выстрелил по координатам %S%n", attacker, shot);
- boolean isGameOver = false;
- if (targetCoords.toString().equals(shot.toString())) {
- System.out.printf("%S выиграл%n", attacker);
- isGameOver = true;
- } else {
- System.out.printf("%S не попал%n", attacker);
- }
- return isGameOver;
- }
- public static void game(Scanner scanner, int colSize, int rowSize) {
- StringBuilder targetCoords = new StringBuilder(drawField('*', '+', 5, 5));
- while (true) {
- StringBuilder playerShot = shot(scanner);
- StringBuilder botShot = botShot(colSize, rowSize);
- if (checkShot(targetCoords, playerShot, "Игрок")) {
- break;
- }
- if(checkShot(targetCoords, botShot, "Робот")){
- break;
- }
- }
- scanner.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement