Introduction to Practical Programming

Introduction

This is a programming tutorial for beginners who cannot be convinced and understood by dry examples such as introductory books.

In this article, programming is focused on practice from the perspective of learning by writing programs. You can't do it just by reading a book like playing a musical instrument or driving a car. Here we convey the important concepts of programming through the implementation of Othello and the card game UNO. In Othello, about values, types, and methods. UNO deals with object orientation.

Note) The latter half "Uno implementation" is currently being edited.

Othello implementation

The first subject is Othello. Othello has few game states and player operations, but the operation of turning it over is complicated and is just right for practice.

What do you need to program Othello? After careful consideration, programmers seek the answer from the ocean of the net. Search technology is one of the most important technologies for programmers. This is because existing technologies can be used to devote resources such as time and concentration to more important issues. The search technology is a technology that extracts and utilizes necessary information from the information obtained by the search.

Then it is the first practice.

Practice 1 Program the Othello game. However, the following requirements must be met.

--Based on the basic rules described in Japanese Wikipedia (https://ja.wikipedia.org/wiki/Othello_ (board game) #rules). --The status of the Othello board is displayed. --You can place a piece. --When the completion conditions are met, the result is displayed and the process ends.

I dared to put up a difficult problem first. By working on Practice 1 as much as possible, the aim is to make the following content convincing. I want you to work on it.

Express the state

When dealing with a task, the first step is to sort out the problem. Any information can be confusing without careful consideration.

What is playing Othello? In order to program, it is necessary to understand all of them. First, you need an Othello board and a piece. And you need two players to play the game.

If you have a board, a piece, and a player, you can play Othello. The next question is "how to connect the world of programs with the real world". Only numerical values can be handled by the program. But boards and players are not numbers. There is a leap here. Instead of making Othello with a program, make a program that can be regarded as Othello. You don't need a board, a piece, or a player. In other words, the board etc. should be expressed numerically.

What should we do to represent the board, pieces and players? There are 64 squares on the board, and the top and back are on the top. The player has a white or black turn and puts a piece on the board. Next is practice.

Practice 2 Express the board and top. However, the following requirements must be met.

--64 You can save the state of squares. --Make the squares have information that can distinguish "nothing is placed", "white is placed", and "black is placed". --Place 4 pieces in the center according to the basic rules. --You can check the status of the board.

There are innumerable methods, but here we use a two-dimensional array. In the program below, 1 and 2 are used to express the black and white of the frame.

Answer example

class Othello {
    public static void main(String[] args) {
        int [][] borad = new int[8][8];

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                borad[i][j] = 0;
            }
        }

        borad[4][4] = 1;
        borad[4-1][4] = 2;
        borad[4][4-1] = 2;
        borad[4-1][4-1] = 1;

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                System.out.print(borad[i][j] + " ");
            }
            System.out.print("\n");
        }
    }
}

It is regarded as the execution result of this program. Next, represent the player.

Change the state

Check player requirements. Place a white or black piece. However, there is a condition that "can you turn it over?" You cannot place a piece in a square that cannot be turned over when you place a piece.

The mechanism that changes the behavior according to the conditions is called control syntax. The condition here is whether or not there is a piece that can be turned over when the piece is placed.

What is the means to achieve the operation? If the user operates the player, the program must accept the user's input. Then, the program is operated according to the input. Upon receiving an input such as "Place a black piece in the xth cell from the right and the yth cell from the left", the program checks if a black frame can be placed in that cell, and if it can, updates the board information and cannot place it. When you tell it to the user.

When accepting input, you often rely on pre-made features. Java uses the Scanner class. The details of the input are beyond the scope of the introduction and will not be dealt with here.

If you organize the operation of placing frames, you can see that it is made up of multiple elements.

--Receive input. --Check if you can place a frame. --Place a piece and turn it over.

Dividing complex problems makes it easier to understand. Here, we will consider the problem separately for each of the three elements as described above. Practice in order from the top of the element.

Practice 3 Receive the coordinates of the square on which the frame is placed as input.

The Scanner class is used to accept input. Refer to the official documentation (https://docs.oracle.com/javase/jp/8/docs/api/java/util/Scanner.html) for how to use the Scanner class.

Answer example

import java.util.Scanner;

class Othello {
    public static void main(String[] args) {
        int [][] borad = new int[8][8];

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                borad[i][j] = 0;
            }
        }

        borad[4][4] = 1;
        borad[4-1][4] = 2;
        borad[4][4-1] = 2;
        borad[4-1][4-1] = 1;

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                System.out.print(borad[i][j] + " ");
            }
            System.out.print("\n");
        }

        //Create an instance of the Scanner class
        //Standard input with arguments System.specify in
        Scanner scanner = new Scanner(System.in);

        //Message prompting for input
        System.out.print("Enter in the order of x y> ");
        int x = scanner.nextInt();
        int y = scanner.nextInt();
        
        //Display the entered contents on the screen
        System.out.println("x=" + x + " y="+y);

        //Close an instance of the Scanner class
        scanner.close();
    }
}

Practice 4 Check if you can place a frame. However, the frame to be placed is black (2).

Answer example

import java.util.Scanner;

class Othello {
    public static void main(String[] args) {
        int [][] borad = new int[8][8];

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                borad[i][j] = 0;
            }
        }

        borad[4][4] = 1;
        borad[4-1][4] = 2;
        borad[4][4-1] = 2;
        borad[4-1][4-1] = 1;

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                System.out.print(borad[i][j] + " ");
            }
            System.out.print("\n");
        }

        //Create an instance of the Scanner class
        //Standard input with arguments System.specify in
        Scanner scanner = new Scanner(System.in);

        //Message prompting for input
        System.out.print("Enter in the order of x y> ");
        int x = scanner.nextInt();
        int y = scanner.nextInt();
        
        //Display the entered contents on the screen
        System.out.println("x=" + x + " y="+y);

        //Range check
        if (0<x&&x<8 && 0<y&&y<8) {
            //Is the square open?
            if (borad[y][x] == 0) {
                //Eight-way list
                int[] dx = {-1,  0,  1,  1,  1,  0, -1, -1};
                int[] dy = {-1, -1, -1,  0,  1,  1,  1,  0};

                //Try eight directions in order
                for (int i=0; i<8; i++) {
                    //Next to the square to put(nx, ny)To
                    int nx = x+dx[i];
                    int ny = y+dy[i];

                    //Range check
                    if (0<nx&&nx<8 && 0<ny&&ny<8) {
                        //Whether there is a white top next to it
                        if (borad[ny][nx] == 1) {
                            //Search in the direction you are looking at the black frame
                            while (0<nx+dx[i]&&nx+dx[i]<8 && 0<ny+dy[i]&&ny+dy[i]<8) {
                                if (borad[ny][nx] == 2) {
                                    //OK
                                    System.out.println("OK");
                                    System.out.println("dx=" + dx[i] + " dy="+dy[i]);
                                }
                                nx += dx[i];
                                ny += dy[i];
                            }
                        }
                    }
                }
            }
        }

        //Close an instance of the Scanner class
        scanner.close();
    }
}

Practice 5 Place a piece and turn it over.

Answer example

import java.util.Scanner;

class Othello {
    public static void main(String[] args) {
        int [][] borad = new int[8][8];

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                borad[i][j] = 0;
            }
        }

        borad[4][4] = 1;
        borad[4-1][4] = 2;
        borad[4][4-1] = 2;
        borad[4-1][4-1] = 1;

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                System.out.print(borad[i][j] + " ");
            }
            System.out.print("\n");
        }

        //Create an instance of the Scanner class
        //Standard input with arguments System.specify in
        Scanner scanner = new Scanner(System.in);

        //Message prompting for input
        System.out.print("Enter in the order of x y> ");
        int x = scanner.nextInt();
        int y = scanner.nextInt();
        
        //Display the entered contents on the screen
        System.out.println("x=" + x + " y="+y);

        //Range check
        if (0<x&&x<8 && 0<y&&y<8) {
            //Is the square open?
            if (borad[y][x] == 0) {
                //Eight-way list
                int[] dx = {-1,  0,  1,  1,  1,  0, -1, -1};
                int[] dy = {-1, -1, -1,  0,  1,  1,  1,  0};

                //Try eight directions in order
                for (int i=0; i<8; i++) {
                    //Next to the square to put(nx, ny)To
                    int nx = x+dx[i];
                    int ny = y+dy[i];

                    //Range check
                    if (0<nx&&nx<8 && 0<ny&&ny<8) {
                        //Whether there is a white top next to it
                        if (borad[ny][nx] == 1) {
                            //Search in the direction you are looking at the black frame
                            while (0<nx+dx[i]&&nx+dx[i]<8 && 0<ny+dy[i]&&ny+dy[i]<8) {
                                if (borad[ny][nx] == 2) {
                                    //OK
                                    System.out.println("OK");
                                    System.out.println("dx=" + dx[i] + " dy="+dy[i]);

                                    
                                    while (x!=nx || y!=ny) {
                                        borad[y][x] = 2;
                                        x += dx[i];
                                        y += dy[i];
                                    }
                                }
                                nx += dx[i];
                                ny += dy[i];
                            }
                        }
                    }
                }
            }
        }

        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                System.out.print(borad[i][j] + " ");
            }
            System.out.print("\n");
        }

        //Close an instance of the Scanner class
        scanner.close();
    }
}

It is said that code with complicated structure due to overlapping branches and loops is not beautiful.

Divide the program

It should be easy to operate, but the code to express it has become complicated. You can play Othello by repeating this operation, but it is troublesome and a source of mistakes. Java (and most other languages) has the ability to group and name the same things.

Putting the same process together makes it easier to write repetitions. In Java, it is called a method, and it is also called a function or subroutine. Aim to complete Othello using the method. The pieces are placed alternately, and if they cannot be placed, the victory or defeat is displayed.

Practice 6 Completion of Othello. However, white and black are input alternately, and the input method is free.

Answer example

import java.util.Scanner;

import sun.launcher.resources.launcher;

class Othello {
    static boolean turn(int player, int x, int y, int[][] borad, boolean check) {
        int opponent = 1;
        if (player == 1) {
            opponent = 2;
        }
        boolean res = false;

        //Range check
        if (0<x&&x<8 && 0<y&&y<8) {
            //Is the square open?
            if (borad[y][x] == 0) {
                //Eight-way list
                int[] dx = {-1,  0,  1,  1,  1,  0, -1, -1};
                int[] dy = {-1, -1, -1,  0,  1,  1,  1,  0};

                //Try eight directions in order
                for (int i=0; i<8; i++) {
                    //Next to the square to put(nx, ny)To
                    int nx = x+dx[i];
                    int ny = y+dy[i];

                    //Range check
                    if (0<nx&&nx<8 && 0<ny&&ny<8) {
                        //Whether there is a white top next to it
                        if (borad[ny][nx] == opponent) {
                            //Search in the direction you are looking at the black frame
                            while (0<nx+dx[i]&&nx+dx[i]<8 && 0<ny+dy[i]&&ny+dy[i]<8) {
                                if (borad[ny][nx] == player) {
                                    //OK
                                    res = true;
                                    
                                    if (!check) {
                                        System.out.println("OK");
                                        System.out.println("dx=" + dx[i] + " dy="+dy[i]);
                                        while (x!=nx || y!=ny) {
                                            borad[y][x] = player;
                                            x += dx[i];
                                            y += dy[i];
                                        }
                                    }
                                    
                                }
                                nx += dx[i];
                                ny += dy[i];
                            }
                        }
                    }
                }
            }
        }
        return res;
    }

    static void print_borad(int[][] borad) {
        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                System.out.print(borad[i][j] + " ");
            }
            System.out.print("\n");
        }
    }
    
    static boolean can_put(int[][] borad, int player) {
        boolean res = true;
        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                res &= turn(player, i, j, borad, true);
            }
        }

        return res;
    }

    static int[][] init() {
        int [][] borad = new int[8][8];
        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                borad[i][j] = 0;
            }
        }

        borad[4][4] = 1;
        borad[4-1][4] = 2;
        borad[4][4-1] = 2;
        borad[4-1][4-1] = 1;

        print_borad(borad);

        return borad;
    }
    public static void main(String[] args) {
        int [][] borad = init();

        int player = 2;
        boolean is_game_end = false;
        //Create an instance of the Scanner class
        //Standard input with arguments System.specify in
        Scanner scanner = new Scanner(System.in);
        int x, y;
        while (!is_game_end) {
            //Message prompting for input
            System.out.println("Player = " + player);
            System.out.print("Enter in the order of x y> ");
            x = scanner.nextInt();
            y = scanner.nextInt();
            
            //Display the entered contents on the screen
            System.out.println("x=" + x + " y="+y);
            if (turn(player, x, y, borad, false)) {          
                if(player == 2) player = 1;
                else player = 2;
                is_game_end = can_put(borad, player);

                print_borad(borad);
            } 
        }
        

        //Close an instance of the Scanner class
        scanner.close();

        int black = 0, white = 0;
        for (int i=0; i<8; i++) {
            for (int j=0; j<8; j++) {
                if (borad[i][j] == 1) {
                    white++;
                } else if (borad[i][j] == 2) {
                    black++;
                }
            }
        }
        if (black>white) {
            System.out.println("Black wins");
        } else if(black<white) {
            System.out.println("White wins");
        } else {
            System.out.println("draw");
        }
    }
}

Uno implementation

Editing now

User-defined type

Access control

Inheritance, run-time polymorphism

Benefits of object-oriented programming

At the end

Reference material

Recommended Posts

Introduction to Practical Programming
Get started with "Introduction to Practical Rust Programming" (Day 3)
Introduction to Functional Programming (Java, Javascript)
Introduction to Programming for College Students: Introduction
Introduction to Ruby 2
Introduction to SWING
Introduction to Micronaut 1 ~ Introduction ~
[Java] Introduction to Java
Introduction to migration
Introduction to java
Introduction to Doma
Introduction to Programming for College Students: Variables
Introduction to Docker / Kubernetes Practical Container Development
Introduction to JAR files
Introduction to Ratpack (8)-Session
Introduction to RSpec 1. Test, RSpec
Introduction to bit operation
Introduction to Ratpack (6) --Promise
Introduction to Ratpack (9) --Thymeleaf
Introduction to PlayFramework 2.7 ① Overview
Introduction to Android Layout
Introduction to design patterns (introduction)
Introduction to kotlin for iOS developers ⑤-Practical XML
Introduction to javadoc command
Introduction to jar command
Introduction to Ratpack (2)-Architecture
Introduction to lambda expression
Introduction to java command
Introduction to RSpec 2. RSpec setup
Introduction to Keycloak development
Introduction to javac command
Introduction to programming for college students (updated from time to time)
Introduction to Programming for College Students: Making a Canvas
Introduction to Design Patterns (Builder)
Introduction to RSpec 5. Controller specs
Introduction to RSpec 6. System specifications
Introduction to RSpec 3. Model specs
Introduction to Ratpack (5) --Json & Registry
Introduction to Metabase ~ Environment Construction ~
Introduction to Ratpack (7) --Guice & Spring
(Dot installation) Introduction to Java8_Impression
Introduction to Design Patterns (Composite)
Introduction to Micronaut 2 ~ Unit test ~
Introduction to JUnit (study memo)
Introduction to Spring Boot ① ~ DI ~
Introduction to design patterns (Flyweight)
[Java] Introduction to lambda expressions
Introduction to Spring Boot ② ~ AOP ~
Introduction to Apache Beam (2) ~ ParDo ~
[Ruby] Introduction to Ruby Error statement
Introduction to EHRbase 2-REST API
Introduction to design patterns Prototype
GitHub Actions Introduction to self-made actions
[Java] Introduction to Stream API
Introduction to Design Patterns (Iterator)
Introduction to Spring Boot Part 1
Introduction to Ratpack (1) --What is Ratpack?
XVim2 introduction memo to Xcode12.3
Introduction to RSpec-Everyday Rails Summary-
Introduction to Design Patterns (Strategy)
[Introduction to rock-paper-scissors games] Java