python to create digital Huarongdao game

This article will use python to create a digital Huarong Road game

All standard libraries are used, no need to use third-party libraries, just copy and run.

Use wasd or move up, down, left, and right. When the numbers form an orderly combination, you can pass the level.

The source code is as follows:
#Production: Pet

import tkinter as tk
from tkinter.ttk import *
from random import *
from tkinter import messagebox

row_of_space = 0
col_of_space = 0

class Digital_Huarong_Road():
    """Digital Huarong Road Class"""
    
    def __init__(self):
        self.main()

    def Game_window(self,Difficulty,big):
        """Game Window"""
        global row_of_space
        global col_of_space
        
        Game=tk.Tk()
        Game.title("Digital Huarong Road-Difficulty Level %s"%Difficulty)
        if Difficulty<=5:
            Game.geometry("260x260 + 300 + 300")
        else:
            Game.geometry("%sx%s + 300 + 300"%(Difficulty*52,Difficulty*52))

        #background color
        Game["background"]="snow"
        
        #Game.resizable(0,0)

        row_of_space = 0 #Storage row number of blank button
        
        col_of_space = 0 #Column number to store blank button
        
        buttons = {} #Array to store number buttons
        
        numbers = [ num for num in range(1,Difficulty**2) ] #Use list comprehension to list all numbers

        numbers.append(" ") #Add a blank character
        
        shuffle(numbers) #Shuffle the order of numbers in the number list
        
        """Manufacturing Digital Huarongdao Square Array"""
        for row in range(Difficulty):
            for col in range(Difficulty):
                button = tk.Button(Game,bg = "#F2F3D6",fg = "black",font = ("楷体",big))
                buttons[row,col] = button #Import buttons into array
                button["text"] = numbers.pop() #Set the text on the button

                if Difficulty<=5:
                    button.place(relx = 0 + col * 52 / 260, rely = 0 + row * 52 / 260, relwidth = 50 / 260, relheight = 50 / 260) #Set the number button size
                else:
                    a = Difficulty * 52
                    button.place(relx = 0 + col * 52 / a,rely = 0 + row * 52 / a,relwidth = 50 / a,relheight = 50 / a) #Set the number button size

                if button["text"] == " ": #Determine whether it is a blank button. If so, record the row and column number variable of the blank button.
                    row_of_space = row
                    col_of_space = col

        #Restore list
        numbers = [ num for num in range(1,Difficulty**2) ]
        numbers.append(" ")

        def Restart_the_game(Difficulty,big):
            """Restart the game and execute this function when the game is won"""
            if messagebox.askyesno("Victory","You have won, do you want to restart the game"):
                Game.destroy()
                self.Game_window(Difficulty,big)
            else:
                Game.destroy()

        def up(event):
            """Keyboard Events-Up"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is at the bottom, jump out of the function.
            if row_of_space==Difficulty-1:
                return

            #Swap button position
            buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space + 1,col_of_space]["text"]
            buttons[row_of_space + 1,col_of_space]["text"] = " "
            row_of_space + = 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)

        def Down(event):
            """Keyboard Events-Down"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is at the bottom, jump out of the function.
            if row_of_space==0:
                return

            #Swap button position
            buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space-1,col_of_space]["text"]
            buttons[row_of_space-1,col_of_space]["text"] = " "
            row_of_space -= 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)

        def Left(event):
            """Keyboard Event-Left"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is on the leftmost layer, jump out of the function.
            if col_of_space==Difficulty-1:
                return

            #Exchange button positions
            buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space,col_of_space + 1]["text"]
            buttons[row_of_space,col_of_space + 1]["text"] = " "
            col_of_space + = 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)

        def Right(event):
            """Keyboard Event-Right"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is on the rightmost layer, jump out of the function.
            if col_of_space==0:
                return

            #Swap button position
            buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space,col_of_space-1]["text"]
            buttons[row_of_space,col_of_space-1]["text"] = " "
            col_of_space -= 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)

        def Control_up(event):
            """Keyboard Events - Column"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is at the bottom, jump out of the function.
            if row_of_space==Difficulty-1:
                return

            #Swap button position
            for i in range(Difficulty):
                if row_of_space==Difficulty-1:
                    return
                else:
                    buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space + 1,col_of_space]["text"]
                    buttons[row_of_space + 1,col_of_space]["text"] = " "
                    row_of_space + = 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)

        def Control_Down(event):
            """Keyboard events-column"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is at the bottom, jump out of the function.
            if row_of_space==0:
                return

            #Swap button position
            for i in range(Difficulty):
                if row_of_space==0:
                    return
                else:
                    buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space-1,col_of_space]["text"]
                    buttons[row_of_space-1,col_of_space]["text"] = " "
                    row_of_space -= 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)

        def Control_Left(event):
            """Keyboard Events-Column Left"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is at the bottom, jump out of the function.
            if col_of_space==Difficulty-1:
                return

            #Swap button position
            for i in range(Difficulty):
                if col_of_space==Difficulty-1:
                    return
                else:
                    buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space,col_of_space + 1]["text"]
                    buttons[row_of_space,col_of_space + 1]["text"] = " "
                    col_of_space + = 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)

        def Control_Right(event):
            """Keyboard Events-Column Right"""
            global row_of_space
            global col_of_space

            #First judge the blank position. If the blank position is at the bottom, jump out of the function.
            if col_of_space==0:
                return

            #Swap button position
            for i in range(Difficulty):
                if col_of_space==0:
                    return
                else:
                    buttons[row_of_space,col_of_space]["text"] = buttons[row_of_space,col_of_space-1]["text"]
                    buttons[row_of_space,col_of_space-1]["text"] = " "
                    col_of_space -= 1

            n = 0
            for row in range(Difficulty):
                for col in range(Difficulty):
                    #Compare all button sequences to see if they are correct. If not, jump out of the function.
                    if buttons[row,col]["text"] != numbers[n]:
                        return
                    n + = 1
            #If all buttons are judged, the game will be won.
            Restart_the_game(Difficulty,big)


        #Bind keyboard events to the window
        Game.bind("<KeyPress-Up>",up)
        Game.bind("<KeyPress-Down>",Down)
        Game.bind("<KeyPress-Left>",Left)
        Game.bind("<KeyPress-Right>",Right)
        Game.bind("<KeyPress-w>",up)
        Game.bind("<KeyPress-s>",Down)
        Game.bind("<KeyPress-a>",Left)
        Game.bind("<KeyPress-d>",Right)

        #Bind shortcut window
        Game.bind("<Control-Up>",Control_up)
        Game.bind("<Control-Down>",Control_Down)
        Game.bind("<Control-Left>",Control_Left)
        Game.bind("<Control-Right>",Control_Right)
        Game.bind("<Control-w>",Control_up)
        Game.bind("<Control-s>",Control_Down)
        Game.bind("<Control-a>",Control_Left)
        Game.bind("<Control-d>",Control_Right)
        
        Game.mainloop()
        
    def main(self):
        """Main window function"""
        root=tk.Tk()
        root.title("Digital Huarong Road")
        root.geometry("400x300 + 300 + 300")
        root.resizable(0,0)

        def Start(defDifficult):
            """Start challenging the transfer function"""
            root.destroy()
            if defDifficult>10:
                self.Game_window(defDifficult,23)
            else:
                self.Game_window(defDifficult,30)
            self.main()

        #Create canvas
        cv=tk.Canvas(root,bg="snow")
        cv.place(x=0,y=0,width=400,height=300)
        #create title
        cv.create_text(200,30,text="Digital Huarongdao",fill="black",font=("华文新伟",30,"bold"))
        #difficulty text
        cv.create_text(110,200,text="Difficulty:",fill="black",font=("华文新伟",18))
        cv.create_text(310,200,text="level",fill="black",font=("华文新伟",18))
        #make
        cv.create_text(280,287,text="Production: Pet",activefill="red",fill="black",font=("华文新伟",12))

        def input_validation(content):
            """Input verification function"""
            if content.isdigit() or content == "":
                if content=="":
                    start.config(state="disabled")
                    return True
                elif int(content)>20:
                    if int(content)>=3 and int(content)<=20:
                        start.config(state="normal")
                    return False
                else:
                    if int(content)<3:
                        start.config(state="disabled")
                    else:
                        start.config(state="normal")
                    return True
            else:
                try:
                    if int(content)>=3 and int(content)<=20:
                        start.config(state="normal")
                except:
                    start.config(state="normal")
                else:
                    if int(content)<3:
                        start.config(state="disabled")
                return False

        def gamerules():
            rule=tk.Toplevel(root)
            rule.title("Game Rules")
            rule.transient(root)
            rule.geometry("810x650 + 300 + 300")
            rule.resizable(0,0)

            tk.Label(rule,text="Game introduction:\\
Huarong Dao is an ancient Chinese folk puzzle game. It is called "Huarong Dao" by foreign intelligence experts together with Rubik's Cube and Independent Diamond because of its variety and endless playability. "Three incredible things in the world of intellectual games." It is also synonymous with traditional Chinese educational toys such as jigsaw puzzles and nine-link puzzles, called "Chinese puzzles."",font=("华文新伟",15) ,justify="left",wraplength=800).place(x=0,y=0)
            tk.Label(rule,text="The Huarong Dao game is taken from the famous Three Kingdoms story. Cao Cao was defeated by Liu Bei and Sun Quan's "bitter flesh strategy" and "iron ropes and boats" in the Battle of Chibi, and was forced to retreat to Huarong Dao. Encountering Zhuge Liang's ambush again, in order to repay Cao Cao's kindness to him, Guan Yu made concessions and finally helped Cao Cao escape from Huarong Road. The game is based on "Cao Cao was defeated and fled to Huarong, and he met Guan Gong on a narrow road. Just for There is a story line about “a great kindness, let go of the golden lock and run away with the dragon”, but the origin of this game is not “one of the oldest games in China” as most people think. In fact, its history may be very short.\ nThe current style of Huarong Road was patented by John Harold Fleming in the UK in 1932, and the solution for Heng Dao Li Ma\\
 is also attached.",font=("华文新伟",15),justify= "left",wraplength=800).place(x=0,y=100)
            tk.Label(rule,text="Game rules:\\
Digital Huarong Road is a puzzle game. Its rules are very simple, but it requires a certain amount of thinking ability and patience. Let's learn more about Digital Huarong Road The rules of the game. \\
The goal of the game of Number Huarong Road is to arrange all the numbers on the game board in order from small to large. The game board is usually a 4x4 square grid with 15 numbers and a space.\ nThe rules of the game are very simple. Players need to move the numbers to arrange them in order from small to large. The way to move the numbers is to exchange the positions of the numbers and spaces. Only adjacent numbers and spaces can exchange positions.\\
Number Huarong Dao may seem simple, but to win in the game, certain skills and strategies are required.\\
\\
The difficulty of Digital Huarong Dao can be adjusted according to the size of the game panel. Generally, the larger the size of the game panel , the more difficult the game is. For example, a 5x5 game board is more difficult than a 4x4 game board\\
\\
Digital Huarong Road is a very interesting puzzle game that can exercise the player's thinking ability and Be patient. If you haven't tried Digital Huarong Road, give it a try, I believe you will like it.",font=("华文新伟",15),justify="left", wraplength=800).place(x=0,y=260)
            tk.Label(rule,text="Move keys:\\
Single movement: use the direction keys up, down, left, left/wasd keys to achieve a single move\\
Whole row/column movement: use control + movement keys (i.e. up, down, left, left/wasd ) to achieve entire row/column movement",font=("华文新伟",15),justify="left",wraplength=800).place(x=0,y=570)

            #Enable login window
            def enable_window():
                root.attributes("-disabled", 0)
                rule.destroy()

            #Disable login window
            root.attributes("-disabled", 1)
            rule.protocol("WM_DELETE_WINDOW",enable_window)
            
        
        #Difficulty input box
        input_validate=root.register(input_validation) #Input verification
        Difficult=tk.Entry(root,font=("Arial",18),validate="all",vcmd=(input_validate,"%P"),justify="center",bd =0,bg="snow")
        Difficult.place(x=130,y=188,width=170,height=21)

        #Draw the underline of the input box
        cv.create_line(130,210,300,210,width=2)

        #start button
        start=Button(root,text="Start Challenge",takefocus=False,state="disabled",command=lambda:Start(int(Difficult.get())))
        start.place(x=53,y=230,width=290,height=40)

        #illustrate
        tk.Label(root,text="Chinese folk puzzle games\\
Exercise players' thinking ability and patience",font=("华文新伟",14),bg="snow") .place(x=85,y=80)
        tk.Label(root,text="Can you pass the level?",font=("华文新伟",14),bg="snow").place(x=10,y=275 )

        #game rules
        Game_Rules=tk.Button(root,text="Game Rules",font=("华文新伟",12),bd=0,bg="snow",activebackground="snow" ,cursor="hand2",takefocus=False,command=gamerules)
        Game_Rules.place(x=335,y=280,width=60,height=15)

        root.mainloop()

        


Digital_Huarong_Road()
The running results are as follows:

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeHomepageOverview 382146 people are learning the system