The story of making ordinary Othello in Java


Hello! It's a private matter, but I moved to Tokyo from April and became a new member of society. We are currently in the middle of training. (There is 3 months of training.) In the training, all engineers are supposed to learn Java. Object-oriented thinking is important in any programming language, Java is a language designed with object orientation in mind, and I think it's a good language to learn first. It also works on Mac, Windows, and Linux in the same way, so it can be widely used without depending on the computer. Although I studied arrays, for loops, methods, and object orientation, Isn't it difficult for many people to get an idea of how these actually work together on software? Therefore, this time, I would like to create an Othello application that runs on the CLI and put the learned knowledge to practical use. I think the most efficient way to study programming is to "create and publish one application with your own power". Now, let's get into the main subject!

Hello, Othello Have you ever played Othello? There are white and black frames, and when you sandwich the opponent's frame, it changes to the color of your own frame. Ultimately, the one with the most pieces of your own color wins. Isn't it appropriate to divide the classes as follows when creating an Othello application? A frame class that holds the state of white or black, the position of the frame, etc. Field class that judges the turning over of a frame A game class that controls the entire game In order to get a feel for the atmosphere, let's first place a frame on the board and display it!

Create a top class

Information on each frame of Othello is handled in the frame class. The state of the frame (white, black, empty) is managed by the String type state variable. Here, black is B, white is W, and sky is E. Implement the setState () method to change the state and the getPosition () method to get the position.

public class Koma{
	private String state; //The color of Othello is black ... B, white ... W, sky ... E
	private int x;
	private int y;

	public Koma(int x,int y){
		this.state = "E";
		this.x = x;
		this.y = y;

	public String getState(){
		return this.state;

	public void setState(String state){
		this.state = state;

	public int[] getPosition(){
		int[]pos = {this.x, this.y};
		return pos;

Create field class

In the field class, you can place pieces on the board and turn them over. The prepare () method that initializes all the frames on the board in state E, Implement the feature () method that visualizes the situation on the board and outputs it to the command line.

import java.util.ArrayList;
import java.util.List;

public class Field{
  private List<Koma> komalist;
  private int ynum = 0;
  private int xnum = 0;

  public Field(int xnum, int ynum){
    this.xnum = xnum;
    this.ynum = ynum;
  public void prepare(){
    this.komalist = new ArrayList<>();
    for(int y=0;y<this.ynum;y++){
      for(int x=0;x<this.xnum;x++){
        Koma koma = new Koma(x,y);

  public Koma getKoma(int y, int x){
    for(Koma koma : this.komalist){
      int[]pos = koma.getPosition();
      if(pos[0]==y && pos[1]==x){
        return koma;
    return null;

  public void putKoma(int x, int y, String state){
    Koma koma = this.getKoma(x,y);

  public void feature(){
    String [][] board = new String[ynum][xnum];
    for(Koma koma : this.komalist){
      int[] pos = koma.getPosition();
      String state = koma.getState();
      board[pos[1]][pos[0]] = state;
    for(int y=0;y<board.length;y++){
      for(int x=0;x<board[0].length;x++){
        String b = board[y][x];

Create a game class

Call the field class and try to put a black frame at the position of x = 2, y = 2.

public class Game{
  public static void main(String[] args){
    Field field = new Field(6,6);


$ javac
$ java Game

Compile and run a Java program.

The position of x = 2, y = 2 is B, and the other places are E!

Judgment to turn over

Next, we will add a process to turn over the opponent's frame when the frame is placed. Let's imagine Othello concretely. (Assuming a simple situation of 4✕4 for explanation)

In the situation shown in the figure, what happens if you put a white frame on B-1? It's that easy! All black frames in between are flipped to white frames. The black frames on B-2 and B-3 change to white frames.

But what about this case? There are many places to reverse this time! Thanks to the white frame in D-1, the black frame in C-1 is inverted. Thanks to the white frame on D-3, the black frame on C-2 is inverted. Thanks to the white frames on B-4, the black frames on B-2 and B-3 are reversed.

Now, let's put this into the algorithm. It seems a little complicated. As you can see from the two examples above, there are common rules for flipping pieces. That is, in a certain direction, the white frame and the white frame sandwich the black frame. There are eight directions (north, northeast, east, southeast, south, southwest, west, northwest) on the board, so judgment processing must be performed for all directions. The fact that the white frame and the white frame sandwich the black frame is a little sloppy. If you chew a little more so that it can be described in the flow of the program, it will be as follows. If the frame you plan to place is a white frame,

  1. Acquire frames in order from near in a certain direction.
  2. Get the index of the closest white frame.
  3. True if black frames continue to that index without interruption, false otherwise

Let's consider using the previous example. If you get the frame list in 8 directions (north, northeast, east, southeast, south, southwest, west, northwest) from the position of B-1, it will be as follows.

direction Top list
North -
Northeast -
east black-White
Southeast black-White
South black-black-White
Southwest black
West White
Northwest -

Since the frame color to be placed next is white, it will be turned over in three directions: east, southeast, and south.

Make a CPU

It would be interesting if I could make network communication and play against my friends, It seems that the level is a little high, so let's play against the CPU this time. Creating a strong CPU is a little difficult, but a weak CPU can do it right away. A weak CPU can be implemented as follows.

  1. Get a list of places where you can place frames.
  2. Randomly select one from them.

That's it.

Othello has a rule that it should only be placed where flipping occurs (certainly) For example, if the next frame to be placed is white in the situation shown in the image below, There are four places that can be placed in orange (A-3, B-4, C-1, D-2). Randomly select one from these four places and place the frame there Let's say "the CPU placed the frame".

in conclusion

So far, I have explained the Othello program. I think it's important to write a program while feeling the gratitude of object orientation! This time

The code is easy for humans to read by dividing it into three parts. What if you don't have object orientation and you want to do these procedurally? I think it's very, very difficult. The important thing is to think for yourself, design and code the class. By all means, it can be Othello, it doesn't have to be Othello, it can be blackjack, it can be a web server, so when you learn a programming language, you have the experience of creating something from scratch. Let's look!

Recommended Posts

The story of making ordinary Othello in Java
The story of writing Java in Emacs
The story of low-level string comparison in Java
The story of learning Java in the first programming
The story of making dto, dao-like with java, sqlite
[Java version] The story of serialization
Get the result of POST in Java
The story of AppClip support in Anyca
The story of making a communication type Othello game using Scala.
[Java] Handling of JavaBeans in the method chain
About the idea of anonymous classes in Java
A story about the JDK in the Java 11 era
The story of forgetting to close a file in Java and failing
The story of making a game launcher with automatic loading function [Java]
The story of making the existing Dockerfile GPU compatible
Measure the size of a folder in Java
Feel the passage of time even in Java
The story of acquiring Java Silver in two months from completely inexperienced.
Import files of the same hierarchy in Java
Get the URL of the HTTP redirect destination in Java
The story of making a reverse proxy with ProxyServlet
The story of an Illegal State Exception in Jetty.
[Java] Get the file in the jar regardless of the environment
Change the storage quality of JPEG images in Java
The story of making Dr. Oakid using LINE BOT
Summarize the additional elements of the Optional class in Java 9
The story that .java is also built in Unity 2018
Implementation of gzip in java
Implementation of tri-tree in Java
Was done in the base year of the Java calendar week
Story of making a task management application with swing, java
A quick explanation of the five types of static in Java
20190803_Java & k8s on Azure The story of going to the festival
The story of throwing BLOB data from EXCEL in DBUnit
Count the number of digits after the decimal point in Java
How to derive the last day of the month in Java
The story of pushing Java to Heroku using the BitBucket pipeline
[Java] Delete the elements of List
Guess the character code in Java
Specify the java location in eclipse.ini
Story of passing Java Gold SE8
Unzip the zip file in Java
The story of @ViewScoped consuming memory
List of members added in Java 9
Parsing the COTOHA API in Java
List of types added in Java 9
Order of processing in the program
The origin of Java lambda expressions
Implementation of like function in Java
Call the super method in Java
Examine the system information of AWS Lambda operating environment in Java
[Java] Get the dates of the past Monday and Sunday in order
The story of not knowing the behavior of String by passing Java by reference
Output the difference between each field of two objects in Java
Find out the list of fonts available in AWS Lambda + Java
A story about hitting the League Of Legends API with JAVA
The milliseconds to set in /lib/ of Java jre is UTC
Examine the list of timezone IDs available in the Java ZoneId class
Get the public URL of a private Flickr file in Java
Let's create a TODO application in Java 5 Switch the display of TODO
How to get the length of an audio file in java