[JAVA] Four-in-a-row with gravity that can be played on the console

Introduction

This time I played with gravity four-in-a-row on the console! It works like this. connect.gif

Since I made it for fun, there may be omissions in the judgment part, but in the future I will make improvements such as adding CPU battles based on this. About four-in-a-row with gravity

wiki https://ja.wikipedia.org/wiki/%E5%9B%9B%E7%9B%AE%E4%B8%A6%E3%81%B9

usage environment

・ Windows 7 · Java 8 ・ Eclipse

Source introduction

I will introduce the source of this time.

ConnectFour.java


package connect.main;

import java.util.Random;
import java.util.Scanner;

public class ConnectFour {

	public static void main(String[] args) {

		System.out.println("Start four-in-a-row with gravity");

		// 0:player1 1:player2
		int player = 0;
		Random random = new Random();
		int turn = 0;
		int[][] bord = new int[6][7];
		int i;

		//Board initialization(-1)
		for(i = 0; i < 6; i++) {
			for(int j = 0; j < 7; j++) {
				bord[i][j] = -1;
			}
		}

		// 0 || 1
		player = random.nextInt(2);


		Scanner scan = new Scanner(System.in);
		scan.useDelimiter(System.lineSeparator());
		while(true) {
			System.out.println();
			printPlayer(player);

			//Board output to console
			printBord(bord);

			//Draw when the board is full
			if(turn >= 42) {
				System.out.println("draw");
				break;
			}

			//Input and validation from the console
			System.out.println("number(0~6)Please enter.");
			String line = scan.next();
			if(line.trim().length() == 0 || line.trim().length() > 1) {
				System.out.println("The input is invalid.");
				continue;
			}
			if(!Character.isDigit(line.charAt(0))) {
				System.out.println("The input is invalid.");
				continue;
			}
			int num = Integer.parseInt(line);
			if(num < 0 || num > 6) {
				System.out.println("The input is invalid.");
				continue;
			}
			for(i = 0; i < 6; i++) {
				if(bord[i][num] == -1) {
					bord[i][num] = player;
					break;
				}
			}
			if(i >= 6) {
				System.out.println("[ " + num + "]Can't put any more in.");
				continue;
			}
			if(isWin(bord, i , num, player)) {
				System.out.println();
				printBord(bord);
				System.out.println((player == 0 ? "player1[○]":"player2[×]")+"Wins!!");
				break;
			}
			player = (player * -1) + 1;
			turn++;
		}
		scan.close();

		System.out.println("End");

	}

	public static void printPlayer(int player) {
		switch(player){
		case 0:
			System.out.println("player1[○]It's your turn.");
			break;
		case 1:
			System.out.println("player2[×]It's your turn.");
			break;
		default:
			System.out.println("error");
			return;
		}
	}

	public static void printBord(int[][] bord) {
		for(int j = 0; j < 7; j++) {

			if(j == 6) {
				System.out.println("[ " + j + "]");
			}else {
				System.out.print("[ " + j + "]");
			}
		}
		for(int i = 5; i >= 0; i--) {
			for(int j = 0; j < 7; j++) {
				String a = "";
				a = (bord[i][j] == 0) ? "[○]" : (bord[i][j] == 1) ? "[×]" : "[  ]";
				if(j == 6) {
					System.out.println(a);
				}else {
					System.out.print(a);
				}
			}
		}
	}

	public static boolean isWin(int[][] bord, int i, int j, int player) {
		int yoko = 1;// -
		int tate = 1;// |
		int sura = 1;// /
		int back = 1;// \
		int y = i;
		int x = j;

		//Horizontal check(right)
		while(x < 6) {
			if(bord[i][x+1] == player) {
				yoko++;
			}else {
				break;
			}
			x++;
		}
		x = j;
		//Horizontal check(left)
		while(x > 0) {
			if(bord[i][x-1] == player) {
				yoko++;
			}else {
				break;
			}
			x--;
		}
		if(yoko >= 4) {
			return true;
		}

		//Vertical check(Up)
		while(y < 5) {
			if(bord[y+1][j] == player) {
				tate++;
			}else {
				break;
			}
			y++;
		}
		y = i;
		//Vertical check(under)
		while(y > 0) {
			if(bord[y-1][j] == player) {
				tate++;
			}else {
				break;
			}
			y--;
		}
		if(tate >= 4) {
			return true;
		}
		y = i;
		x = j;
		// /Direction check(Up)
		while(y < 5 && x < 6) {
			if(bord[y+1][x+1] == player) {
				sura++;
			}else {
				break;
			}
			y++;
			x++;
		}
		y = i;
		x = j;
		// /Direction check(under)
		while(y > 0 && x > 0) {
			if(bord[y-1][x-1] == player) {
				sura++;
			}else {
				break;
			}
			y--;
			x--;
		}
		if(sura >= 4) {
			return true;
		}
		y = i;
		x = j;
		// \Direction check(Up)
		while(y < 5 && x > 0) {
			if(bord[y+1][x-1] == player) {
				back++;
			}else {
				break;
			}
			y++;
			x--;
		}
		y = i;
		x = j;
		// \Direction check(under)
		while(y > 0 && x < 6) {
			if(bord[y-1][x+1] == player) {
				back++;
			}else {
				break;
			}
			y--;
			x++;
		}
		if(back >= 4) {
			return true;
		}

		return false;
	}
}

That's all the sauce! To briefly explain the overall flow,

  1. Randomly decide the first player 1 and 2 with odd and even numbers (0 or 1).
  2. Initialize the board with -1.
  3. Display which order is displayed and display the board.
  4. Get the number from the console where to put the frame.
  5. Input check.
  6. If there is space on the board, set it on the board.
  7. From the position where the piece is installed, make a vertical and horizontal licking victory judgment, and if the conditions are met, it ends.
  8. Switch players and increment turn. Loop from 9.3

About victory judgment

Judge in the up / down / left / right, slash, and backslash directions from the piece you placed.

tate = 1; yoko = 1; sura = 1; back = 1;

Loop for each of the following conditions

① If the direction is the player's piece when viewed from the current position tate++; Loop by shifting the current position in the ↑ direction If they are different, they will not be continuous, so the loop ends

② If the direction is the player's piece when viewed from the current position tate++; Loop by shifting the current position in the ↓ direction If they are different, they will not be continuous, so the loop ends

The results of ① and ② are tate = Number of continuous pieces in the ↑ direction + Number of continuous pieces in the ↓ direction + 1 (initial value); Will be the same as.

When applied in the ← → ↙↗↖↘ direction in the same way as ① and ② yoko = ← + → + 1; sura = ↙ + ↗ + 1; back = ↖ + ↘ + 1; Is obtained.

If any one of them meets the condition of> = 4, the current player wins.

The point to note is to set each variable to the initial value 1 and to see the next cell from the current position under the loop condition. This is because the reference points will overlap if the judgment is made based on the current position. (If the initial value is 0 and the final value is -1, there is no problem with the reference point.) Example: Let's look at [3] [3] as a reference point (Upward judgment) Increment because the current position [3] [3] is player Move upward and current position [4] [3] ... (Downward judgment) Increment because the current position [3] [3] is player Move downward and current position [2] [3] ...

You will be covered at your current position [3] [3].

Summary

You should be able to play immediately if you copy and paste! Four-in-a-row with gravity has a wave of petit boom since I played when I was a student (laugh) Please play while killing time!

Recommended Posts

Four-in-a-row with gravity that can be played on the console
The world of Azure IoT that can be played on the DE10-Nano board: Ajuchika with FPGA !!?
Firebase-Realtime Database on Android that can be used with copy
Set the access load that can be changed graphically with JMeter (Part 2)
About the problem that the server can not be started with rails s
[Rails] "pry-rails" that can be used when saving with the create method
Organize methods that can be used with StringUtils
[Ruby] Methods that can be used with strings
About the matter that hidden_field can be used insanely
Ruby on Rails 5 quick learning practice guide that can be used in the field Summary
Summary of css selectors that can be used with Nookogiri
Create a page control that can be used with RecyclerView
A scraping of past weather that can be seen on the Japan Meteorological Agency website
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
Learning Ruby with AtCoder Beginners Selection [Some Sums] Increase the methods that can be used
Static analysis tool that can be used on GitHub [Java version]
File form status check sheet that can be deleted with thumbnails
Logic to draw a circle with ASCII art on the console
SwiftUI View that can be used in combination with other frameworks
Summary of JDK that can be installed with Homebrew (as of November 2019)
Introduction to Java that can be understood even with Krillin (Part 1)
Programming with ruby (on the way)
Try the lightweight JavaScript engine “QuickJS” that can be incorporated into C / C ++
Performance analysis and failure diagnostic tools that can be used with OpenJDK
Ruby array methods that can be used with Rails (other than each)
[ERROR message display] A simplified version that can be used at any time with the rails partial template.
Until ruby can be used on windows ...
Object-oriented that can be understood by fairies
Check with Java / Kotlin that files cannot be written in UAC on Windows
Try to save the data that can be read by JavaFX as PNG
Graph the sensor information of Raspberry Pi and prepare an environment that can be checked with a web browser