【Python】超简单的华容道小游戏制作+保姆级讲解(附源码)

本文介绍了一种使用Python实现华容道游戏的方法,包括游戏数据构建、初始化、界面输出等功能,详细解释了游戏逻辑和控制流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

华容道游戏是一个历史悠久的经典游戏,玩法就是将已经打乱的数字重新调整顺序,使其成为正序排列

正好昨天一个朋友的python老师留下了这道华容道的题目,今天就来学习一下吧

注意!!!

以下内容不包含多类库或者框架等多种小白难以接受的知识,所以很适合刚刚开始学编程的同学

话不多说,我们开始吧!

①游戏数据的构建

假设你想玩一个n阶的数字华容道,那么展示在你面前的将是n*n个数字方块,意味着我们要生成n*n个内存来储存数据

在C++中我们用int指针数组储存这n*n个数据,在python中我们也沿袭,用列表来储存这n*n个数据

创建列表对象👇

array=[]   #创建列表对象

那么n从哪里来呢,当然是玩家输入啊,所以我们用一个名为index变量来记录玩家输入的阶数(有大用处)

其次我们还需要设置一个简单的纠错机制来保证输入的阶数合法👇

index=0   #初始化index,使它为int整型变量
while index <= 0:   #进入while循环
    print("请输入阶数:")
    index=int(input(index))   #input输入进来的是str类型,需要转换成int类型
    if type(type(index)==int and index >0):   #要求输入的是个整数,并且阶数大于0
        break   #如果是合法输入,则跳出循环

②游戏数据初始化

这一步的关键问题使——如何随机生成一组0~index**2(index**2=index*index)的随机数值,并且保证不重复

大部分人(包括我)第一时间想到的是把生成的随机数直接赋值给列表元素,但如果那样一定会重复

不妨先生成一个顺序的表,让array[0]='0',array[1]='1',array[2]='2'…………,其中的0就是‘空’

然后再把它们打乱,怎么打乱呢?我的做法是让array里的元素与array列表中随机一个元素互换数值,换来换去就变成一组不重复的随机数了👇

import random   #加载random库
for i in range(index**2):   #初始化成顺序值
    array.append(str(i))   #把顺序值添加进array列表,注意类型转换成str
for i in range(index**2):   #交换变量
    pos=random.randint(0,index**2-1)   #确定交换的位置
    x=array[i]   #x是中间变量
    array[i]=array[pos]   
    array[pos]=x

random库里的randint()函数可以生成指定范围内的int随机数

random.randint(0,index**2-1)可以生成[0,index**2-1]范围随机数

随机数问题可以参考这篇博客

③函数speak()输出游戏界面

我们想要的界面是这样的👉

array列表里有index*index个数据,我们需要逐个输出他们,并且每输出index个变量就要换行👇

def speak():
    for i in range(index**2):
        if array[i]=='0':   #如果变量值是0,输出空格
            print("".ljust(4),end="")   #end避免了自动换行
        else:
            print(array[i].ljust(4),end="")   
        if(i%index==index-1):   #确定换行条件
            print("\n")

这里的str.ljust(4)是字符串输出填充函数,就是在输出时会自动填充成4个字符

如果array[i]是'7',输出的是'   7'(前面填充了3个空格)

如果array[i]是'14',输出的是'  14'(前面填充了2个空格)

填充函数问题可以参考这篇博客

④函数isCorrect()判断游戏是否结束

不妨先来想一想,什么时候游戏可以判定为结束?是不是这样(假设index=2)

那就是除了最后一个元素外,array[0]=1,array[1]=2,array[2]=3…………array[i]=i+1

如果条件达到,返回布尔值True表示游戏结束,反之则返回False表示游戏未结束👇

def isCorrect():
    for i in range(index**2-1):
        if array[i]!=str(i+1):
            return False
    return True

⑤函数whereBlank()寻找'0'(空白格)

这个函数用于逐个检索array列表中的元素,找到值为'0'的元素,并返回它的下标(也就是地址)

def whereBlank():
    for i in range(index**2):
        if array[i]=='0':
            return i

⑥函数move()进行数字移动

在这个函数里,我们要接收玩家的操作数据,不妨规定↑(w)↓(s)←(a)→(d)

移动的过程实质上是一个变量交换的过程,和前面一样,定义一个x作为中间变量进行相似操作

这一步最关键地方在于如何设立纠错机制

(s)向下移动,空白格的上方格子必须在界面内,即(whereBlank() - index) >= 0

(w)向上移动,空白格的下方格子必须在界面内,即(whereBlank() + index) < index**2

(d)向右移动,空白格左侧格子必须在界面内,即(whereBlank() - 1) >= 0,而且必须与它相邻(不可以跨行移动),即whereBlank() % index != 0

(a)向左移动,空白格右侧格子必须在界面内,即(whereBlank() + 1) < index**2,而且必须与它相邻(不可以跨行移动),即whereBlank() + 1) % index != 0

我使用了双重否定的while条件判断式,即只要有一个达到正确输入的条件,循环就会结束👇

def move():
    option=''   #定义字符串变量option
    #输入纠错机制
    while ((option == 's' and (whereBlank() - index) >= 0) or (option == 'w' and (whereBlank() + index) < index**2) or (option == 'd' and (whereBlank() - 1) >= 0 and whereBlank() % index != 0) or (option == 'a' and (whereBlank() + 1) < index**2 and (whereBlank() + 1) % index != 0))==False:
        print("请输入移动方向↑(w)↓(s)←(a)→(d)——",end="")
        option=input(option)   #input本身就是str,无需类型转换
    if option=='w':   #向上移动
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos+index]
        array[pos+index]=x
    elif option=='s':   #向下移动
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos-index]
        array[pos-index]=x
    elif option=='a':   #向左移动
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos+1]
        array[pos+1]=x
    elif option=='d':   #向右移动
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos-1]
        array[pos-1]=x

⑦函数play()进行游戏

这个函数会调用上面创建的几个函数,进行游戏

只要isCorrect()返回值不为True,就代表游戏未完成,则继续执行while循环

一次while循环包括打印新的游戏界面(speak)和玩家操作(move)两部分👇

def play():
    speak()
    while(isCorrect()!=True):
        move()
        speak()
    print("成功")

定义完成后,直接调用play()函数即可开始游戏👇

play()

⑧完整代码

#Author:Mitchell
#Date:2021.3.14

array=[]

index=0
while index <= 0:
    print("请输入阶数:")
    index=int(input(index))
    if type(type(index)==int and index >0):
        break

import random
for i in range(index**2):
    array.append(str(i))
for i in range(index**2):
    pos=random.randint(0,index**2-1)
    x=array[i]
    array[i]=array[pos]
    array[pos]=x



def speak():
    for i in range(index**2):
        if array[i]=='0':
            print("".ljust(4),end="")
        else:
            print(array[i].ljust(4),end="")
        if(i%index==index-1):
            print("\n")

def isCorrect():
    for i in range(index**2-1):
        if array[i]!=str(i+1):
            return False
    return True

def whereBlank():
    for i in range(index**2):
        if array[i]=='0':
            return i

def move():
    option=''
    while ((option == 's' and (whereBlank() - index) >= 0) or (option == 'w' and (whereBlank() + index) < index**2) or (option == 'd' and (whereBlank() - 1) >= 0 and whereBlank() % index != 0) or (option == 'a' and (whereBlank() + 1) < index**2 and (whereBlank() + 1) % index != 0))==False:
        print("请输入移动方向↑(w)↓(s)←(a)→(d)——",end="")
        option=input(option)
    if option=='w':
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos+index]
        array[pos+index]=x
    elif option=='s':
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos-index]
        array[pos-index]=x
    elif option=='a':
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos+1]
        array[pos+1]=x
    elif option=='d':
        pos=whereBlank()
        x=array[pos]
        array[pos]=array[pos-1]
        array[pos-1]=x

def play():
    speak()
    while(isCorrect()!=True):
        move()
        speak()
    print("成功")

play()

⑨小拓展:让游戏界面更生动

我们可以尝试优化一下我们的游戏界面,比如像这样是不是更有感觉呢?👇

做到这个其实并不难,只要稍微修改一下speak()函数即可👇

def speak():
    print("_____"*index,"_\n",sep="")   
    for i in range(index**2):
        if(i%index==0):
            print('|',end="")
        if array[i]=='0':
            print("".center(4),end="|")
        else:
            print(array[i].center(4),end="|")
        if(i%index==index-1):
            print("\n_","_____"*index,"\n",sep="")

str.center()也是字符填充函数,填充的同时可以让字符居中输出

sep=""表示如果一个print中有多个变量需要打印,每个变量中间不进行间隔(否则默认间隔一个空格)

数字华容道是一个经典的益智游戏,玩家需要将一个n*n的数字方块按照规定的顺序排列,最终使得数字从左到右,从上到下依次递增。下面是一个简单Python数字华容道的实现: ```python import random # 生成随机的n*n数字方块 def generate_board(n): nums = list(range(1, n*n)) nums.append(None) random.shuffle(nums) board = [nums[i:i+n] for i in range(0, n*n, n)] return board # 找到数字方块中空格的位置 def find_blank(board): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == None: return (i, j) # 移动数字方块 def move(board, direction): i, j = find_blank(board) if direction == 'up' and i > 0: board[i][j], board[i-1][j] = board[i-1][j], board[i][j] elif direction == 'down' and i < len(board)-1: board[i][j], board[i+1][j] = board[i+1][j], board[i][j] elif direction == 'left' and j > 0: board[i][j], board[i][j-1] = board[i][j-1], board[i][j] elif direction == 'right' and j < len(board[0])-1: board[i][j], board[i][j+1] = board[i][j+1], board[i][j] # 判断是否完成游戏 def is_finished(board): nums = [num for row in board for num in row] return nums == list(range(1, len(nums))) + [None] # 打印数字方块 def print_board(board): for row in board: print(row) # 主函数 def main(): n = int(input("请输入数字华容道的阶数:")) board = generate_board(n) print_board(board) while not is_finished(board): direction = input("请输入移动方向(up/down/left/right):") move(board, direction) print_board(board) print("恭喜你完成了游戏!") if __name__ == '__main__': main() ```
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mitch311

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值