欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python之迷宫小游戏

程序员文章站 2022-07-13 08:26:44
...

迷宫小游戏

强烈推荐b站麦叔编程 (https://b23.tv/ZBqJSJ)讲的真的超好,容易理解。
而且理解基础代码后还可以自己稍加拓展。
我进行了简单的拓展,也可能存在bug,欢迎指正。
拓展一:共设置了5关,也可跟自己喜好随意设置多少关卡
拓展二:左上角显示当前关卡和游戏说明
拓展三:当玩家和恶魔相撞,提醒gameover,然后空格键重玩此关

效果图片

python之迷宫小游戏
python之迷宫小游戏
python之迷宫小游戏
python之迷宫小游戏
python之迷宫小游戏
python之迷宫小游戏

python之迷宫小游戏

简单效果

吃金币

python之迷宫小游戏

空格键刷新

python之迷宫小游戏

回车键进入下一关

python之迷宫小游戏

代码

代码中相关注释,保准大家一定能看懂

#1.创建游戏背景
import turtle as t

import random

# 创建窗口
mz = t.Screen()

# 设置长宽
mz.setup(700,700)
# 设置背景色
mz.bgcolor('black')
# 设置标题
mz.title('吃金币迷宫小游戏')

# 使用照片前先将照片注册
mz.register_shape('images/wall.gif')
mz.register_shape('images/pr.gif')
mz.register_shape('images/pl.gif')
mz.register_shape('images/gold.gif')
mz.register_shape('images/e.gif')

# 不用一步一步显示画面,最后一起显示,和mz.update()配合用
mz.tracer(0)


levels = []
# 第一关
# P:player; G:金币; E:恶魔;
level_1 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XXX   XXXXXX  XXXXXXXXXXX",
"XXXP XXXXXXX  XXXXXXXXXXX",
"XXX  XXXXXXX  XXXXXXXXXXX",
"XXX                  XXXX",
"XXXXXXX XXXX  XXXXX  XXXX",
"XXXXXXXG XXX  XXXXXG  XXX",
"XXXXXXXX XXX  XXXXXX  XXX",
"XXXXXXXX XXX  XXXXX    XX",
"XX                     XX",
"XXXX  XXXGXXXXX XX  XXXXX",
"XXXX  XXXXXXXXX XXX XXXXX",
"XXXXE               XXXXX",
"XXXXX  XX XXXXX  XX XXXXX",
"XXXXXX XX XXXXX  XX XXXXX",
"XXXXXX XX XXXXX  XXXXXXXX",
"XX               XXXXXXXX",
"XX   XXXXXXXXXXGXXXXXXXXX",
"XX   XXXXX              X",
"XXE  XXXXXXXXXXXXX  XXXXX",
"XX     XXXXXXXXXXX  XXXXX",
"XX            XXXX      X",
"XXXX                    X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]
level_2 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XXX   XXXXXX  XXXXXXXXXXX",
"XXXP XXXXXXX  XXXXXXXXXXX",
"XXX  XXXXXXX  GXXXXXXXXXX",
"XXX                  XXXX",
"XXXXXXX XXXX  XXXXX  XXXX",
"XXXXXXXG XXX  XXXXXG  XXX",
"XXXXXXXX XXX  XXXXXX  XXX",
"XXXXXXXX XXX  XXXXX    EX",
"XX                     XX",
"XXXX  XXXGXXXXX XX  XXXXX",
"XXXX  XXXXXXXXX XXXGXXXXX",
"XXXXE               XXXXX",
"XXXXX  XX XXXXX  XX XXXXX",
"XXXXXX XX XXXXX  XX XXXXX",
"XXXXXX XX XXXXX  XXXXXXXX",
"XX               XXXXXXXX",
"XX   XXXXXXXXXXGXXXXXXXXX",
"XX   XXXXX              X",
"XXE  XXXXXXXXGXXXX  XXXXX",
"XX     XXXXXXXXXXX  XXXXX",
"XX            XXXX      X",
"XXXX                    X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]
level_3 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XXX   XXXXXX  XXXXXXXXXXX",
"XXXX XXX  XXE XXXXX  XXXX",
"XXX  XXX   X  XXXXX  XXXX",
"XXX                   XXX",
"XXXXXXX XXXX  XXXXX  XXXX",
"XXXXX  GXXXX  XXXXXE   XX",
"XXXX  XXXXXP  XXXXX   XXX",
"XXXX  GXX XX  XXXXX    XX",
"XX                     XX",
"XX X  XXXX XX XXXX  XXXXX",
"XXXX  XXXXGXX XXX   X XXX",
"XXXGX            XX XXXXX",
"XXX   XXX XXX X  XX XXXXX",
"XXX  XXXE XXX G  XX XXXXX",
"XXX  XXXX XXX X   G XXXXX",
"XX               XX XXXXX",
"XX   X X XXXX XXXXX XXXXX",
"XX   X X                X",
"XX   XXXGXXXX XXXX XXXXXX",
"XX     XXXXXEXXXXX  XXXXX",
"XX            XXXX      X",
"XXXX                    X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]
level_4 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XXX   XXXXXX  XX XXXXXXXX",
"XXXE XXX  XX  PX XX   XXX",
"XXX  XXX  XX  XX XX  XXXX",
"XXX                  XXXX",
"XXXXXXX XXXX  XX XX  XXXX",
"XXX    GXXXX  XX XXE   XX",
"XG  XXXXXXX   XXXXX   XXX",
"X  X  XXXXXX  XXGXX    XX",
"XX                     EX",
"XXXX  XXXX XX XXXX   XXXX",
"XXXX  XXXXXXXGXXXXX  XXXX",
"XXXXE            XXXGXXXX",
"XXXX  XXX XXX X  XXX XXXX",
"XXX  XXXX XXX X  XXX XXXX",
"XG   XXGX XXX X  XXX XXXX",
"XX                   XXXX",
"XX   XXXXXX X XEXXXX XXXX",
"XX   XXXXX              X",
"XX   XGXXXXXX XXXX  XXXXX",
"XX     XXXXXX XXXX  XXXXX",
"XX            XXXX      X",
"XXEX                    X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]

level_5 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XXX   XXXXXE  XX XXXXXXXX",
"XXXE XXX  XXX XX XX   PXX",
"XXX  XXX  XX  XX XX  XXXX",
"XXX                  GXXX",
"XXXXXXX XXXX  XX XX  XXXX",
"XXX    GXXXXXXXX XXE   XX",
"XG  XXXXXXX   XX XX   XXX",
"X  X  XXXXXX  XXGXX    XX",
"XX                     EX",
"XXXX  XXXX XX XXXX   XX X",
"XXXX  XXXXXXXGXXXXX  XX X",
"XXXXE            XXXGXXGX",
"XXXX  XXX XXX X  XXX XX X",
"XXX  XXXX XXX E  XXX XX X",
"XG   XXGX XXX X  XXX XX X",
"XX                    G X",
"XX   XXXXXX X XEXXXX XXXX",
"XX   XXXXX              X",
"XX   XGXXXXXX XXXX  XXXXX",
"XX     XXXXXX XXGX  XXEXX",
"XX            XX X      X",
"XXEX                    X",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]

levels.append(level_1)
levels.append(level_2)
levels.append(level_3)
levels.append(level_4)
levels.append(level_5)

class Pen(t.Turtle):
    # -----------画笔-------------
    def __init__(self):
        # 继承父类的属性
        super().__init__()
        # 先隐藏起来,隐秘进行运动
        self.ht()
        self.shape('images/wall.gif')
        self.speed(0)
        self.penup()

    # -----------迷宫--------------
    def make_maze(self):
        level = levels[current_level - 1]
        for i in range(len(level)):
            # 取出某一行
            row = level[i]
            # 获取到某一元素的坐标
            for j in range(len(row)):
                screen_x = -288 + 24 * j
                screen_y = 288 - 24 * i

                char = row[j]
                #如果元素为X,则画出迷宫
                if char == 'X':
                    self.goto(screen_x,screen_y)
                    self.stamp()
                    walls.append((screen_x,screen_y))#元组
                elif char == 'P':
                    player.goto(screen_x,screen_y)
                    player.st()
                elif char == 'G':
                    gold = Gold()
                    golds.append(gold)
                    gold.goto(screen_x,screen_y)
                    gold.st()
                elif char == 'E':
                    e = Evil()
                    evils.append(e)
                    e.goto(screen_x, screen_y)
                    e.st()
        show_level('当前关卡:',current_level,'如想重玩此关,在进入下一关前按空格键即可!')




class Player(t.Turtle):
    # -----------玩家-------------
    def __init__(self):
        # 继承父类的属性
        super().__init__()
        # 先隐藏起来,隐秘进行运动
        self.ht()
        self.shape('images/pr.gif')
        self.speed(0)
        self.penup()

    # 右移
    def go_right(self):
        # print('going right')
        go_x = self.xcor() + 24
        go_y = self.ycor()
        self.shape('images/pr.gif')
        self.move(go_x, go_y)

    # 左移
    def go_left(self):
        # print('going left')
        go_x = self.xcor() - 24
        go_y = self.ycor()
        # 左移时通过更换图片来更换方向
        self.shape('images/pl.gif')
        self.move(go_x,go_y)

    # 上移
    def go_up(self):
        # print('going up')
        go_x = self.xcor()
        go_y = self.ycor() + 24
        self.move(go_x, go_y)

    # 下移
    def go_down(self):
        # print('going down')
        go_x = self.xcor()
        go_y = self.ycor() - 24
        self.move(go_x, go_y)

    # 运动时的共同行为
    def move(self, go_x, go_y):
        if (go_x, go_y) not in walls:
            self.goto(go_x, go_y)

            # 边运动边查找是否金币
            self.look_for_gold(go_x,go_y)
            self.isgameover(go_x,go_y)
        else:
            print('撞墙了')

    def look_for_gold(self,go_x,go_y):
        global score
        for g in golds:
            # print('g--',g)
            # 判断玩家和金币的距离
            if g.distance(player) == 0:
                score += 1
                #当玩家和金币重叠时,将金币隐藏,并从golds数组中移除
                g.ht()
                golds.remove(g)

        # 如果golds数组为空,则说明金币已全部吃完
        if not golds:
            print('金币全部吃完了')
            success()

    def isgameover(self,go_x,go_y):
        for e in evils:
            # print('e--',e)
            if e.distance(player) ==0:
                print('gameover')
                fail()

class Gold(t.Turtle):
    # -----------金币-------------
    def __init__(self):
        # 继承父类的属性
        super().__init__()
        # 先隐藏起来,隐秘进行运动
        self.ht()
        self.shape('images/gold.gif')
        self.speed(0)
        self.penup()


class Evil(t.Turtle):
    # -----------恶魔-------------
    def __init__(self):
        # 继承父类的属性
        super().__init__()
        # 先隐藏起来,隐秘进行运动
        self.ht()
        self.shape('images/e.gif')
        self.speed(0)
        self.penup()

    # 恶魔移动
    def move(self):
        # 调用turn给恶魔运动一个随机的方向
        self.turn()
        if self.fx == 'U':
            go_x = self.xcor()
            go_y = self.ycor() + 24
        elif self.fx == 'D':
            go_x = self.xcor()
            go_y = self.ycor() - 24
        elif self.fx == "L":
            go_x = self.xcor() - 24
            go_y = self.ycor()
        elif self.fx == "R":
            go_x = self.xcor() + 24
            go_y = self.ycor()

        # 避免恶魔撞墙
        if (go_x, go_y) not in walls:
            self.goto(go_x, go_y)
        # 恶魔移动时间在100-300毫秒之间
        t.ontimer(self.move, random.randint(100, 300))

    # 恶魔转向
    def turn(self):
        # 跟随功能
        if self.distance(player) < 48:
            if self.xcor() < player.xcor():
                self.fx = 'R'
            elif self.xcor() > player.xcor():
                self.fx = 'L'
            elif self.ycor() < player.ycor():
                self.fx = 'U'
            elif self.ycor() > player.ycor():
                self.fx = 'D'
        else:
            self.fx = random.choice(['U', 'D', 'L', 'R'])

# 进入下一关
# 默认当前级别为1
current_level = 1

# --------显示当前关卡----------
level_pen = t.Turtle()
level_pen1 = t.Turtle()
def show_level(title,current_level,msg):
    # ---title---msg--
    level_pen.ht()
    level_pen.speed(0)
    level_pen.penup()
    level_pen.color('#fff')
    level_pen.goto(-300,310)
    level_pen.write(title,align='left',font=('Arial',20,'bold'))
    level_pen.goto(-160, 310)
    level_pen.write(msg, align='left', font=('Arial', 14, 'bold'))
    # ----关卡数----level----
    level_pen1.ht()
    level_pen1.speed(0)
    level_pen1.penup()
    level_pen1.color('#FF4500')
    level_pen1.goto(-200, 310)
    level_pen1.write(current_level, align='left', font=('Arial', 30, 'bold'))

# --------通关---------------
def success():
    # 如果已到最后一关,则提示您已通关
    if(current_level == len(levels)):
        print('您已全部过关')
        show_success_msg('恭喜,您已全部过关!!','','按回车键重玩游戏')
    # 否则进入下一关
    else:
        print('成功过关,按回车键进入下一关')
        show_success_msg('恭喜,您成功通过关卡',current_level,'按回车键进入下一关')

# --------画笔-----通关消息------------
success_pen = t.Turtle()
def show_success_msg(title,current_level,msg):
    success_pen.ht()
    success_pen.speed(0)
    success_pen.penup()
    success_pen.goto(-100,-100)
    # 填充色
    success_pen.fillcolor('#BC8F8F')
    # 开始填充
    success_pen.begin_fill()
    for i in range(4):
        success_pen.fd(250)
        success_pen.left(90)
    # 结束填充
    success_pen.end_fill()
    success_pen.goto(-80,40)
    success_pen.color('#fff')
    success_pen.write(title,align='left',font=('Arial',20,'bold'))
    success_pen.goto(120, 40)
    success_pen.write(current_level, align='left', font=('Arial', 20, 'bold'))
    success_pen.goto(-85,-40)
    success_pen.write(msg, align='left', font=('Arial', 20, 'bold'))

# ------进入下一关---------
def next_level():
    global current_level
    # 只有当吃完金币进入下一关时,回车键才起作用
    if not golds:
        if current_level == len(levels):
            current_level = 1
        else:
            current_level =current_level + 1

        # 清除提示信息
        success_pen.clear()
        level_pen.clear()
        level_pen1.clear()
        fail_pen.clear()
        # 隐藏并清空恶魔
        for e in evils:
            e.ht()
        evils.clear()
        # 清空砖块
        walls.clear()
        #清除迷宫的砖墙
        pen.clear()
        #重建迷宫
        pen.make_maze()
        # 设置定时器让恶魔移动
        for e in evils:
            t.ontimer(e.move, random.randint(100, 300))


# --------gameover---------------
def fail():
    # print('gameover----')
    show_fail_msg('gameover','按空格键重玩游戏')

# --------画笔-----gameover消息------------
fail_pen = t.Turtle()
def show_fail_msg(title,msg):
    fail_pen.ht()
    fail_pen.speed(0)
    fail_pen.penup()
    fail_pen.goto(-100,-100)
    # 填充色
    fail_pen.fillcolor('#BC8F8F')
    # 开始填充
    fail_pen.begin_fill()
    for i in range(4):
        fail_pen.fd(250)
        fail_pen.left(90)
    # 结束填充
    fail_pen.end_fill()
    fail_pen.goto(-80,40)
    fail_pen.color('#fff')
    fail_pen.write(title,align='left',font=('Arial',20,'bold'))
    fail_pen.goto(-85,-40)
    fail_pen.write(msg, align='left', font=('Arial', 20, 'bold'))

# ------gameover后重玩此关---------
def restart():
    global current_level
    current_level =current_level + 0
    # 清除提示信息
    fail_pen.clear()
    level_pen.clear()
    level_pen1.clear()
    success_pen.clear()
    # 隐藏并清空恶魔
    for e in evils:
        e.ht()
    evils.clear()
    # 清空砖块
    walls.clear()
    #清除迷宫的砖墙
    pen.clear()
    #重建迷宫
    pen.make_maze()
    # 设置定时器让恶魔移动
    for e in evils:
        t.ontimer(e.move, random.randint(100, 300))



score = 0

# 调用画笔类
pen = Pen()

# 调用玩家
player = Player()

evil = Evil()

# walls数组来存储墙的坐标
walls = []

# golds数组存储金币
golds = []

evils = []

# 根据不同的关卡绘制迷宫
pen.make_maze()

# 根据键盘移动
mz.listen()
mz.onkey(player.go_right, 'Right')
mz.onkey(player.go_left, 'Left')
mz.onkey(player.go_up, 'Up')
mz.onkey(player.go_down, 'Down')
mz.onkey(next_level, 'Return')#回车键
mz.onkey(restart, 'space')#空格键



# 设置闹钟让恶魔移动
for e in evils:
    t.ontimer(e.move,random.randint(100,300))

while True:
    mz.update()

# 提醒窗口不要退出
mz.mainloop()

image

python之迷宫小游戏
python之迷宫小游戏
python之迷宫小游戏
python之迷宫小游戏
python之迷宫小游戏

引用

麦叔b站****

相关标签: python 游戏