SoFunction
Updated on 2024-10-30

Python based implementation of the game of backgammon

In this article, we share the example of Python to achieve the specific code of the game of backgammon, for your reference, the details are as follows

Knowing the rules of the game is the first thing we need to do, and if we don't know the rules, then we certainly can't move an inch.

Rules of the game of backgammon:

1. Each player in the game has a piece of one color.
2. Empty board opening.
3. Black first, white second, alternating moves, only one move at a time.
4. A piece is placed on a blank point on the board, and after it has been placed, it may not be moved to another point, removed from the board or picked up and placed elsewhere.
5. Black's first disc may be played at any intersection of the board.
6. Taking turns is the right of both players, but either player is allowed to waive the right to play (i.e., the right to PASS).

In the game of Backgammon, the rules of Black's designated opening, three exchangeable moves, and five two-player moves are enforced. Throughout the game Black has forbidden moves and White has no forbidden moves. Black's forbidden moves are 3-3, 4-4, and long-link.

In this blog we have only implemented the simpler rules, disregarding Rule 6 and the banning of hands (personal ability is limited, if there are friends who are willing to study it, we can study it together /hugs).

Design Idea.

1, first of all we need to use the interface, we first analyze the interface need to achieve what the screen, that is, we want to carry out this game of backgammon to see what. To see: the board, the pieces (the pieces should be divided into colors, black and white), these are necessary to play the game to see.

2、After the appearance is done we need to think about the filling of the internal code and think:

① how the pieces fall into the designated positions.
② How to realize alternating discs, alternating colors, and keeping records for calculating the arrangement of the discs.
(iii) How to count the number of pieces of the same color in four directions to reach the winning position.

First bring up the window and implement the code:

from tkinter import *#Import Window third-party libraries
root = Tk()       #Creating windows
("Backgammon made by Bean.")  #Window name
w1 = Canvas(root, width=600,height=600,background='lightcyan')# Create a canvas in the center of the window, root is the window, width 600, height 600, background color lightcyan
()    #Layout approach, global needs to be harmonized.
mainloop()

A backgammon board is made up of 15 horizontal lines and 15 vertical lines.

Draw the board:

for i in range(0, 15):
    w1.create_line(i * 40 + 20, 20, i * 40 + 20, 580)
    w1.create_line(20, i * 40 + 20, 580, i * 40 + 20)
w1.create_oval(135, 135, 145, 145,fill='black')
w1.create_oval(135, 455, 145, 465,fill='black')
w1.create_oval(465, 135, 455, 145,fill='black')
w1.create_oval(455, 455, 465, 465,fill='black')
w1.create_oval(295, 295, 305, 305,fill='black')

The coordinates of the upper left corner of the window is (0, 0), through debugging, we came up with the starting position for (20, 20) is more appropriate, many debugging for comparison, I choose the line spacing of 40 is better. Of course, the line width, the size of the circle, the spacing of the board lines can be adjusted, you can slowly explore (h_h). The five black dots in the board need to be calculated to find their positions.
create_line (start, end): draws a straight line
create_oval(x1,y1,x2,y2,fill='color')this is to draw a tangent circle, the upper left corner of the rectangle (x1,y1), the lower right corner of the rectangle (x2,y2) fill for the fill color, we can find turtle color library from the Internet, by the way, to help people find a Choose your own favorite color.

Rendering:

The board is ready, we start to design the drop, here need to alternate the color change, then we need to go through a judgment method to change the color of the pieces. I think of two kinds: ① one is to use the character to mark the current mouse on the color of the pieces, change to another. The other is to change the color by counting. In addition to this, we need to make it so that no piece can be placed in a position where a piece has already been placed, i.e., we need to determine if there is a piece in the current position before placing a piece.

num=0        # Calculate how many pieces are on the board and use it to determine the color of the next piece.
A=((15,15),0    )        #Matrix of existing pieces in storage locations
B=((15,15),'')        # Used to record the color of the pieces in each position
def callback(event):        # The input is the click event, and is the location of the mouse click event
    global num ,A            # Global variables can be used globally
    for j in range (0,15):    The #double loop locates the nearest intersection of the grid lines (i, j) at the clicked position, ensuring that the piece falls at the intersection of the lines.
        for i in range (0,15):
            if ( - 20 - 40 * i) ** 2 + ( - 20 - 40 * j) ** 2 <= 2 * 20 ** 2:
                break
        if ( - 20 - 40 * i) ** 2 + ( - 20 - 40 * j) ** 2 <= 2*20 ** 2:
            break
    if num % 2 == 0 and A[i][j] != 1:#Judge the color of the piece now.
        w1.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='black')
        A[i][j] = 1
        B[i][j] = 'b'
        num += 1
    if num % 2 != 0 and A[i][j] != 1 :
        w1.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='white')
        A[i][j] = 1
        B[i][j] = 'w'
        num += 1

After the fall of the need to calculate whether the five pieces in a row, the direction of calculation of each piece there are eight to form four lines, then it is from the fall of the first to one end of the calculation, until the encounter with another color of the pieces, the reverse query encountered in another color of the pieces out of the stop, when it reaches the five pieces, that is, on behalf of a party to win, or else the cycle of the next line. When the end of the four lines have not reached the victory conditions, you can continue to drop.

f = [[-1, 0], [-1, 1], [0, 1], [1, 1]] #The pattern of change of coordinates of one of the four lines in one direction
    for z in range(0, 4):                 #Cyclic direction
        a, b = f[z][0], f[z][1]
        count1, count2 = 0, 0
        x, y = i, j
        while B[x][y] == B[i][j]:#Calculate when colors are the same
            count1 += 1
            if x + a > 0 and y + b > 0 and x + a < 15 and y + b < 15 and B[x + a][y + b] == B[i][j]:# Make sure you don't go beyond the boundaries of the matrix, or you'll get an error!
                [x, y] = ([x, y]) + ([a, b])
            else:
                x, y = i, j     
                break
        while B[x][y] == B[i][j]:# Count the number of pieces of the same color backwards from the drop.
            count2 += 1
            if x - a < 15 and y - b < 15 and x - a > 0 and y - b > 0 and B[x - a][y - b] == B[i][j]:
                [x, y] = ([x, y]) - ([a, b])
            else:
                break
        if count1 + count2 == 6:            #Calculated two drops
            if B[i][j] == 'b':
                ('Hints', "Black wins.)
            else:
                ('Hints', "White wins.)

Click event, after each click you need to make a drop and game over judgment. The function is called to make a drop and determine if the game is over.

("<Button -1>",callback)
()

Set the Exit button:

u=Button(root,text="Exit.",width=10,height=1,command=quit,font=('italicized',15))
()

Full Code:

from tkinter import *
import   # popup library
import numpy as np

root = Tk()                                 #Creating windows
("Backgammon made by Bean.")                  #Window name
w1 = Canvas(root, width=600,height=600,background='lightcyan')
()

for i in range(0, 15):
    w1.create_line(i * 40 + 20, 20, i * 40 + 20, 580)
    w1.create_line(20, i * 40 + 20, 580, i * 40 + 20)
w1.create_oval(135, 135, 145, 145,fill='black')
w1.create_oval(135, 455, 145, 465,fill='black')
w1.create_oval(465, 135, 455, 145,fill='black')
w1.create_oval(455, 455, 465, 465,fill='black')
w1.create_oval(295, 295, 305, 305,fill='black')

num=0
A=((15,15),0)
B=((15,15),'')
def callback(event):
    global num ,A
    for j in range (0,15):
        for i in range (0,15):
            if ( - 20 - 40 * i) ** 2 + ( - 20 - 40 * j) ** 2 <= 2 * 20 ** 2:
                break
        if ( - 20 - 40 * i) ** 2 + ( - 20 - 40 * j) ** 2 <= 2*20 ** 2:
            break
    if num % 2 == 0 and A[i][j] != 1:
        w1.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='black')
        A[i][j] = 1
        B[i][j] = 'b'
        num += 1
    if num % 2 != 0 and A[i][j] != 1 :
        w1.create_oval(40*i+5, 40*j+5, 40*i+35, 40*j+35,fill='white')
        A[i][j] = 1.
        B[i][j] = 'w'
        num += 1

    f = [[-1, 0], [-1, 1], [0, 1], [1, 1]]
    for z in range(0, 4):
        a, b = f[z][0], f[z][1]
        count1, count2 = 0, 0
        x, y = i, j
        while B[x][y] == B[i][j]:
            count1 += 1
            if x + a > 0 and y + b > 0 and x + a < 15 and y + b < 15 and B[x + a][y + b] == B[i][j]:
                [x, y] = ([x, y]) + ([a, b])
            else:
                x, y = i, j
                break
        while B[x][y] == B[i][j]:
            count2 += 1
            if x - a < 15 and y - b < 15 and x - a > 0 and y - b > 0 and B[x - a][y - b] == B[i][j]:
                [x, y] = ([x, y]) - ([a, b])
            else:
                break
        if count1 + count2 == 6:
            if B[i][j] == 'b':
                ('Hints', "Black wins.)
            else:
                ('Hints', "White wins.)

("<Button -1>",callback)
()
def quit():
    ()

u=Button(root,text="Exit.",width=10,height=1,command=quit,font=('italicized',15))
()

mainloop()

Not technically proficient, but like to do a little research, find the joy of playing from learning, willing to learn and play with everyone.

This is the entire content of this article.