One of my classmates wanted to do a backgammon interview, so I took out the code I wrote before, but there was a bug, so I redid it.

The code is just a simple implementation, but enough to interview, by the way, write an article to explain the idea and code in detail.

The Demo & source

Single machine Demo

Standalone Demo source online Demo source code

Standalone version details

1. Board layout

A chessboard (square) is made up of squares, and the pieces can be placed at the intersection of vertical and horizontal lines. The chessboard is basically like this

Use an empty label as a square and the pseudo-element “before after” as a horizontal and vertical center line to form a cross

Then a line of labels is arranged, and a label is added where a newline is needed. The pseudocode is as follows,

// square checkerboard with length and width 11Copy the code

Checkerboard code

2. Coordinate initialization

For each subsequent move, you need to know the position of the specific piece, so add coordinates to all positions on the board

Since it is a two-dimensional checkerboard, you only need to initialize the coordinate information for each position with two nested loops, length and width, and store them in the Pieces object, and you can initialize the middle pieces as black pieces.

The key of each coordinate object is the (x,y) coordinate value, and the value is the information of the pieces in the current coordinate (W: white b: black).

3.1, move later

This step is easy because each coordinate initializes the data, so add the listening TICK method

Copy the code

3.2, take back,

This is an extra function, add a state last to store the coordinates of each step, to repent the move, directly empty the data of the coordinates of the previous step.

4. Judge the winner

This is the core of gobang, relatively is also the most troublesome, every move (coordinates X, Y), need from ** horizontal, vertical, \ to, / to ** four direction of the other pieces to judge the result.

The transverse vertical

These two directions are very simple, from the most left and the most top of the coordinates to judge whether and the current child color is the same, consecutive 5 is the winner.

Direction of \

First calculate the coordinates (_x,_y) in the \ direction after moving x(Max. 5) back to the upper left from the current subpoint

Then start from (_x,_y) and use the for loop to compare each coordinate one by one in the direction of the lower right corner. The loop length is the maximum number of pieces in this direction (in fact, the maximum number of pieces can be judged five times, there will be extra coordinates beyond the board into the loop, small details, not modified for the time being).

/ direction

/ is the mirror image of \

Similarly, calculate the coordinates of x (Max. 5) positions backward from the current locating point to the lower left, and then compare them one by one in the upper right direction. Judge the result according to whether there are 5 consecutive same chess pieces in this direction

The online version

Each online user can be a host and can enter the socket. ID of another host to match

Here WebSocket uses socket. IO to communicate.

The service side

Const players = {} // Mapping between sid and socket object ID :socket const relations = {} // Mapping between each player and opponent ID1: ID2 ID2: ID1Copy the code

The Players object stores the mapping between siDs and socket objects for each player. The relations object stores the mapping between each player and his opponent

Only two events are used here: Link and tick

  • Link is used to monitor the connection between a user and a host. After the connection is successful, the user relationship is stored and the user relationship is notified
  • Tick Monitors the event of a chess match played by any user, receives all coordinates and match information, and notifies the opponent

The client

Client listens for connection events and drop-off events (tick-back)

The client sends a link event to connect to the host and sends a TICK event to synchronize the drop and coordinate information (for convenience, no websocket communication failure handling was added).

The entire client code is relatively simple, directly posted

Const socket = IO. Connect ('http://127.0.0.1:8888') socket. On ('connect', () => {this.socket = socket}) socket.on('linked', () => {alert(' host connected successfully, ')}) socket.on('linkOK', () => {alert(' link to host successfully, Player = 0 this.canPlay = true}) // Data is returned to socket.on('tick-back', d => { const data = JSON.parse(d) this.pieces = data.pieces; this.canPlay = true if(data.gameOver){ alert('game over') } })Copy the code

The last

This is a demo for the group of students to provide interview questions, mainly look at the idea, unavoidably many details did not deal with, bug more…


Did this article help you? Welcome to join the front End learning Group wechat group: