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()

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