目录
前言
游戏说明
1.游戏地图
2.类图
3.代码
Python课程的作业,最初的版本是玩家使用文字进行游戏,但实际体验感相当差,现在利用GUI进行可视化交互,方便玩家进行游戏。
不过许多功能是为了踩点拿分做,代码结构现在回过来看看emmm。但总之对能跑起来,各个功能都可以正常运行,没啥大bug。
这是一款冒险游戏。玩家在一个破败的基地中醒来。玩家需要通过探索基地来寻找帮助其回家的物品,但也会有许多陷阱和宝藏。玩家需要在基地收集足够的钥匙,击败怪物方可逃离。
游戏地图为两张,分为一层和二层,只有收集所需武器以及钥匙才可以击杀最终boss
一层地图:
二层地图:
代码主要分为四个部分:GUI(负责界面交互)、Game(游戏主要逻辑)、Room(游戏房间设置)、Player(玩家HP、武器、钥匙等物品)
顺便设置了自动化测试(确保功能可以正常运行)以及log记录(方便玩家查看自己的行动历史)
GUI代码如下:
import tkinter as tk
from tkinter import messagebox, RIGHT, LEFT, TOP, NW, DISABLED, NORMAL, BOTTOM
import tkinter
from PIL import ImageTk, Image
from Game import Game
import datetime
class MyGame_FIRSTUI:
def __init__(self, root,PLAYER_IMAGE):
'''
User initial interface
Enter user nickname
:param root:
'''
# Create the model instance ...
self.PLAYER_IMAGE=PLAYER_IMAGE
#PLAYER_IMAGE=0
self.root = root
self.root.config()
self.userframe = tk.Frame(self.root, width=1100, height=700)
self.userframe.pack_propagate(0) # Prevents resizing
self.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 secondUI
Global variable: PLAYER_NAME
Error prevention and recovery
"""
global PLAYER_NAME
try:
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_IMAGE
self.PLAYER_IMAGE=1
def Avatar2(self):
#global PLAYER_IMAGE
self.PLAYER_IMAGE=2
class MyGame_secondUI:
def __init__(self, root,PLAYER_IMAGE):
'''
The main interface of the game
:param root:
'''
# Create the model instance ...
self.PLAYER_IMAGE=PLAYER_IMAGE
self.game = Game()
self.res = False
self.root = root
self.people_x=225
self.people_y=125
self.nowroom='outside'
# Create the GUI
#add menubar
menubar=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 frame
self.frame1 = tk.Frame(root, width=850,height=640, bg='GREY', borderwidth=2)
self.frame1.pack_propagate(0) # Prevents resizing
self.frame1.pack(side = LEFT)
self.frame2 = tk.Frame(root, width=250, height=650, borderwidth=2)
self.frame2.pack_propagate(0) # Prevents resizing
self.frame2.pack(side = RIGHT)
self.frame3 = tk.Frame(self.frame2, width=250, height=350, borderwidth=2)
self.frame3.pack_propagate(0) # Prevents resizing
self.frame3.pack(side = TOP)
self.frame4 = tk.Frame(self.frame2, width=250, height=350, borderwidth=2)
self.frame4.pack_propagate(0) # Prevents resizing
self.frame4.pack(side = TOP)
self.frame5 = tk.Frame(self.frame2, width=250, height=350, borderwidth=2)
self.frame5.pack_propagate(0) # Prevents resizing
self.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_IMAGE
if 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 button
options = ['background introduction', 'button introduction'] # List with all options
self.v = tk.StringVar(self.frame3)
self.v.set("help") # default value
self.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)
#direction
self.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)
#LABEL
self.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_room
self.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 backpack
If using the wrong item causes the health to be less than 0
The game is over
You 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 GARDEN
monster Different attack ways will have different damage
Create a new framework and Forget Frame1 and Frame 2
South east north west cannot be used
Can only use down
downstairs:Reposition the frame1
Monsters will not refresh repeatedly
"""
#GUI
self.frame1.pack_forget()
self.frame6=tk.Frame(self.root,width=850,height=640, bg='GREY', borderwidth=2)
self.frame6.pack_propagate(0) # Prevents resizing
self.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 method
One attack reduces the monster's HP by 50
and causes 1Hp damage to yourself
'''
if self.game.player.life > 0:
if self.game.monster_HP>0:
self.game.monster_HP-=50
self.game.player.life-=1
messagebox.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 = 0
messagebox.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+=5
self.game.player.coins+=10
self.game.player.total_keys+=5
self.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 method
One attack reduces the monster's HP by 20
and causes 1Hp damage to yourself
'''
if self.game.player.life > 0:
if self.game.monster_HP>0:
self.game.monster_HP-=20
self.game.player.life -= 1
messagebox.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 = 0
messagebox.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+=5
self.game.player.coins+=10
self.game.player.total_keys+=5
self.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 floor
forget 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 buttons
First
judge whether the key is enough
and 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 insufficient
If it is enough,
judge whether the now room is the same as the old room,
if nowroom != oldroom ,return Flag=False
Then 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 Flag
Update 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 -= 25
self.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 = i
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.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 += 25
self.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 = i
self.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 += 25
self.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=i
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))
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 -= 25
self.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 = i
self.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 = root
self.game_again=Game()
self.root.config()
self.overframe = tk.Frame(self.root, width=1100, height=600)
self.overframe.pack_propagate(0) # Prevents resizing
self.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 window
win.title("MY GAME") # Set window title
win.geometry("1100x650") # Set window size
win.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 askinteger
from 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 map
Test 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.testroom
class Game:
def __init__(self):
"""
Initialises the game
rec_roomlist=[] Store coordinate information
rec_roomdic = {} #Store coordinate information and name(key)
"""
self.roomlist = [] #object
self.player = Player()
self.createRooms()
self.currentRoom = self.outside
# self.textUI = TextUI()
self.rec_roomlist=[] #Store coordinate information
self.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 = 100
def createRooms(self):
"""
Sets up all room and assets
append the room as object into a list
:return: None
"""
#Set up the room
self.outside = Room("You are outside a shabby base","outside")#1
self.lobby = Room("in the lobby","lobby")#2
self.corridor = Room("in a corridor","corridor") #3
self.lab = Room("in a computing lab","lab") #4
self.office = Room("in the computing admin office","office") #5
self.garden = Room("in the garden","garden") #6
self.lounge = Room("in the lounge","lounge") #7
self.dinningroom = Room("in the dinning room","dinningroom")#8
self.storehouse=Room("in the storehouse","storehouse") #9
self.basement=Room("in the basement","basement") #10
self.gym=Room("in the gym","gym") #11
self.destination=Room("in the destination","destination") #12
self.shop=Room("in the shop","shop")#13
self.portal =Room("in a teleport magic circle","portal") #Random teleport
self.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 keys
self.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 room
Dictionary :Storage room and coordinate relationship
"""
self.rec_roomlist.append((25, 25, 175, 100))#garden0
self.rec_roomlist.append((25, 125, 175, 200))#corridor1
self.rec_roomlist.append((25, 225, 175, 300))#lounge2
self.rec_roomlist.append((25, 325, 175, 400))#gym3
self.rec_roomlist.append((25, 425, 175, 500))#destination4
self.rec_roomlist.append((225, 125, 375, 200))#outside5
self.rec_roomlist.append((225, 225, 375, 300))#lab6
self.rec_roomlist.append((225, 325, 375, 400))#storehouse7
self.rec_roomlist.append((225, 425, 375, 500))#basement8
self.rec_roomlist.append((425, 125, 575, 200))#lobby9
self.rec_roomlist.append((425, 225, 575, 300))#office10
self.rec_roomlist.append((425, 325, 575, 400))#Portal11
self.rec_roomlist.append((625, 125, 775, 200))#diningroom12
self.rec_roomlist.append((625, 225, 775, 300))#shop13
#door
self.rec_roomlist.append((75, 100, 125, 125))#14
self.rec_roomlist.append((75, 200, 125, 225))#15
self.rec_roomlist.append((75, 300, 125, 325))#16
self.rec_roomlist.append((75, 400, 125, 425))#17
self.rec_roomlist.append((175, 150, 225, 175))#18
self.rec_roomlist.append((275,200,325,225))#19
self.rec_roomlist.append((275,300,325,325))#20
self.rec_roomlist.append((275,400,325,425))#21
self.rec_roomlist.append((375,150,425,175))#22
self.rec_roomlist.append((375,250,425,275))#23
self.rec_roomlist.append((375,350,425,375))#24
self.rec_roomlist.append((575,150,625,175))#25
self.rec_roomlist.append((575,250,625,275))#26
self.rec_roomlist.append((675,200,725,225))#27
self.rec_roomlist.append((175,450,225,475))#28
self.rec_roomlist.append((75,500,125,550))#29
self.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 True
return False
def JudgeInRoom(self,people_x,people_y):
"""
judge which room the user is in the map
if 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=k
return room_name
for k in self.rec_doorway_dic.keys():
if self.rec_doorway_dic[k]==room_point:
room_name='doorway'
return room_name
def roomplay(self,people_x,people_y,gui):
"""
through the method JudgeInRoom() to decide the play
Conditions for entering the last room: destination
If the number of keys is greater than 6
and destroy the monsters on the second floor
Need to choose 2:Wipe Twice can pass the game
Teleport room:
Random teleport (dinningroom storehouse garden lounge outside)
"""
wantToQuit = False
self.currentRoom=self.JudgeInRoom(people_x,people_y)
for i in self.roomlist:
if i.roomname == self.currentRoom:
self.currentRoom=i
if 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 += 100
wantToQuit = True
break
elif number == 1:
messagebox.showinfo("NOTE", "A elves have been showing up"
"He is very angry!"
"And you die!")
Player.life -= 1
elif number == 3:
messagebox.showinfo("NOTE", "A elves have been showing up"
"He gives you some money!"
"Please try again")
self.player.coins += 10
except 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 delivery
elif 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.dinningroom
gui.people_x=675
gui.people_y=150
elif i == 2:
#self.currentRoom = self.storehouse
gui.people_x=275
gui.people_y=350
elif i == 3:
#self.currentRoom = self.garden
gui.people_x=75
gui.people_y=150
elif i == 4:
#self.currentRoom = self.lounge
gui.people_x=75
gui.people_y=250
elif i == 5:
#self.currentRoom = self.outside
gui.people_x=275
gui.people_y=150
return wantToQuit
Room代码如下:
"""
Create a room
And place props and keys in the room
"""
import unittest
import random
class 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.room1
del self.room2
class Room:
def __init__(self, description,roomname):
"""
Constructor method
:param description: text description for this room
"""
self.description = description
self.roomname=roomname
self.exits = {} # Dictionary The optional room after going out is saved as a dictionary
self.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 room
the props will be dropped randomly
:return: currenttool
'''
if self.tools==[]:
return None
else:
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, askstring
class Player:
life=3
total_keys=0
coins=10
def __init__(self):
'''
Initialize the Player Class
Save props and props effects as a dictionary
Save items and item prices as a dictionary
Save 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 effects
self.keyslist={"Golden key":3,"Silver key":2,"Ordinary key":1} #Key and key value
self.shoplist={"potionRed":3,"potionGreen":2, "apple":2,"potionBlue":1, "shield":1,"food":1} #items and item prices
def gettool(self,currentRoom):
'''
Add a new command to allow the user to pick up items when in a room
When 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 have
Enter 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+life
self.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,0
for i in self.keys:
self.total_keys=a+b+c+self.total_keys
if i=="Golden key":
a+=3
if i=="Silver key":
b+=2
if i=="Ordinary key":
c+=1
def lobby(self):
'''
Provide Office clues 110
a 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 key
a weapon:Knife
'''
messagebox.showinfo("Note","You find a Ordinary key\nYou find a weapon:Knife")
self.weapon.append("Knife")
self.total_keys += 1
def lab(self):
'''
choose 2:do an experiment
get a item:Bomb to open the door
and 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 += 1
self.life -= 1
self.weapon.append("Bomb")
break
elif next==1:
messagebox.showinfo("NOTE","nothing happened")
break
except ValueError:
print("Oops! That was no valid number. Try again...")
continue
def office(self):
"""
clue is in the lobby
answer:110
Input integer type
It will report an error when entering other types
"""
global next
messagebox.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:")
break
except 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 += 1
self.total_keys += 3
else:
if self.life>=0:
messagebox.showinfo("Sorry!","You are wrong!Loos a life")
self.life -= 1
else:
messagebox.showinfo("Sorry!","You have no life")
return False
def 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 room
Input integer type
It 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 = False
var_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-=1
var_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 = True
continue
elif 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 += 1
break
else:
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 arrow
ADD 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 += 3
self.total_keys += 1
def dinningroom(self):
"""
Lose a life
"""
messagebox.showinfo("Note","You ate junk food.Lose a life")
self.life -= 1
def storehouse(self):
"""
Monsters: need weapon:bomb to kill
After the monster dies, there will be a lot of rewards
Otherwise 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 += 2
self.coins -= 2
self.weapon.pop(self.weapon.index("Bomb"))
else:
messagebox.showinfo("Note","You have no BOMB,So you use a key to open")
self.total_keys-=1
def basement(self):
"""
You need to enter 2:Don't take away the gold
To get more rewards
Input integer type
It 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 += 2
self.life -= 1
elif var_int==2:
messagebox.showinfo("Note","You find a Golden key and get 5 coins")
self.total_keys += 3
self.coins += 5
except ValueError:
messagebox.showinfo("Note","I got no idea what that means.")
def gym(self):
"""
Monsters: need weapon:Pistol or Bow and arrow to kill
After the monster dies, there will be a lot of rewards
Otherwise 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 += 3
self.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 += 3
self.weapon.pop(self.weapon.index("Bow and arrow"))
else:
self.life -= 1
messagebox.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-=cost
messagebox.showinfo("NOTE","Successful purchase\nCOST "+str(cost))
self.bag.append(var_string)
else:
messagebox.showinfo("NOTE","Your bag is full")