use Python to make a game

在学习完类的相关知识后,作者建议自己试着用类制作游戏,于是我就按照他的方法制作了一个和他的游戏类似的小游戏。

作者制作游戏的流程大致是:

The process is as follows:

  1. Write or draw about the problem.
  2. Extract key concepts from #1 and research them.
  3. Create a class hierarchy and object map for the concepts.
  4. Code the classes and a test to run them.
  5. Repeat and refine.

总的来说就是提取提到的问题的关键词,然后解决对应的问题。
作者的这句话说的很好:

make a list of all the nouns and verbs in your writing

名词用来写类名,动词用函数解决。这样思路就比较清晰了,解决问题思路清晰,有迹可循。
1、问题描述:游戏( 寻宝游戏),制作大致五个地图,每一个地图设置不同的闯关难题,让玩家参与互动,进行闯关;每通过一个关卡,就会得到对应的奖励,和对应的宝藏之玉碎片。五个地图全部闯关成功,集齐五个碎片,就能成功获得宝物,游戏结束;每个地图闯关失败,会有对应的惩罚甚至是造成闯关失败!

2、关键词提取:地图名字;互动内容;惩罚机制;闯关成功

3、我设置六个地图的名字:
ELFRoom;
TigerRoom;
BabyRoom;
EinsteinRoom;
DragonRoom;
ReadingRoom;
DeathRoom.
互动内容:自己在每个关卡设置对应的问题或者任务,答对或者完成就可通过本关卡。
惩罚:重新进入关卡,或者直接宣告死亡(闯关失败)!
争取把前边的内容都尽可能用上,复习一下,熟能生巧。

地图名字 互动内容
ELFRoom 引入地图
TigerRoom 打架or挑逗 打败老虎,得到碎片
BabyRoom 救下Baby,得到碎片
EinsteinRoom 智力问答,得到碎片
DragonRoom 帮助王子救下公主,得到碎片
ReadingRoom 猜中文件中的内容,得到最后一个碎片
DeathRoom 挑战失败

4、完成这部分工作后,进行对事件进行类处理。

  • 设置场景(Scene)为父类;

ELFRoom;TigerRoom;BabyRoom;EinsteinRoom;DragonRoom;ReadingRoom;DeathRoomf

都是作为它的子类存在。

  • 设置地图(Map)为父类,使进入地图有迹可循;
  • 设置引擎(Engine)为父类,使其能正常切换场景
    确定类的关系后,进一步确定每个类应该有的函数:
    Scene() 应该包括进入地图函数;
    Map()应该包括初始化函数,切换地图函数,打开地图函数;
    Engine()应该包括初始化函数,运行函数。

5、接下来就是书写游戏框架,进行初步调试:

class Engine(object):
	def __init__(self):
		pass
	def play(self):
		pass
		
class Scene(object):
	def enter(self):
		pass
		
class Map(object):
	def __init__(self):
		pass
	def next_scene(slef):
		pass
	def opening_scene(self):
		pass

class ElfRoom(Scene):
	def enter(self):
		pass

class TigerRoom(Scene):
	def enter(self):
		pass

class BabyRoom(Scene):
	def enter(self):
		pass
		
class EinsteinRoom(Scene):
	def enter(self):
		pass
		
class DragonRoom(Scene):
	def enter(self):
		pass
		
class ReadingRoom(Scene):
	def enter(self):
		pass
		
class Death(Scene):
	def enter(self):
		pass
	
	

运行结果是:


PS C:\Users\15222> cd lpthw
PS C:\Users\15222\lpthw> python debug.py
PS C:\Users\15222\lpthw>

说明框架书写正确,没有错误。
6、接下来,对框架添加对应的函数(自己想办法添加各种考验,每个关卡尽量形式多样,并且顺便当作复习前边学习的知识),实现寻宝功能。这里我继续运用书中老师的游戏运行框架。

这是我完善后的代码:

from sys import argv
from sys import exit
from random import randint


script, filename = argv



global count
count = 0
class Engine(object):
	def __init__(self, scene_map):
		self.scene_map = scene_map
		
	
	def play(self):
		current_scene = self.scene_map.opening_scene()
		while True:
			next_scene_name = current_scene.enter()  #  find the next map 
			current_scene = self.scene_map.next_scene(next_scene_name)    #
		
class Scene(object):
	def enter(self):
		print "This scene is not yet configured. Subclass it and implement enter()."   #this sentence is not clear
		exit(1)
		

class Death(Scene):
	mocks = [
		"You died. You kinda suck at this.",
		"Your mom would be proud...if she were smarter.",
		"Such a luser.",
		"I have a small puppy that's better at this."
	]
	def enter(self):
		
		print "Loser!"
		
		print Death.mocks[randint(0,len(self.mocks)-1)]
		exit(1)
	
		
		
		
class ElfRoom(Scene):
	def enter(self):
		print "\n\n----------------------------"
		print "Welcome to this game"
		print "you'll use your intelligeant and body to"
		print "beat the NPC in every room."
		print "Are you ready?"
		ans = raw_input(">>>")
		if ans:
			print "\n\n"
			print "Ok"
			print "You'll pledge into the first room."
			print "Loading......"
			return 'tiger_room'
		else:
			print "\n\n"
			print "Are you kidding me?"
			print "Please ready quickly"
			print "And come on again!!"
			return 'elf_room'
		
class TigerRoom(Scene):
	def enter(self):
		global count
		print "\n\n----------------------------"
		print "This is a tiger_room"
		print "The tiger is stare at you angrily."
		print "Find an idea to let it happy "
		print "And you will beat it."
		idea = raw_input(">>>")
		if idea == 'tickle':
		
			print "\n\nThis tiger is a big cat in fact"
			print "Use green brist legrass can let him happy"
			print "Yes, brillant"
			print "You got a clip"
			print "You'll Meet the next challenge!"
			count += 1
			return 'baby_room'
		elif idea == 'clasp':
			print "\n\nOh,no "
			print "This is a tragedy"
			print "The tiger is so angery"
			print "And you're die!"
			return 'death'
		else:
			print "\n\nI'm not sure are you doing"
			print "Please try it again"
			return 'tiger_room'

		
		
class BabyRoom(Scene):
	def enter(self):
		global count
		print "\n\n----------------------------"
		print "This is a baby_room"
		print "Thre baby is crying"
		print "Find what do he want to do"
		print "Let you go"
		ans1 = raw_input(">>")
		#ans2 == raw_input(">>")
		#ans3 == raw_input(">>")
		answer = ['eat', 'drink', 'pee']
		if ans1 == answer[0] or ans1 == answer[1] or ans1 == answer[2]:
			print "\n\nYou're right"
			print "The baby is not cry."
			print "You're take care of children"
			print "You got a clip."
			print "You'll Meet the next challenge!"
			count += 1
			return 'einstein_room'
		else:
			print "\n\nYou don't know how to make baby happy "
			print "This is a big challenge"
			print "Please try again."
			return 'baby_room'
class EinsteinRoom(Scene):
	def enter(self):
		global count
		print "\n\n----------------------------"
		print "This is einstein_room"
		print "This man is good at math "
		print "And you need challenge his math"
		print "Only beat him"
		print "can you through this pass"
		print "Just do it "
		input1 = int(raw_input(">>"))
		input2 = int(raw_input(">>"))
		input3 = int(raw_input(">>"))
		res1 = 9 % 2
		res2 = 256 + 2 - 100
		res3 = 9 // 2
		if input1 == res1 and input2 == res2 and input3 == res3:
			print "\n\nYou're so cool"
			print "Your brain is incredible"
			print "You get a clip"
			print "You'll Meet the next challenge!"
			count += 1
			return 'dragon_room'
		else:
			print "\n\nYou have some error in your answer"
			print "I'm so sorry"
			print "Please do it again"
			return 'einstein_room'
		
class DragonRoom(Scene):
	def enter(self):
		global count
		print "\n\n----------------------------"
		print "This is dragon_room"
		print "The princess is snatched"
		print "The prince is anxious about her"
		print "Please help the prince"
		print "Save the prince"
		print "This dragon is bizzaed by the True and Flase"
		print "HELP him he'll let the princess go "
		a = int(raw_input('1  0  -1  \n>>'))
		if a > 0:
			print "\n\nYou're right"
			print "This is a problem"
			print "And you're right"
			count += 1
			return 'reading_room'
		else:
			print "\n\nThis is not true"
			print "You're die"
			return 'death'
		
			 
		
class ReadingRoom(Scene):
	def enter(self):
		global count
		print "\n\n----------------------------"
		print "This is reading_room"
		print "And this is the last room"
		print "Across this room, you'll win"
		print "You need guess what things in the box"
		print "Just do it"
		wenjian = open(filename,'r')
		a = wenjian.readline()
		#a = wenjain.readline(len(a))
		#b = wenjian.readline()
		#c = wenjian.readline()
		fin1 = raw_input(">>")
		#fin2 = raw_input(">>")
		#fin3 = raw_input(">>")
		wenjian.close()
		print "%r" % a
		
		if fin1 == a :#and fin2 == b and fin3 == c:
			print "\n\nYou're good"
			print "And your answer is right"
			print "You win"
			count += 1
			print "You enter in %d rooms" % count
			#return  'finish'
			exit(1)
			
	#	elif not fin1 == a# and not fin2 == b and not fin3 == c:
		#	print "You're so good "
		#	print "Your answer is not correct"
		#	print "at all"
		#	return 'death'
		
		else:
			print "\n\nYour answer isn't correct"
			print "Please answer it again"
			return "reading_room"
			
			
			
			
class Map(object):
	scenes ={
				'elf_room': ElfRoom(),
				'tiger_room': TigerRoom(),
				'baby_room':BabyRoom(),
				'einstein_room':EinsteinRoom(),
				'dragon_room':DragonRoom(),
				'reading_room':ReadingRoom(),
				'death':Death()
				}
	def __init__(self, start_scene):
		self.start_scene = start_scene
	def next_scene(self, scenename):
		return Map.scenes.get(scenename)
	def opening_scene(self):
		return self.next_scene(self.start_scene)
		
		
a_map = Map('elf_room')
a_game =Engine(a_map)
a_game.play() 

通关的运行结果是:

PS C:\Users\15222\lpthw> python ex45.py ex45.txt


----------------------------
Welcome to this game
you'll use your intelligeant and body to
beat the NPC in every room.
Are you ready?
>>>True



Ok
You'll pledge into the first room.
Loading......


----------------------------
This is a tiger_room
The tiger is stare at you angrily.
Find an idea to let it happy
And you will beat it.
>>>tickle


This tiger is a big cat in fact
Use green brist legrass can let him happy
Yes, brillant
You got a clip
You'll Meet the next challenge!


----------------------------
This is a baby_room
Thre baby is crying
Find what do he want to do
Let you go
>>eat


You're right
The baby is not cry.
You're take care of children
You got a clip.
You'll Meet the next challenge!


----------------------------
This is einstein_room
This man is good at math
And you need challenge his math
Only beat him
can you through this pass
Just do it
>>1
>>158
>>4


You're so cool
Your brain is incredible
You get a clip
You'll Meet the next challenge!


----------------------------
This is dragon_room
The princess is snatched
The prince is anxious about her
Please help the prince
Save the prince
This dragon is bizzaed by the True and Flase
HELP him he'll let the princess go
1  0  -1
>>1


You're right
This is a problem
And you're right


----------------------------
This is reading_room
And this is the last room
Across this room, you'll win
You need guess what things in the box
Just do it
>>200
'200'


You're good
And your answer is right
You win
You enter in 5 rooms
PS C:\Users\15222\lpthw>

失败的运行结果是:

PS C:\Users\15222\lpthw> python ex45.py ex45.txt


----------------------------
Welcome to this game
you'll use your intelligeant and body to
beat the NPC in every room.
Are you ready?
>>>True



Ok
You'll pledge into the first room.
Loading......


----------------------------
This is a tiger_room
The tiger is stare at you angrily.
Find an idea to let it happy
And you will beat it.
>>>tickle


This tiger is a big cat in fact
Use green brist legrass can let him happy
Yes, brillant
You got a clip
You'll Meet the next challenge!


----------------------------
This is a baby_room
Thre baby is crying
Find what do he want to do
Let you go
>>eat


You're right
The baby is not cry.
You're take care of children
You got a clip.
You'll Meet the next challenge!


----------------------------
This is einstein_room
This man is good at math
And you need challenge his math
Only beat him
can you through this pass
Just do it
>>1
>>158
>>4


You're so cool
Your brain is incredible
You get a clip
You'll Meet the next challenge!


----------------------------
This is dragon_room
The princess is snatched
The prince is anxious about her
Please help the prince
Save the prince
This dragon is bizzaed by the True and Flase
HELP him he'll let the princess go
1  0  -1
>>0


This is not true
You're die
Loser!
You died. You kinda suck at this.
PS C:\Users\15222\lpthw>

运行结果比较顺利。

  • 比较需要注意的问题:

1、全局变量的使用:在每个函数中调用全局变量时,都应该定义好这个变量,必然会报错处理。

2、类的使用过程中,每个类下的函数的变量调用时应该是 self.XXXX 的形式,不然编译器不认识是哪个的变量。

3、 在对文件进行操作时,最终要记得关闭文件close()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章