目录

前言

游戏说明

1.游戏地图

2.类图

3.代码

前言

Python课程的作业,最初的版本是玩家使用文字进行游戏,但实际体验感相当差,现在利用GUI进行可视化交互,方便玩家进行游戏。

不过许多功能是为了踩点拿分做,代码结构现在回过来看看emmm。但总之对能跑起来,各个功能都可以正常运行,没啥大bug。

游戏说明

这是一款冒险游戏。玩家在一个破败的基地中醒来。玩家需要通过探索基地来寻找帮助其回家的物品,但也会有许多陷阱和宝藏。玩家需要在基地收集足够的钥匙,击败怪物方可逃离。

1.游戏地图

游戏地图为两张,分为一层和二层,只有收集所需武器以及钥匙才可以击杀最终boss

一层地图:

二层地图:

2.类图

3.代码

代码主要分为四个部分:GUI(负责界面交互)、Game(游戏主要逻辑)、Room(游戏房间设置)、Player(玩家HP、武器、钥匙等物品)

顺便设置了自动化测试(确保功能可以正常运行)以及log记录(方便玩家查看自己的行动历史)

GUI代码如下:

import tkinter as tk
from tkinter import messagebox, RIGHT, LEFT, TOP, NW, DISABLED, NORMAL, BOTTOMimport tkinter
from PIL import ImageTk, Image
from Game import Gameimport datetimeclass MyGame_FIRSTUI:def __init__(self, root,PLAYER_IMAGE):'''User initial interfaceEnter user nickname:param root:'''# Create the model instance ...self.PLAYER_IMAGE=PLAYER_IMAGE#PLAYER_IMAGE=0self.root = rootself.root.config()self.userframe = tk.Frame(self.root, width=1100, height=700)self.userframe.pack_propagate(0)  # Prevents resizingself.userframe.pack()self.userframe.columnconfigure(0, pad=5)for i in range(7):self.userframe.rowconfigure(i, pad=5)self.start_image = ImageTk.PhotoImage(Image.open('images/welcome.png'))self.image1 = ImageTk.PhotoImage(Image.open("images/player.png"))self.image2 = ImageTk.PhotoImage(Image.open("images/player2.gif"))self.start = tk.Label(self.userframe, image=self.start_image, width=1100, height=300)self.start.grid(row=0,column=0)self. label = tk.Label(self.userframe, text='Please enter user name', font=('Sans', '15', 'bold'))self.label.grid(row=1, column=0)self.button = tk.Button(self.userframe, text='start', command=self.change,font=('Sans', '15', 'bold'))self.button.grid(row=3,column=0, ipady=10, pady=10)self.player_name = tk.Entry(self.userframe, text='player_name')self.player_name.grid(row=2,column=0, ipady=10, pady=10)self.label_w = tk.Label(self.userframe, text='Please choose your Avatar', font=('Sans', '15', 'bold'))self.label_w.grid(row=4,column=0)self.button_image1=tk.Button(self.userframe,image=self.image1,compound=tkinter.BOTTOM,text='Avatar 1', command=self.Avatar1)self.button_image1.grid(row=5, column=0)self.button_image2 = tk.Button(self.userframe, image=self.image2,compound=tkinter.BOTTOM,text='Avatar 2', command=self.Avatar2)self.button_image2.grid(row=6, column=0)def change(self):"""close the firstUI and start the secondUIGlobal variable: PLAYER_NAMEError prevention and recovery"""global PLAYER_NAMEtry:PLAYER_NAME = self.player_name.get()if PLAYER_NAME.isalpha() == False:raise (ValueError())except ValueError:messagebox.showinfo("NOTE",message="Please use String type!")else:self.userframe.destroy()myApp = MyGame_secondUI(self.root,self.PLAYER_IMAGE)def Avatar1(self):#global PLAYER_IMAGEself.PLAYER_IMAGE=1def Avatar2(self):#global PLAYER_IMAGEself.PLAYER_IMAGE=2class MyGame_secondUI:def __init__(self, root,PLAYER_IMAGE):'''The main interface of the game:param root:'''# Create the model instance ...self.PLAYER_IMAGE=PLAYER_IMAGEself.game = Game()self.res = Falseself.root = rootself.people_x=225self.people_y=125self.nowroom='outside'# Create the GUI#add menubarmenubar=tk.Menu()menubar.add_command(label="Quit",command=root.destroy)root.config(menu=menubar)menubar.add_command(label="About",command=self.about)root.config(menu=menubar)# add frameself.frame1 = tk.Frame(root, width=850,height=640, bg='GREY', borderwidth=2)self.frame1.pack_propagate(0)   # Prevents resizingself.frame1.pack(side = LEFT)self.frame2 = tk.Frame(root, width=250, height=650, borderwidth=2)self.frame2.pack_propagate(0)  # Prevents resizingself.frame2.pack(side = RIGHT)self.frame3 = tk.Frame(self.frame2, width=250, height=350, borderwidth=2)self.frame3.pack_propagate(0)  # Prevents resizingself.frame3.pack(side = TOP)self.frame4 = tk.Frame(self.frame2, width=250, height=350, borderwidth=2)self.frame4.pack_propagate(0)  # Prevents resizingself.frame4.pack(side = TOP)self.frame5 = tk.Frame(self.frame2, width=250, height=350, borderwidth=2)self.frame5.pack_propagate(0)  # Prevents resizingself.frame5.pack(side=TOP)self.frame3.columnconfigure(0, pad=10)for i in range(6):self.frame3.rowconfigure(i,pad=10)for i in range(2):self.frame4.columnconfigure(i, pad=10)for i in range(4):self.frame4.rowconfigure(i,pad=10)#get images#global PLAYER_IMAGEif self.PLAYER_IMAGE==2:self.character = ImageTk.PhotoImage(Image.open("images/player2.gif"))else:self.character = ImageTk.PhotoImage(Image.open("images/player.png"))self.east = ImageTk.PhotoImage(Image.open("images/east.png"))self.west=ImageTk.PhotoImage(Image.open("images/west.png"))self.south=ImageTk.PhotoImage(Image.open("images/south.png"))self.north=ImageTk.PhotoImage(Image.open("images/north.png"))self.weapon = ImageTk.PhotoImage(Image.open("images/axe.png"))self.coin = ImageTk.PhotoImage(Image.open("images/coin.png"))self.heart=ImageTk.PhotoImage(Image.open("images/heart.png"))self.wolf= ImageTk.PhotoImage(Image.open("images/wolf.png"))self.bear= ImageTk.PhotoImage(Image.open("images/Bear_Run.png"))self.garden_bg= ImageTk.PhotoImage(Image.open("images/Garden.png"))self.oustide_bg= ImageTk.PhotoImage(Image.open("images/outside.jpg"))self.lab_bg=ImageTk.PhotoImage(Image.open("images/lab.png"))self.diningroom_bg=ImageTk.PhotoImage(Image.open("images/diningroom.png"))self.beasment_bg=ImageTk.PhotoImage(Image.open("images/basement.png"))self.shop_bg=ImageTk.PhotoImage(Image.open("images/shop.png"))self.lobby_bg=ImageTk.PhotoImage(Image.open("images/lobby.png"))self.gym_bg=ImageTk.PhotoImage(Image.open("images/gym.png"))self.loung_bg=ImageTk.PhotoImage(Image.open("images/loung.png"))self.portal_bg=ImageTk.PhotoImage(Image.open("images/portal.png"))self.office_bg=ImageTk.PhotoImage(Image.open("images/office.png"))self.storehouse_bg=ImageTk.PhotoImage(Image.open("images/storehouse.png"))self.destination_bg=ImageTk.PhotoImage(Image.open("images/destination.png"))self.corridor_bg = ImageTk.PhotoImage(Image.open("images/corridor.png"))self.logo=ImageTk.PhotoImage(Image.open("images/destination-logo.png"))self.key=ImageTk.PhotoImage(Image.open("images/Key.png"))#add buttonoptions = ['background introduction', 'button introduction']    # List with all optionsself.v = tk.StringVar(self.frame3)self.v.set("help")  # default valueself.v.trace("w", self.help)self.w = tk.OptionMenu(self.frame3, self.v, *options)self.w.grid(row=0, column=0)self.button_bag=tk.Button(self.frame3,text="use bag",command=lambda :self.usebag())self.button_bag.grid(row=1, column=0)self.button_weapon=tk.Button(self.frame3,text="weapon",image=self.weapon,compound=tkinter.BOTTOM,command=lambda :self.checkweapon())self.button_weapon.grid(row=4, column=0)#directionself.button_north=tk.Button(self.frame4,text="north",image=self.north,compound=tkinter.BOTTOM,command=lambda :self.North())self.button_north.grid(row=0, column=0)self.button_south = tk.Button(self.frame4, text="soth", image=self.south,compound=tkinter.BOTTOM,command=lambda: self.South())self.button_south.grid(row=0, column=1)self.button_west=tk.Button(self.frame4,text="west",image=self.west,compound=tkinter.BOTTOM,command=lambda :self.West())self.button_west.grid(row=1, column=0)self.button_east=tk.Button(self.frame4,text="east",image=self.east,compound=tkinter.BOTTOM,command=lambda :self.East())self.button_east.grid(row=1, column=1)self.stair=ImageTk.PhotoImage(Image.open("images/wooden_stairs-ns.png"))self.button_up=tk.Button(self.frame4,text="upstairs",image=self.stair,compound=tkinter.BOTTOM,command=lambda :self.Up())self.button_up.grid(row=2,column=0)self.button_down = tk.Button(self.frame4, text="downstairs",image=self.stair,compound=tkinter.BOTTOM,command=lambda :self.Down())self.button_down.grid(row=2,column=1)self.button_down.configure(state=DISABLED)#LABELself.label_HP=tk.Label(self.frame5,text="Your life:"+str(self.game.player.life)+"HP",image=self.heart,compound=tkinter.LEFT)self.label_HP.pack(side=TOP)self.label_COIN=tk.Label(self.frame5,text="Your coin:"+str(self.game.player.coins),image=self.coin,compound=tkinter.LEFT)self.label_COIN.pack(side=TOP)self.label_KEY=tk.Label(self.frame5,text="Your key:"+str(self.game.player.total_keys),image=self.key,compound=tkinter.LEFT)self.label_KEY.pack(side=TOP)#picture_roomself.cv=tk.Canvas(self.frame1,bg ='white',width=850,height=650)# Create rectangle with coordinates#garden=self.cv.create_rectangle(25, 25, 175, 100)self.garden=self.cv.create_image(25, 25, anchor=NW,image=self.garden_bg)self.cv.create_text(70, 35, text="GARDEN",fill="white")door1=self.cv.create_rectangle(75, 100, 125, 125,outline="",fill="grey")#corridor=self.cv.create_rectangle(25, 125, 175, 200)self.corridor=self.cv.create_image(25, 125,anchor=NW,image=self.corridor_bg)self.cv.create_text(70, 135, text="CORRIDOR",fill="white")door2 = self.cv.create_rectangle(75, 200, 125, 225,outline="",fill="grey")#lounge=self.cv.create_rectangle(25, 225, 175, 300)self.loung = self.cv.create_image(25, 225, anchor=NW, image=self.loung_bg)self.cv.create_text(70, 235, text="LOUNGE",fill="white")door3 = self.cv.create_rectangle(75, 300, 125, 325,outline="",fill="grey")#gym=self.cv.create_rectangle(25, 325, 175, 400)self.gym=self.cv.create_image(25, 325, anchor=NW, image=self.gym_bg)self.cv.create_text(70, 335, text="GYM",fill="white")door4 = self.cv.create_rectangle(75, 400, 125, 425,outline="",fill="grey")#destination=self.cv.create_rectangle(25, 425, 175, 500)self.destination = self.cv.create_image(25, 425, anchor=NW, image=self.destination_bg)self.cv.create_text(70,435, text="DISTINATION",fill="white")door5=self.cv.create_rectangle(175, 150, 225, 175,outline="",fill="grey")#outside=self.cv.create_rectangle(225, 125, 375, 200)self.outside = self.cv.create_image(225, 125, anchor=NW, image=self.oustide_bg)self.cv.create_text(270,135, text="OUTSIDE",fill="white")door6 = self.cv.create_rectangle(275,200,325,225,outline="",fill="grey")#lab=self.cv.create_rectangle(225,225,375,300)self.lab = self.cv.create_image(225,225, anchor=NW, image=self.lab_bg)self.cv.create_text(270,235, text="LAB",fill="white")door7 = self.cv.create_rectangle(275,300,325,325,outline="",fill="grey")#storehouse=self.cv.create_rectangle(225,325,375,400)self.storehouse = self.cv.create_image(225,325, anchor=NW, image=self.storehouse_bg)self.cv.create_text(270,335, text="STOREHOUSE",fill="white")door8 = self.cv.create_rectangle(275,400,325,425,outline="",fill="grey")#basement=self.cv.create_rectangle(225,425,375,500)self.basement=self.cv.create_image(225,425,anchor=NW,image=self.beasment_bg)self.cv.create_text(270,435, text="BASEMENT",fill="white")door9 = self.cv.create_rectangle(375,150,425,175,outline="",fill="grey")#lobby=self.cv.create_rectangle(425,125,575,200)self.lobby = self.cv.create_image(425,125, anchor=NW, image=self.lobby_bg)self.cv.create_text(450,135, text="LOBBY",fill="white")door10 = self.cv.create_rectangle(375,250,425,275,outline="",fill="grey")#office=self.cv.create_rectangle(425,225,575,300)self.office = self.cv.create_image(425,225, anchor=NW, image=self.office_bg)self.cv.create_text(450,235, text="OFFICE",fill="white")door11 = self.cv.create_rectangle(375,350,425,375,outline="",fill="grey")self.portal = self.cv.create_image(425,325, anchor=NW, image=self.portal_bg)self.cv.create_text(500, 335, text="MAGIC PORTAL",fill="black")#Portal = self.cv.create_rectangle(425,325,575,400)door12 = self.cv.create_rectangle(575,150,625,175,outline="",fill="grey")#diningroom=self.cv.create_rectangle(625,125,775,200)self.diningroom = self.cv.create_image(625,125, anchor=NW, image=self.diningroom_bg)self.cv.create_text(700,135, text="DINING ROOM",fill="white")door13 = self.cv.create_rectangle(575,250,625,275,outline="",fill="grey")#shop = self.cv.create_rectangle(625,225,775,300)self.shop = self.cv.create_image(625,225, anchor=NW, image=self.shop_bg)self.cv.create_text(700, 235, text="SHOP",fill="black")door14 = self.cv.create_rectangle(675,200,725,225,outline="",fill="grey")door15 = self.cv.create_rectangle(175,450,225,475,outline="",fill="grey")door16=self.cv.create_image(75,500,anchor=NW, image=self.logo)self.label_warning=tk.Label(self.frame1,text="Please go to the second floor to destroy the monster.")self.label_warning.place(x=400, y=400)self.label_warning2=tk.Label(self.frame1,text="Please go find enough keys to pass the game.")self.label_warning2.place(x=400, y=420)self.mybag=tk.Label(self.frame1,text="Your item:"+str(self.game.player.bag))self.mybag.place(x=25,y=560, width=500, height=30)self.location=tk.Label(self.frame1,text='Hi, '+str(PLAYER_NAME)+" Your location:" + str(self.game.JudgeInRoom(self.people_x,self.people_y)))self.location.place(x=0, y=0, width=400, height=20)self.man = self.cv.create_image(self.people_x,self.people_y,anchor=NW,image=self.character)self.cv.pack()def usebag(self):'''Use backpackIf using the wrong item causes the health to be less than 0The game is overYou can use the props again when it is equal to 0:return:'''self.mylog('Use bag')self.game.player.useTools()self.label_HP.configure(text="Your life:" + str(self.game.player.life) + "HP")if self.game.player.life<0:self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)elif self.game.player.life==0:messagebox.showinfo("NOTE","Please use other items")def checkweapon(self):'''Check weapon'''self.mylog('Check weapon')self.game.player.seeweapon()def help(self, *args):'''background introduction'''command = self.v.get()self.mylog('Help-background introduction')if command == 'background introduction':messagebox.showinfo("Background", "You are in a shabby base. ""\nYou are alone. You wander.""\nThere is a magical item in the shabby base to help you go home.""\nYou need to reach the designated location with enough keys.""\nSo start your adventure.")elif command == 'button introduction':messagebox.showinfo("Button", "help:Function Introduction""\nquit:Exit the game""\nbag:See the tools and its character attributes""\nuse:Use tools in your bag""\nweapon:Check your keys number""\nkey:Check your keys number""\ndirection:Check exits""\nlife:Check your health value")def Up(self):"""Upstairs:go SKY GARDENmonster    Different attack ways will have different damageCreate a new framework and Forget Frame1 and Frame 2South east north west cannot be usedCan only use downdownstairs:Reposition the frame1Monsters will not refresh repeatedly"""#GUIself.frame1.pack_forget()self.frame6=tk.Frame(self.root,width=850,height=640, bg='GREY', borderwidth=2)self.frame6.pack_propagate(0)   # Prevents resizingself.frame6.pack(side = LEFT)self.button_up.configure(state=DISABLED)self.button_east.configure(state=DISABLED)self.button_west.configure(state=DISABLED)self.button_north.configure(state=DISABLED)self.button_south.configure(state=DISABLED)self.button_down.configure(state=NORMAL)self.sky_garden = ImageTk.PhotoImage(Image.open("images/UPSTAIRS.png"))self.monster = ImageTk.PhotoImage(Image.open("images/monster.png"))self.attack_m=ImageTk.PhotoImage(Image.open("images/magicicons.png"))self.attack_y=ImageTk.PhotoImage(Image.open("images/sword.png"))self.mybag=tk.Label(self.frame6,text="Your item:"+str(self.game.player.bag))self.mybag.place(x=25,y=560, width=500, height=30)self.location=tk.Label(self.frame6,text='Hi, '+str(PLAYER_NAME)+" Your location: Sky Garden" )self.location.place(x=0, y=0, width=400, height=20)self.label_sky=tk.Label(self.frame6,image=self.sky_garden)self.label_sky.place(x=20,y=50, width=500, height=396)self.label_monster=tk.Label(self.frame6,image=self.monster)self.label_monster.place(x=230, y=150, width=102, height=102)self.label_text=tk.Label(self.frame6,text="There is a santa claus here\nBeat it to get huge rewards""\nHere are two weapons \nPlease choose one to defeat him")self.label_text.place(x=550, y=50, width=250, height=100)self.label_monsterHP = tk.Label(self.frame6, text="HP of santa claus "+str(self.game.monster_HP))self.label_monsterHP.place(x=550, y=160, width=250, height=30)self.button_MagicAttack=tk.Button(self.frame6,text="Magic Attack",command=lambda :self.attack1())self.button_MagicAttack.place(x=570,y=200)self.label_attack1=tk.Label(self.frame6,image=self.attack_m)self.label_attack1.place(x=570,y=230)self.button_PhysicalAttack = tk.Button(self.frame6, text="Physical Attack",command=lambda :self.attack2())self.button_PhysicalAttack.place(x=680, y=200)self.label_attack2 = tk.Label(self.frame6, image=self.attack_y)self.label_attack2.place(x=680, y=230)def attack1(self):'''Magic attack methodOne attack reduces the monster's HP by 50and causes 1Hp damage to yourself'''if self.game.player.life > 0:if self.game.monster_HP>0:self.game.monster_HP-=50self.game.player.life-=1messagebox.showinfo("ATTACK", "SUCCESSFUL ATTACK !\n -50HP \nPlease go on! \nYou are also injured\n-1HP")self.mylog("ATTACK:SUCCESSFUL ATTACK !-50HP Please go on! You are also injured. -1HP")if self.game.monster_HP <=0:self.game.monster_HP = 0messagebox.showinfo("NOTE", "The monster is dead\nYou get a lot of coins, HP and Keys")self.mylog("The monster is dead.You get a lot of coins, HP and Keys")self.game.player.life+=5self.game.player.coins+=10self.game.player.total_keys+=5self.button_MagicAttack.configure(state=DISABLED)self.button_PhysicalAttack.configure(state=DISABLED)else:self.mylog('You lose the game')messagebox.showinfo("GAME OVER", "You have no enough life!\nYOU LOSE!")self.frame2.pack_forget()self.frame6.pack_forget()myApp = MyGame_thirdUI(self.root)self.label_monsterHP.configure(text="HP of santa claus "+str(self.game.monster_HP))self.label_HP.configure(text="Your life:" + str(self.game.player.life) + "HP")self.label_COIN.configure(text="Your coin:" + str(self.game.player.coins))self.mybag.configure(text="Your item:" + str(self.game.player.bag))self.label_KEY.configure(text="Your key:" + str(self.game.player.total_keys))def attack2(self):'''Physical attack methodOne attack reduces the monster's HP by 20and causes 1Hp damage to yourself'''if self.game.player.life > 0:if self.game.monster_HP>0:self.game.monster_HP-=20self.game.player.life -= 1messagebox.showinfo("ATTACK","SUCCESSFUL ATTACK !\n -20HP\nPlease go on!\nYou are also injured\n-1HP")self.mylog("ATTACK:SUCCESSFUL ATTACK !-50HP Please go on! You are also injured. -1HP")if self.game.monster_HP<=0:self.game.monster_HP = 0messagebox.showinfo("NOTE", "The monster is dead\nYou get a lot of coins, HP and Keys")self.mylog("The monster is dead.You get a lot of coins, HP and Keys")self.game.player.life+=5self.game.player.coins+=10self.game.player.total_keys+=5self.button_PhysicalAttack.configure(state=DISABLED)self.button_MagicAttack.configure(state=DISABLED)else:self.mylog('You lose the game')messagebox.showinfo("GAME OVER", "You have no enough life!\nYOU LOSE!")self.frame2.pack_forget()self.frame6.pack_forget()myApp = MyGame_thirdUI(self.root)self.label_monsterHP.configure(text="HP of santa claus "+str(self.game.monster_HP))self.label_HP.configure(text="Your life:" + str(self.game.player.life) + "HP")self.label_COIN.configure(text="Your coin:" + str(self.game.player.coins))self.mybag.configure(text="Your item:" + str(self.game.player.bag))self.label_KEY.configure(text="Your key:" + str(self.game.player.total_keys))def Down(self):'''Go downstairs:restore the frame1 andframe2 on the first floorforget the frame on the second floor'''self.frame1.pack()self.frame6.pack_forget()self.button_up.configure(state=NORMAL)self.button_east.configure(state=NORMAL)self.button_west.configure(state=NORMAL)self.button_north.configure(state=NORMAL)self.button_south.configure(state=NORMAL)self.button_down.configure(state=DISABLED)def North(self):'''Direction buttonsFirstjudge whether the key is enoughand whether the monster on the second floor has died,otherwise remind the player.Secondly,it is judged whether the player's life value supports the player to continue the game,The game is over if insufficientIf it is enough,judge whether the now room is the same as the old room,if nowroom != oldroom ,return Flag=FalseThen judge whether it is in the map,if it is in the map,move forward,and decide whether to trigger the corresponding game according to the FlagUpdate player information'''if self.game.monster_HP>0:self.label_warning.configure(text="Please go to the second floor to destroy the monster")if self.game.player.total_keys<6:self.label_warning2.configure(text="Please go find enough keys to pass the game")if self.game.player.life>0:self.oldroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.nowroom = self.game.JudgeInRoom(self.people_x, self.people_y - 25)if self.oldroom != self.nowroom and self.nowroom=='doorway':self.res=self.game.roomplay(self.people_x, self.people_y,self)if self.game.JudgeInMap(self.people_x,self.people_y-25)==True and self.res==False:self.cv.move(self.man, 0, -25)self.people_y -= 25self.nowroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.mylog('North: you are in the '+str(self.nowroom))for i in self.game.roomlist:if i == self.nowroom:self.game.currentRoom = iself.location.configure(text='Hi, '+str(PLAYER_NAME)+" Your location:" + str(self.game.JudgeInRoom(self.people_x, self.people_y)))self.label_HP.configure(text="Your life:" + str(self.game.player.life) + "HP")self.label_COIN.configure(text="Your coin:" + str(self.game.player.coins))self.mybag.configure(text="Your item:" + str(self.game.player.bag))self.label_KEY.configure(text="Your key:" + str(self.game.player.total_keys))elif self.res==True:messagebox.showinfo("GAME OVER", "Congratulations!\nYOU win!")self.mylog('You win ')self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)else:self.mylog('You lose the game')messagebox.showinfo("GAME OVER","You have no enough life!\nYOU LOSE!")self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)def South(self):'''Consistent with North()'''if self.game.monster_HP>0:self.label_warning.configure(text="Please go to the second floor to destroy the monster")if self.game.player.total_keys<6:self.label_warning2.configure(text="Please go find enough keys to pass the game")if self.game.player.life > 0:self.oldroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.nowroom = self.game.JudgeInRoom(self.people_x, self.people_y+25)if self.oldroom!=self.nowroom and self.nowroom=="doorway":self.res=self.game.roomplay(self.people_x, self.people_y,self)if self.game.JudgeInMap(self.people_x, self.people_y+25) == True and self.res==False:self.cv.move(self.man, 0, 25)self.people_y += 25self.nowroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.mylog('South: you are in the ' + str(self.nowroom))for i in self.game.roomlist:if i == self.nowroom:self.game.currentRoom = iself.mybag.configure(text="Your item:" + str(self.game.player.bag))self.location.configure(text='Hi, '+str(PLAYER_NAME)+" Your location:" + str(self.game.JudgeInRoom(self.people_x, self.people_y)))self.label_HP.configure(text="Your life:" + str(self.game.player.life) + "HP")self.label_COIN.configure(text="Your coin:" + str(self.game.player.coins))self.label_KEY.configure(text="Your key:" + str(self.game.player.total_keys))elif self.res==True:self.mylog('You win ')messagebox.showinfo("GAME OVER", "Congratulations!\nYOU win!")self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)else:self.mylog('You lose the game')messagebox.showinfo("GAME OVER","You have no enough life!\nYOU LOSE!")self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)def East(self):'''Consistent with North()'''if self.game.monster_HP>0:self.label_warning.configure(text="Please go to the second floor to destroy the monster")if self.game.player.total_keys<6:self.label_warning2.configure(text="Please go find enough keys to pass the game")if self.game.player.life > 0:self.oldroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.nowroom = self.game.JudgeInRoom(self.people_x +25, self.people_y)if self.oldroom!=self.nowroom and self.nowroom=="doorway":self.res=self.game.roomplay(self.people_x, self.people_y,self)if self.game.JudgeInMap(self.people_x+25,self.people_y)==True and self.res==False:self.cv.move(self.man, 25, 0)self.people_x += 25self.nowroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.mylog('East: you are in the ' + str(self.nowroom))for i in self.game.roomlist:if i == self.nowroom:self.game.currentRoom=iself.location.configure(text='Hi, '+str(PLAYER_NAME)+" Your location:" + str(self.game.JudgeInRoom(self.people_x, self.people_y)))self.label_HP.configure(text="Your life:" + str(self.game.player.life) + "HP")self.label_COIN.configure(text="Your coin:" + str(self.game.player.coins))self.label_KEY.configure(text="Your key:" + str(self.game.player.total_keys))self.mybag.configure(text="Your item:" + str(self.game.player.bag))elif self.res==True:self.mylog('You win ')messagebox.showinfo("GAME OVER", "Congratulations!\nYOU win!")self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)else:self.mylog('You lose the game')messagebox.showinfo("GAME OVER","You have no enough life!\nYOU LOSE!")self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)def West(self):'''Consistent with North()'''if self.game.monster_HP>0:self.label_warning.configure(text="Please go to the second floor to destroy the monster")if self.game.player.total_keys<6:self.label_warning2.configure(text="Please go find enough keys to pass the game")if self.game.player.life > 0:self.oldroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.nowroom = self.game.JudgeInRoom(self.people_x-25, self.people_y)if self.oldroom!=self.nowroom and self.nowroom=="doorway":self.res=self.game.roomplay(self.people_x, self.people_y,self)if self.oldroom==self.game.portal.roomname:#messagebox.showinfo('11',f'{self.people_x,self.people_y}')self.cv.delete(self.man)self.man = self.cv.create_image(self.people_x, self.people_y, anchor=NW, image=self.character)if self.game.JudgeInMap(self.people_x-25,self.people_y)==True and self.res==False:self.cv.move(self.man, -25, 0)self.people_x -= 25self.nowroom = self.game.JudgeInRoom(self.people_x, self.people_y)self.mylog('West: you are in the ' + str(self.nowroom))for i in self.game.roomlist:if i == self.nowroom:self.game.currentRoom = iself.mybag.configure(text="Your item:" + str(self.game.player.bag))self.location.configure(text='Hi, '+str(PLAYER_NAME)+" Your location:" + str(self.game.JudgeInRoom(self.people_x, self.people_y)))self.label_HP.configure(text="Your life:" + str(self.game.player.life) + "HP")self.label_COIN.configure(text="Your coin:" + str(self.game.player.coins))self.label_KEY.configure(text="Your key:" + str(self.game.player.total_keys))elif self.res==True:self.mylog('You win ')messagebox.showinfo("GAME OVER", "Congratulations!\nYOU win!")self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)else:self.mylog('You lose the game')messagebox.showinfo("GAME OVER","You have no enough life!\nYOU LOSE!")self.frame1.destroy()self.frame2.destroy()myApp = MyGame_thirdUI(self.root)def about(self):'''View game background'''self.mylog('View game background')messagebox.showinfo("Background","You are in a shabby base. ""\nYou are alone. You wander.""\nThere is a magical item in the shabby base to help you go home.""\nYou need to reach the designated location with enough keys.""\nSo start your adventure.")def mylog(self, action):"""Create a log to record the user's action"""with open("log.txt", "a") as f:f.write("\n------------------------------------------------------------------------------\n")f.write(str(datetime.datetime.now()) + '\n')f.write(str(action + '\n'))f.close()class MyGame_thirdUI:def __init__(self, root):# Create the model instance ...self.root = rootself.game_again=Game()self.root.config()self.overframe = tk.Frame(self.root, width=1100, height=600)self.overframe.pack_propagate(0)  # Prevents resizingself.overframe.pack(side=TOP)self.gameover_image = ImageTk.PhotoImage(Image.open('images/gameover.jpg'))self.gameover = tk.Label(self.overframe, image=self.gameover_image, width=1100, height=468)self.gameover.pack(side=TOP)self.button_again=tk.Button(self.overframe,text="PLAY ANAIN",command=lambda :self.change())self.button_again.pack(side=TOP)def change(self):"""close the  secondUI and start the firstUI"""self.overframe.destroy()myApp = MyGame_FIRSTUI(self.root,0)def main():win = tk.Tk()                           # Create a windowwin.title("MY GAME")                  # Set window titlewin.geometry("1100x650")                 # Set window sizewin.resizable(False, False)             # Both x and y dimensions ...# Create the GUI as a Frame# and attach it to the window ...myApp = MyGame_FIRSTUI(win,0)# Call the GUI mainloop ...win.mainloop()if __name__ == "__main__":main()

Game代码如下:

import random
from tkinter.simpledialog import askintegerfrom Room import Room
import unittest
from Player import Player
from tkinter import messagebox
"""
Create a room and save the coordinate information and name of the room as a dictionary.
The user can only move within the map.
Determine the room where the user is based on the location of the player,
and play the game corresponding to the room.
"""class Test(unittest.TestCase):def setUp(self):'''initialization'''self.game=Game()self.testroom=Room("in the test",'testroom')self.game.roomlist.insert(0,self.testroom)self.game.rec_roomlist.insert(0,(100,100,400,400))self.game.rec_roomdic["testroom"] = self.game.roomlist[0]'''test the room object'''def test_01(self):self.assertEqual(self.game.roomlist[0],self.testroom)'''test the room list'''def test_02(self):self.assertEqual(self.game.rec_roomdic["testroom"] ,self.game.roomlist[0])'''Test whether the player is in the mapTest the room the player is in'''def test_03(self):self.assertTrue(self.game.JudgeInMap(25,25))self.assertFalse(self.game.JudgeInMap(25, 100))self.assertEqual(self.game.JudgeInRoom(225,225),"lab")self.assertEqual(self.game.JudgeInRoom(2, 2),None)def tearDown(self):'''Delete test object'''del self.testroomclass Game:def __init__(self):"""Initialises the gamerec_roomlist=[] Store coordinate informationrec_roomdic = {} #Store coordinate information and name(key)"""self.roomlist = [] #objectself.player = Player()self.createRooms()self.currentRoom = self.outside# self.textUI = TextUI()self.rec_roomlist=[] #Store coordinate informationself.rec_roomdic = {} #Store coordinate information and room name(key)self.rec_doorway_dic={}##Store coordinate information and doorway name(key)self.rec_room()self.monster_HP = 100def createRooms(self):"""Sets up all room and assetsappend the room as object into a list:return: None"""#Set up the roomself.outside = Room("You are outside a shabby base","outside")#1self.lobby = Room("in the lobby","lobby")#2self.corridor = Room("in a corridor","corridor") #3self.lab = Room("in a computing lab","lab") #4self.office = Room("in the computing admin office","office") #5self.garden = Room("in the garden","garden") #6self.lounge = Room("in the lounge","lounge") #7self.dinningroom = Room("in the dinning room","dinningroom")#8self.storehouse=Room("in the storehouse","storehouse") #9self.basement=Room("in the basement","basement") #10self.gym=Room("in the gym","gym") #11self.destination=Room("in the destination","destination") #12self.shop=Room("in the shop","shop")#13self.portal =Room("in a teleport magic circle","portal") #Random teleportself.doorway = Room("in the doorway", "doorway")self.roomlist.append(self.outside)self.roomlist.append(self.lobby)self.roomlist.append(self.corridor)self.roomlist.append(self.lab)self.roomlist.append(self.office)self.roomlist.append(self.garden)self.roomlist.append(self.lounge)self.roomlist.append(self.dinningroom)self.roomlist.append(self.gym)self.roomlist.append(self.destination)self.roomlist.append(self.shop)self.roomlist.append(self.storehouse)self.roomlist.append(self.portal)self.roomlist.append(self.doorway)self.roomlist.append(self.basement)#Set up items and keysself.lab.setKeys("Golden key")self.lab.setTools("potionBlue")self.lab.setTools("potionGreen")self.lab.setTools("potionRed")self.lab.randomDrop()self.corridor.setTools("potionBlue")self.corridor.setTools("bomb")self.corridor.setKeys("Silver key")self.corridor.randomDrop()self.storehouse.setKeys("Ordinary key")self.storehouse.setTools("rotten apple")self.storehouse.setTools("potionGreen")self.basement.setTools("rotten apple")self.basement.setTools("potionGreen")self.basement.setKeys("Ordinary key")self.basement.randomDrop()self.office.setKeys("Ordinary key")self.office.setTools("potionGreen")self.garden.setKeys("Ordinary key")self.garden.setTools("apple")self.garden.setTools("potionRed")self.garden.setTools("shield")self.garden.randomDrop()self.gym.setTools("shield")self.dinningroom.setTools("rotten food")self.dinningroom.setTools("water")#self.dinningroom.randomDrop()self.lobby.setKeys("Ordinary key")self.lobby.setTools("food")def rec_room(self):"""List:append the location of each roomDictionary :Storage room and coordinate relationship"""self.rec_roomlist.append((25, 25, 175, 100))#garden0self.rec_roomlist.append((25, 125, 175, 200))#corridor1self.rec_roomlist.append((25, 225, 175, 300))#lounge2self.rec_roomlist.append((25, 325, 175, 400))#gym3self.rec_roomlist.append((25, 425, 175, 500))#destination4self.rec_roomlist.append((225, 125, 375, 200))#outside5self.rec_roomlist.append((225, 225, 375, 300))#lab6self.rec_roomlist.append((225, 325, 375, 400))#storehouse7self.rec_roomlist.append((225, 425, 375, 500))#basement8self.rec_roomlist.append((425, 125, 575, 200))#lobby9self.rec_roomlist.append((425, 225, 575, 300))#office10self.rec_roomlist.append((425, 325, 575, 400))#Portal11self.rec_roomlist.append((625, 125, 775, 200))#diningroom12self.rec_roomlist.append((625, 225, 775, 300))#shop13#doorself.rec_roomlist.append((75, 100, 125, 125))#14self.rec_roomlist.append((75, 200, 125, 225))#15self.rec_roomlist.append((75, 300, 125, 325))#16self.rec_roomlist.append((75, 400, 125, 425))#17self.rec_roomlist.append((175, 150, 225, 175))#18self.rec_roomlist.append((275,200,325,225))#19self.rec_roomlist.append((275,300,325,325))#20self.rec_roomlist.append((275,400,325,425))#21self.rec_roomlist.append((375,150,425,175))#22self.rec_roomlist.append((375,250,425,275))#23self.rec_roomlist.append((375,350,425,375))#24self.rec_roomlist.append((575,150,625,175))#25self.rec_roomlist.append((575,250,625,275))#26self.rec_roomlist.append((675,200,725,225))#27self.rec_roomlist.append((175,450,225,475))#28self.rec_roomlist.append((75,500,125,550))#29self.rec_roomdic["garden"]=self.rec_roomlist[0]self.rec_roomdic.update({"corridor": self.rec_roomlist[1]})self.rec_roomdic.update({"lounge": self.rec_roomlist[2]})self.rec_roomdic.update({"gym": self.rec_roomlist[3]})self.rec_roomdic.update({"destination": self.rec_roomlist[4]})self.rec_roomdic.update({"outside": self.rec_roomlist[5]})self.rec_roomdic.update({"lab": self.rec_roomlist[6]})self.rec_roomdic.update({"storehouse": self.rec_roomlist[7]})self.rec_roomdic.update({"basement": self.rec_roomlist[8]})self.rec_roomdic.update({"lobby": self.rec_roomlist[9]})self.rec_roomdic.update({"office": self.rec_roomlist[10]})self.rec_roomdic.update({"portal": self.rec_roomlist[11]})self.rec_roomdic.update({"dinningroom": self.rec_roomlist[12]})self.rec_roomdic.update({"shop": self.rec_roomlist[13]})self.rec_doorway_dic.update({'doorway1': self.rec_roomlist[14],'doorway2':self.rec_roomlist[15],'doorway3':self.rec_roomlist[16],'doorway4':self.rec_roomlist[17],'doorway5':self.rec_roomlist[18],'doorway6':self.rec_roomlist[19],'doorway7': self.rec_roomlist[20],'doorway8':self.rec_roomlist[21],'doorway9':self.rec_roomlist[22],'doorway10':self.rec_roomlist[23],'doorway11':self.rec_roomlist[24], 'doorway12':self.rec_roomlist[25],'doorway13':self.rec_roomlist[26], 'doorway14':self.rec_roomlist[27],'doorway15':self.rec_roomlist[28],'doorway16':self.rec_roomlist[29]})def JudgeInMap(self,people_x,people_y):"""judge if the user is in the map"""for i in self.rec_roomlist:if (people_x>=i[0] and people_x<=i[2] and people_y>=i[1] and people_y<=i[3]) and \(people_x+25>=i[0] and people_x+25<=i[2] and people_y+25>=i[1] and people_y+25<=i[3]):return Truereturn Falsedef JudgeInRoom(self,people_x,people_y):"""judge which room the user is in the mapif in the room , return room name (str)if in the doorway, return doorway(str)"""for i,room_point in enumerate(self.rec_roomlist):if (people_x>=room_point[0] and people_x<=room_point[2] and people_y>=room_point[1] and people_y<=room_point[3])\and (people_x+25>=room_point[0] and people_x+25<=room_point[2] and people_y+25>=room_point[1] and people_y+25<=room_point[3]):for k in self.rec_roomdic.keys():if self.rec_roomdic[k]==room_point:room_name=kreturn room_namefor k in self.rec_doorway_dic.keys():if self.rec_doorway_dic[k]==room_point:room_name='doorway'return room_namedef roomplay(self,people_x,people_y,gui):"""through the method JudgeInRoom() to decide the playConditions for entering the last room: destinationIf the number of keys is greater than 6and destroy the monsters on the second floorNeed to choose 2:Wipe Twice can pass the gameTeleport room:Random teleport (dinningroom storehouse garden lounge outside)"""wantToQuit = Falseself.currentRoom=self.JudgeInRoom(people_x,people_y)for i in self.roomlist:if i.roomname == self.currentRoom:self.currentRoom=iif self.currentRoom !=self.outside:if self.currentRoom==self.destination:if self.player.total_keys >= 6:if self.monster_HP<=0:while self.player.life > 0:try:number = askinteger("Just type the munber", "There is a light here...""\nWhat do you want to do with it?""\n1:Throw Away  2:Wipe Twice 3:Wipe Once""\nJust type the munber")if number == 2:messagebox.showinfo("NOTE", "A elves have been showing up""\nHe sent you home and gave you a lot of wealth""\nCongratulations, you win the game!")self.player.coins += 100wantToQuit = Truebreakelif number == 1:messagebox.showinfo("NOTE", "A elves have been showing up""He is very angry!""And you die!")Player.life -= 1elif number == 3:messagebox.showinfo("NOTE", "A elves have been showing up""He gives you some money!""Please try again")self.player.coins += 10except ValueError:print("Oops! That was no valid number. Try again...")else:messagebox.showinfo("Note", "Please go to the second floor \nto destroy the monster")else:messagebox.showinfo("Note", "You do not have enough keys \nto trigger the game of destination")elif self.currentRoom==self.gym:self.gym.randomDrop()self.player.gym()self.player.gettool(self.currentRoom)elif self.currentRoom==self.garden:self.player.garden()self.garden.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom==self.corridor:self.player.corridor()self.corridor.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom== self.basement:self.player.basement()self.basement.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom== self.lobby:self.player.lobby()self.lobby.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom== self.dinningroom:self.player.dinningroom()self.dinningroom.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom== self.office:self.player.office()self.office.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom== self.lounge:messagebox.showinfo("note","There is no tool in this room")self.player.lounge()elif self.currentRoom== self.storehouse:self.player.storehouse()self.storehouse.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom==self.lab:self.player.lab()self.lab.randomDrop()self.player.gettool(self.currentRoom)elif self.currentRoom== self.shop:self.player.shop()# Random deliveryelif self.currentRoom==self.portal:messagebox.showinfo("Note","There's a magical teleport circle on the ground""\nYou open the door and randomly teleport to a room")i = random.randint(1, 5)print(i)if i == 1:#self.currentRoom = self.dinningroomgui.people_x=675gui.people_y=150elif i == 2:#self.currentRoom = self.storehousegui.people_x=275gui.people_y=350elif i == 3:#self.currentRoom = self.gardengui.people_x=75gui.people_y=150elif i == 4:#self.currentRoom = self.loungegui.people_x=75gui.people_y=250elif i == 5:#self.currentRoom = self.outsidegui.people_x=275gui.people_y=150return wantToQuit

Room代码如下:

"""
Create a room
And place props and keys in the room
"""
import unittest
import randomclass Test(unittest.TestCase):def setUp(self):'''#initialization'''self.room1=Room("You are in testroom1","room1")self.room2 = Room("You are in testroom2","room2")self.room1.setTools("test tool")def test_01(self):'''#test tool'''self.assertEqual(self.room1.randomDrop(),"test tool")self.assertIsNone(self.room2.randomDrop())def tearDown(self):'''Delete test object'''del self.room1del self.room2class Room:def __init__(self, description,roomname):"""Constructor method:param description: text description for this room"""self.description = descriptionself.roomname=roomnameself.exits = {}     # Dictionary The optional room after going out is saved as a dictionaryself.tools=[]self.keys=[]def setKeys(self,keys):'''set keys:param keys::return:'''self.keys.append(keys)def setTools(self,tools):'''set item:param tools::return:'''self.tools.append(tools)def randomDrop(self):'''If there are more than one props in the roomthe props will be dropped randomly:return: currenttool'''if self.tools==[]:return Noneelse:totaltoolsnumber=len(self.tools)tool=random.randrange(totaltoolsnumber)currenttool=self.tools[tool]return currenttool# def setExit(self, direction, neighbour):#     """#         Adds an exit for a room. The exit is stored as a dictionary#         entry of the (key, value) pair (direction, room)#     :param direction: The direction leading out of this room#     :param neighbour: The room that this direction takes you to#     :return: None#     key——direction#     value——room##     """#     self.exits[direction] = neighbour### def getShortDescription(self):#     """#         Fetch a short text description#     :return: text description#     """#     return self.description## def getLongDescription(self):#     """#         Fetch a longer description including available exits#     :return: text description##     """#     return f'Location: {self.description}, Exits: {self.getExits()} '## def getExits(self):#     """#         Fetch all available exits as a list#     :return: list of all available exits##     """#     allExits = self.exits.keys()#     return list(allExits)## def getExit(self, direction):#     """#         Fetch an exit in a specified direction#     :param direction: The direction that the player wishes to travel#     :return: Room object that this direction leads to, None if one does not exist#     """#     if direction in self.exits:#         return self.exits[direction]#     else:#         return "Doorway"

Player代码如下:

'''
Create a new class
Record player information:HP, KEYS, BAG, COINS
And the games in each room
'''from tkinter import messagebox, RIGHT, LEFT, TOP, NW
from tkinter import Button
from tkinter.simpledialog import askinteger, askstringclass Player:life=3total_keys=0coins=10def __init__(self):'''Initialize the Player ClassSave props and props effects as a dictionarySave items and item prices as a dictionarySave Key and key value as a dictionary'''self.bag=["potionBlue"]self.weapon=[]self.keys=[]self.toolslist={"potionRed":3,"potionGreen":2,"potionBlue":1,"apple":2,"rubbish":-2,"bomb":-3,"shield":1,"rotten food":-3,"food":1,"water":1} #props and props effectsself.keyslist={"Golden key":3,"Silver key":2,"Ordinary key":1} #Key and key valueself.shoplist={"potionRed":3,"potionGreen":2, "apple":2,"potionBlue":1, "shield":1,"food":1} #items and item pricesdef gettool(self,currentRoom):'''Add a new command to allow the user to pick up items when in a roomWhen the number of items in the backpack is less than 4,the player is asked whether to pick up the item,otherwise the player is reminded to use the item in time.'''if currentRoom.setTools !=[]:item=currentRoom.randomDrop()ans = messagebox.askquestion('Question', "There is a "+str(item)+". \nDo you want pick up ?")if ans == "yes":try:self.bag.append(item)if len(self.bag) > 4:raise(OverflowError())except OverflowError:self.bag.remove(currentRoom.randomDrop())messagebox.showwarning("warning","The bag is full, please use the items in time")else:messagebox.showwarning("NEW TOOL","You have a new tool:"+str(item))def seeweapon(self):'''check all the weapon you have:return: NONE'''if len(self.weapon)!=0:messagebox.showinfo("Weapon","Your weapon:"+str(self.weapon))else:messagebox.showinfo("Weapon", "NONE" )def seeTools(self):'''check all the tool you have:return: NONE'''if len(self.bag )!= 0:messagebox.showinfo("YOUR BAG:",self.bag)else:messagebox.showinfo("YOUR BAG:","There is no item in your bag.")def useTools(self):'''use the tool you haveEnter the name of the item,an error will be reported if the item does not exist'''var_string = askstring("Note",prompt="You have the following things in your bag\n"+str(self.bag)+"\nwhich tool do you want to use")try:if var_string in self.bag:life=self.toolslist[var_string]self.life=self.life+lifeself.bag.pop(self.bag.index(var_string))messagebox.showinfo("NOTE: ","Successful\nYour current HP:"+str(self.life)+"\nYour current bag\n:"+str(self.bag))elif var_string==None:messagebox.showinfo("NOTE","NO item to be used")else:raise(IOError())except IOError:messagebox.showinfo("Error","This item is not in the bag")def setkeys(self,currentRoom):'''Set room key'''if currentRoom.setKeys !=[]:self.keys.append(currentRoom.setKeys())def seekeys(self):'''Calculate the total number of keys'''a,b,c=0,0,0for i in self.keys:self.total_keys=a+b+c+self.total_keysif i=="Golden key":a+=3if i=="Silver key":b+=2if i=="Ordinary key":c+=1def lobby(self):'''Provide Office clues 110a weapon:Pistol'''messagebox.showinfo("Note","There is a note saying 110\nSeems to be a clue\nYou find a weapon:Pistol")self.weapon.append("Pistol")def corridor(self):'''Add a keya weapon:Knife'''messagebox.showinfo("Note","You find a Ordinary key\nYou find a weapon:Knife")self.weapon.append("Knife")self.total_keys += 1def lab(self):'''choose 2:do an experimentget a item:Bomb to open the doorand get a key'''while True:try:next = askinteger(title="INPUT 1 OR 2",prompt="There are many experimental equipments here.\nThere was an explosion in the laboratory\n1:do nothing \ 2:do an experiment ")if next ==2:messagebox.showinfo("NOTE","Bomb! You lose your one life\nBut you find a Ordinary key and a weapon:Bomb")self.total_keys += 1self.life -= 1self.weapon.append("Bomb")breakelif next==1:messagebox.showinfo("NOTE","nothing happened")breakexcept ValueError:print("Oops! That was no valid number. Try again...")continuedef office(self):"""clue is in the lobbyanswer:110Input integer typeIt will report an error when entering other types"""global nextmessagebox.showinfo("Note","This is a safe with a three-digit code""\nHint:The clue to the password seems to be in the lobby""\nYou only have one time")while True:try:var_int = askinteger(title="INPUT",prompt="Please enter an integer:")breakexcept ValueError:print("Oops! That was no valid number. Try again...")finally:if var_int == 110:messagebox.showinfo("Congratulation!"," Add a life! \nYou find a Golden key  ")self.life += 1self.total_keys += 3else:if self.life>=0:messagebox.showinfo("Sorry!","You are wrong!Loos a life")self.life -= 1else:messagebox.showinfo("Sorry!","You have no life")return Falsedef garden(self):"""You need to enter 2:taunting big bear to move the bear first ----self.bear_moved =True,and enter 3:go next room to leave the roomInput integer typeIt will report an error when entering other types"""messagebox.showinfo("Note","There is a bear in front of the door.""\nThe bear has a pot of honey.""\nHow are you going to avoid the bear and enter the next room?")self.bear_moved = Falsevar_int = askinteger("Please enter 1 or 2 or 3",prompt="1:steal honey \n2:taunting big bear \n3:go next room >")while not self.bear_moved:if var_int == 1:messagebox.showinfo("Note", "The bear looks at you then slaps your face off.\nYou lose your one life")self.life-=1var_int =  askinteger("Please enter your answer",prompt="1:steal honey \n2:taunting big bear \n3:go next room >")elif var_int == 2:messagebox.showinfo("Note","The bear has moved from the door. You can go through it now.")var_int = askinteger("Please enter your answer",prompt="1:steal honey \n2:taunting big bear \n3:go next room >")self.bear_moved = Truecontinueelif var_int == 3:messagebox.showinfo("Note","The bear gets pissed off and chews your leg off.\nLose one life")#var_int = askstring("Please enter your answer",prompt="1:steal honey \n2:taunting big bear \n3:go next room >")else:messagebox.showinfo("Note","I got no idea what that means.")var_int = askinteger("Please enter your answer",prompt="1:steal honey \n2:taunting big bear \n3:go next room >")while self.bear_moved:if var_int == 3:messagebox.showinfo("Note","You find a Ordinary key")self.total_keys += 1breakelse:var_int = askinteger("Please enter your answer",prompt="1:steal honey \n2:taunting big bear \n3:go next room >")def lounge(self):"""a weapon:Bow and arrowADD  3 coins and a key"""messagebox.showinfo("Note","You find a Ordinary key and some coins\nYou find a weapon:Bow and arrow")self.weapon.append("Bow and arrow")self.coins += 3self.total_keys += 1def dinningroom(self):"""Lose a life"""messagebox.showinfo("Note","You ate junk food.Lose a life")self.life -= 1def storehouse(self):"""Monsters: need weapon:bomb to killAfter the monster dies, there will be a lot of rewardsOtherwise lose a life"""messagebox.showinfo("Note","The door is blocked, you need to use a bomb")if "Bomb" in self.weapon:messagebox.showinfo("Note","You find a Silver key and some coins")self.total_keys += 2self.coins -= 2self.weapon.pop(self.weapon.index("Bomb"))else:messagebox.showinfo("Note","You have no BOMB,So you use a key to open")self.total_keys-=1def basement(self):"""You need to enter 2:Don't take away the goldTo get more rewardsInput integer typeIt will report an error when entering other types"""try:var_int = askinteger(title="Answer",prompt="There is a lot of gold here ""\nDo you want to take him away""\n1:Yes  2:No""\nPlease enter 1 or 2")if var_int==1:messagebox.showinfo("Note","You are a greedy person""\nlose a life")self.coins += 2self.life -= 1elif var_int==2:messagebox.showinfo("Note","You find a Golden key and get 5 coins")self.total_keys += 3self.coins += 5except ValueError:messagebox.showinfo("Note","I got no idea what that means.")def gym(self):"""Monsters: need weapon:Pistol or Bow and arrow  to killAfter the monster dies, there will be a lot of rewardsOtherwise lose a life"""messagebox.showinfo("Note","There is a wolf.You need a Pistol or Bow and arrow")if "Pistol" in self.weapon:messagebox.showinfo("Note","You kill the wolf with the pistol and find a golden key")self.total_keys += 3self.weapon.pop(self.weapon.index("Pistol"))elif "Bow and arrow" in self.weapon:messagebox.showinfo("Note","You kill the wolf with the pistol and find a golden key")self.total_keys += 3self.weapon.pop(self.weapon.index("Bow and arrow"))else:self.life -= 1messagebox.showinfo("Note","You have no Pistol and so lose a life")def shop(self):'''Consider adding a facility where a user can purchase items within rooms for use elsewhere in the game.Can only be purchased when the backpack weight is less than 4'''if len(self.bag) <= 4:ans=messagebox.askquestion('Question',"Do you want use your coins to buy some items?")if ans=='yes':var_string = askstring("STRING",prompt="which item do you want to buy?\nITEMS:"+str(self.shoplist.keys()))if var_string in self.shoplist:cost=self.shoplist[var_string]self.coins-=costmessagebox.showinfo("NOTE","Successful purchase\nCOST "+str(cost))self.bag.append(var_string)else:messagebox.showinfo("NOTE","Your bag is full")

Python基于tkinterGUI的冒险交互小游戏项目总结相关推荐

  1. Python制作简单的终端交互小游戏

    Python制作简单的终端交互小游戏 因为最近的集训课程中,老师让我们把python,java,nodejs都需要掌握,本人最常使用的是java,python许久没有用过,就想写一段逻辑来帮助自己复习 ...

  2. 【课程设计】基于Taro+React+Springboot+TaroUI+Python爬虫的网络音乐播放小程序详细设计实现

    [课程设计]基于Taro+React+Springboot+TaroUI+Python爬虫的网络音乐播放小程序详细设计实现 解决触摸穿透 自定义导航栏 文章目录 项目简介 功能截图 1.用户登录注册 ...

  3. 基于Python/Tkinter的飞机大战单机小游戏

    这是很早之前课余时间写的基于Python/Tkinter单机小游戏,用来练手,今天将代码贴出来,方便大家一起学习,通过Py/Tk对于学习GUI作为一个入口,其实是个不错入口,在这里推荐一下Tcl/Tk ...

  4. 基于Python实现图片格式转换的小程序

    基于Python实现图片格式转换的小程序 特点: 批量处理图片 转换常见的4种图片格式 运行窗口 运行窗口-1 选择图片(可批量选择)-2 假设选中4张JEPG格式的图片 格式选择窗口-3 假设选择目 ...

  5. 使用python的pygame做的小游戏项目:小船打鱼

    python小游戏项目:小船打鱼 成果展示 代码解析 go_fishing.py game_function.py game_stats.py scoreboard.py alien.py setti ...

  6. Python基于用户协同过滤算法电影推荐的一个小改进

    之前曾经推送过这个问题的一个实现,详见:Python基于用户协同过滤算法的电影推荐代码demo 在当时的代码中没有考虑一种情况,如果选出来的最相似用户和待测用户完全一样,就没法推荐电影了.所以,在实际 ...

  7. [智慧农业]Python基于改进YOLOv5的猕猴桃叶病害检测系统(完整源码&数据集&视频教程)

    1.背景 现如今由于农作物病虫害的多样性和复杂性,在特定的条件下其很容易在大范围内发生,导致农产品产量急剧下降.因此,预防和监测农作物病虫害已成为农业生产活动中的重要环节.当前,耕地面积逐渐减少,世界 ...

  8. Python基于YOLOv7和CRNN的车牌分割&识别系统(源码&教程)

    1.研究背景 随着科技的进步和社会需求的增长,近年来摄像头逐渐高清化.高帧率化,摄像头作为信息获取设备的载体也不再局限于固定场景.路口.路侧.室内.高位.低位等不同场景下产生了各种对于检测识别的需求, ...

  9. DOTS介绍+Unity DOTS-MAN小游戏项目实战

    文章目录 前言 一.1. What is DOTS and why we use it? 1.DOTS包含的主要元素(三件套) 2.Why we use it? 3.Where we use it? ...

最新文章

  1. 图论 ---- CF1495D .BFS Trees(图论最短路生成树+枚举计数+树的层次性)
  2. TCP的3次握手和4次挥手过程
  3. “桥铁”旅行团春节昌旺 业界称成港人出游新模式
  4. 【LuKS】Vba if not c is nothing
  5. gorm 密码字段隐藏_非常专业且免费的密码管理工具
  6. 直男们给我看清楚!这才是小姐姐的真面目......
  7. 【剑指offer】_06 变态跳台阶
  8. 前端学习(2469):echart复习电商管理通过erchart加载数据
  9. Qt工作笔记-通过C++使widgets与QQuick交互(包含qml界面对象与C++对象映射)
  10. 神经网络不收敛的查缺补漏
  11. olcd12864的u8g2库_U8G2 软件包单色1.3寸OLED屏驱动在 RT-Thread 移植问题
  12. http协议编程java_Java与Http协议的详细介绍
  13. openwrt lede_在openwrt lede接入点上的免费动态dns服务提供商配置
  14. eterm 350转443转接器
  15. 爱玩软件 | win10桌面美化
  16. 小程序pdf预览插件_微信小程序中预览 PDF 文档
  17. webpack+plugin插件机制+weboack dev server工具
  18. 如何查看计算机有无无线连接功能,你可能不知道的,电脑自带的WIFI信号发射功能!...
  19. 论文笔记之:Co-saliency Detection via A Self-paced Multiple-instance Learning Framework
  20. 产品设计如何鼓励用户上传头像?

热门文章

  1. Dcmtk在PACS开发中的应用(基础篇)打印影像(胶片)
  2. 关于工信部批准发布138项通信行业标准等876项行业标准的公告
  3. 【Python】实例属性不能通过类访问,案例演示
  4. 第五天:全国计算机等级考试C语言专题
  5. oracle语句怎么查工作日,oracle查询一年中的工作日
  6. 我电脑里有用的数据在哪里?
  7. 小明Q1投影仪好不好?适合新手小白使用吗?
  8. 使用conda安装旧版本torch0.2.0
  9. Linux系统如何操作关机或重启180.188.22.X
  10. Qt 播放Yuv420p视频