Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
271241651a
18 changed files with 936 additions and 0 deletions
48
kjg/python-the-hard-way/baseballgame.py
Normal file
48
kjg/python-the-hard-way/baseballgame.py
Normal file
|
@ -0,0 +1,48 @@
|
|||
import baseballgameclass
|
||||
|
||||
|
||||
|
||||
# initial fucntion
|
||||
size = []
|
||||
cGameNumber = baseballgameclass.GameNumber()
|
||||
guess = []
|
||||
checknewgame = 0
|
||||
inputset = {}
|
||||
inputset = set()
|
||||
|
||||
# assign class
|
||||
cInputNumber = baseballgameclass.InputNumber()
|
||||
cCheckNumber = baseballgameclass.CheckNumber()
|
||||
cPrintResult = baseballgameclass.PrintResult()
|
||||
|
||||
|
||||
while True:
|
||||
|
||||
if checknewgame == 0: # check new game
|
||||
# get game size and max of number
|
||||
size = cInputNumber.getGameSize()
|
||||
inputset = cGameNumber.createNumberSet(size[1], size[0])
|
||||
number = cGameNumber.createGameNumber(inputset)
|
||||
checknewgame = 1
|
||||
elif checknewgame != 3: # running game
|
||||
while True:
|
||||
guess = cInputNumber.getNumber(size[0]) # get created gaem number
|
||||
result3 = cCheckNumber.compareNumber(number, guess) # compare input number and game number
|
||||
cPrintResult.printResult(result3) # print result
|
||||
# print(number)
|
||||
if result3[0] == size[0]:
|
||||
print('You win.')
|
||||
newgame = input('continue a game (y or n) : ')
|
||||
if newgame == 'y':
|
||||
checknewgame = 0 # continue game
|
||||
break
|
||||
else:
|
||||
checknewgame = 3 # stop game
|
||||
break
|
||||
elif checknewgame == 3: # exit game
|
||||
break
|
||||
|
||||
|
||||
|
||||
|
||||
|
115
kjg/python-the-hard-way/baseballgameclass.py
Normal file
115
kjg/python-the-hard-way/baseballgameclass.py
Normal file
|
@ -0,0 +1,115 @@
|
|||
import random
|
||||
|
||||
|
||||
class GameNumber():
|
||||
# create game's numbers
|
||||
|
||||
# create number set for game
|
||||
def createNumberSet(self, amount, gamesize):
|
||||
s = {}
|
||||
s = set()
|
||||
while len(s) < gamesize:
|
||||
# add set as gamesize
|
||||
s.add(random.randint(0, amount-1))
|
||||
|
||||
print(s)
|
||||
return s
|
||||
|
||||
# create game number list
|
||||
def createGameNumber(self, gameSet):
|
||||
numbers = []
|
||||
for k in gameSet:
|
||||
numbers.append(k)
|
||||
print(k)
|
||||
|
||||
return numbers
|
||||
|
||||
|
||||
class CheckNumber():
|
||||
# check number whether it is right
|
||||
|
||||
# compare number between a guess answer and a right answer
|
||||
def compareNumber(self, gameNumber, guessNumber):
|
||||
result = []
|
||||
strike = 0
|
||||
ball = 0
|
||||
|
||||
for i in range(len(gameNumber)):
|
||||
print(guessNumber)
|
||||
if guessNumber[i] == gameNumber[i]:
|
||||
# check number of strke
|
||||
strike += 1
|
||||
elif guessNumber[i] in gameNumber:
|
||||
# check number of ball
|
||||
ball += 1
|
||||
|
||||
# add results of strike and ball
|
||||
result.append(strike)
|
||||
result.append(ball)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class InputNumber():
|
||||
# user inputs numbers
|
||||
|
||||
def getGameSize(self):
|
||||
amountNumber = []
|
||||
while True: # check wrong input
|
||||
temp = input('put a game size : ')
|
||||
try:
|
||||
if len(temp) > 1:
|
||||
raise
|
||||
|
||||
for i in temp:
|
||||
if i not in '0123456789':
|
||||
raise
|
||||
except:
|
||||
print('it is not number or too big, input again')
|
||||
else:
|
||||
amountNumber.append(int(temp))
|
||||
break
|
||||
|
||||
while True: # check wrong input
|
||||
temp = input('put a max of number : ')
|
||||
try:
|
||||
if len(temp) > 1:
|
||||
raise
|
||||
|
||||
for i in temp:
|
||||
if i not in '0123456789':
|
||||
raise
|
||||
except:
|
||||
print('it is not number or too big, input again')
|
||||
else:
|
||||
amountNumber.append(int(temp))
|
||||
|
||||
return amountNumber
|
||||
|
||||
def getNumber(self, gameSize):
|
||||
userGuess = []
|
||||
for i in range(gameSize):
|
||||
while True: # check wrong input
|
||||
print('put ', i+1, ' of numbers : ', end='')
|
||||
temp2 = input()
|
||||
try:
|
||||
if len(temp2) > 1:
|
||||
raise
|
||||
|
||||
for k in temp2:
|
||||
if k not in '0123456789':
|
||||
raise
|
||||
except:
|
||||
print('it is not number or too big, input again')
|
||||
else:
|
||||
userGuess.append(int(temp2))
|
||||
break
|
||||
|
||||
return userGuess
|
||||
|
||||
|
||||
class PrintResult():
|
||||
# print result
|
||||
|
||||
def printResult(self, result):
|
||||
print(result[0], ' strike, ', result[1], ' ball')
|
35
kjg/python-the-hard-way/calc.py
Normal file
35
kjg/python-the-hard-way/calc.py
Normal file
|
@ -0,0 +1,35 @@
|
|||
from sys import argv
|
||||
|
||||
script, file_name = argv
|
||||
|
||||
|
||||
def input_and_calculate_one_line():
|
||||
txt_result = ''
|
||||
number = input("> ")
|
||||
if number == 'q':
|
||||
txt_result = ''
|
||||
return txt_result
|
||||
|
||||
sp_number = number.split(' ')
|
||||
for i in range(len(sp_number) - 1):
|
||||
txt_result = txt_result + sp_number[i] + ' + '
|
||||
|
||||
sp_number = list(map(int, sp_number))
|
||||
result = sum(sp_number)
|
||||
txt_result = txt_result + str(sp_number[-1]) + ' = ' + str(result) + '\n'
|
||||
return txt_result
|
||||
|
||||
|
||||
def editor():
|
||||
txt = open(file_name, 'w')
|
||||
while True:
|
||||
output = input_and_calculate_one_line()
|
||||
if output == '':
|
||||
txt.close()
|
||||
exit(0)
|
||||
else:
|
||||
print(output)
|
||||
txt.write(output)
|
||||
|
||||
|
||||
editor()
|
26
kjg/python-the-hard-way/e37.py
Normal file
26
kjg/python-the-hard-way/e37.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
while 1:
|
||||
money = input("insert coin=>")
|
||||
number = input("select beverage\n")
|
||||
money = int(money)
|
||||
temp = money
|
||||
if number == "1":
|
||||
#grape 100
|
||||
print("you choose grape. change is ",money-100,"coin")
|
||||
money = temp-100 #callculate change
|
||||
if money <= 0: #check money
|
||||
break
|
||||
elif number == "2":
|
||||
#orange 200
|
||||
print("you choose orange. change is ",money-200,"coin")
|
||||
money = temp-200 #callculate change
|
||||
if money <= 0: #check money
|
||||
break
|
||||
elif number == "3":
|
||||
#fanta 300
|
||||
print("you choose fanta. change is ",money-300,"coin")
|
||||
money = temp-300 #callculate change
|
||||
if money <= 0: #check money
|
||||
break
|
||||
else:
|
||||
#wrong sellection
|
||||
print("wrong number. please select again")
|
17
kjg/python-the-hard-way/e38.py
Normal file
17
kjg/python-the-hard-way/e38.py
Normal file
|
@ -0,0 +1,17 @@
|
|||
ten_things = "Apples Oranges Crows Telephone Light Sugar"
|
||||
|
||||
print("Wait there are not 10 things in that list. Let's fix that.")
|
||||
|
||||
stuff = ten_things.split(' ')
|
||||
more_stuff = ["Day", "Night", "Song", "Frisbee","Corn", "Banana", "Girl", "Boy"]
|
||||
while len(stuff) != 10:
|
||||
next_one = more_stuff.pop()
|
||||
print("Adding: ", next_one)
|
||||
stuff.append(next_one)
|
||||
print(f"There are {len(stuff)} items now.")
|
||||
print("There we go: ", stuff)
|
||||
print("Let's do some things with stuff.")
|
||||
print(stuff[1])
|
||||
print(stuff[-1]) # whoa! fancy print(stuff.pop())
|
||||
print(' '.join(stuff)) # what? cool!
|
||||
print('#'.join(stuff[3:5])) # super stellar!
|
66
kjg/python-the-hard-way/e39.py
Normal file
66
kjg/python-the-hard-way/e39.py
Normal file
|
@ -0,0 +1,66 @@
|
|||
# create a mapping of state to abbreviation
|
||||
states = {
|
||||
'Kyungsangdo': 'KS',
|
||||
'Kangwondo': 'KW',
|
||||
'Jeju': 'JE',
|
||||
'Junlado': 'JL',
|
||||
'Chungchungdo': 'CC'
|
||||
}
|
||||
|
||||
# create a basic set of states and some cities in them
|
||||
cities = {
|
||||
'KS': 'Busan',
|
||||
'JE': 'Jejusi',
|
||||
'JL': 'Mokpo'
|
||||
}
|
||||
|
||||
# add some more cities
|
||||
cities['KW'] = 'Sokcho'
|
||||
cities['CC'] = 'Chungju'
|
||||
|
||||
# print out some cities
|
||||
print('-' * 10)
|
||||
print("KS State has: ", cities['KS'])
|
||||
print("KW State has: ", cities['KW'])
|
||||
|
||||
# print some states
|
||||
print('-' * 10)
|
||||
print("Kyungsangdo's abbreviation is: ", states['Kyungsangdo'])
|
||||
print("Kangwondo's abbreviation is: ", states['Kangwondo'])
|
||||
|
||||
# do it by using the state then cities dict
|
||||
print('-' * 10)
|
||||
print("Jeju has: ", cities[states['Jeju']])
|
||||
print("Junlado has: ", cities[states['Junlado']])
|
||||
|
||||
# print every state abbreviation
|
||||
print('-' * 10)
|
||||
for state, abbrev in list(states.items()):
|
||||
print(f"{state} is abbreviated {abbrev}")
|
||||
|
||||
# print every city in state
|
||||
print('-' * 10)
|
||||
for abbrev, city in list(cities.items()):
|
||||
print(f"{abbrev} has the city {city}")
|
||||
|
||||
|
||||
# now do both at the same time
|
||||
print('-' * 10)
|
||||
for state, abbrev in list(states.items()):
|
||||
print(f"{state} state is abbreviated {abbrev}")
|
||||
print(f"and has city {cities[abbrev]}")
|
||||
|
||||
|
||||
print('-' * 10)
|
||||
# safely get a abbreviation by state that might not be there
|
||||
state = states.get('Texas')
|
||||
|
||||
if not state:
|
||||
print("Sorry, no Texas.")
|
||||
|
||||
|
||||
# get a city with a default value
|
||||
city = cities.get('TX', 'Does Not Exist')
|
||||
print(f"The city for the state 'TX' is: {city}")
|
||||
|
||||
|
20
kjg/python-the-hard-way/e40.py
Normal file
20
kjg/python-the-hard-way/e40.py
Normal file
|
@ -0,0 +1,20 @@
|
|||
class Song(object):
|
||||
def __init__(self, lyrics):
|
||||
self.lyrics = lyrics
|
||||
|
||||
def sing_me_a_song(self):
|
||||
for line in self.lyrics:
|
||||
print(line)
|
||||
|
||||
|
||||
ly1 = ["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"]
|
||||
ly2 = ["They rally around tha family","With pockets full of shells"]
|
||||
|
||||
happy_bday = Song(ly1)
|
||||
|
||||
bulls_on_parade = Song(ly2)
|
||||
|
||||
|
||||
happy_bday.sing_me_a_song()
|
||||
|
||||
bulls_on_parade.sing_me_a_song()
|
87
kjg/python-the-hard-way/e41.py
Normal file
87
kjg/python-the-hard-way/e41.py
Normal file
|
@ -0,0 +1,87 @@
|
|||
import random
|
||||
from urllib.request import urlopen
|
||||
import sys
|
||||
|
||||
WORD_URL = "http://learncodethehardway.org/words.txt"
|
||||
WORDS = []
|
||||
|
||||
PHRASES = {
|
||||
"class %%%(%%%):":
|
||||
"Make a class named %%% that is-a %%%.",
|
||||
"class %%%(object):\n\tdef __init__(self, ***)" :
|
||||
"class %%% has-a __init__ that takes self and *** params.",
|
||||
"class %%%(object):\n\tdef ***(self, @@@)":
|
||||
"class %%% has-a function *** that takes self and @@@ params.",
|
||||
"*** = %%%()":
|
||||
"Set *** to an instance of class %%%.",
|
||||
"***.***(@@@)":
|
||||
"From *** get the *** function, call it with params self, @@@.",
|
||||
"***.*** = '***'":
|
||||
"From *** get the *** attribute and set it to '***'."
|
||||
}
|
||||
|
||||
# do they want to drill phrases first
|
||||
if len(sys.argv) == 2 and sys.argv[1] == "english":
|
||||
PHRASE_FIRST = True
|
||||
else:
|
||||
PHRASE_FIRST = False
|
||||
|
||||
|
||||
# load up the words from the website
|
||||
for word in urlopen(WORD_URL).readlines():
|
||||
WORDS.append(str(word.strip(), encoding="utf-8"))
|
||||
|
||||
|
||||
def convert(snippet, phrase):
|
||||
class_names = [w.capitalize() for w in
|
||||
random.sample(WORDS, snippet.count("%%%"))]
|
||||
other_names = random.sample(WORDS, snippet.count("***"))
|
||||
results = []
|
||||
param_names = []
|
||||
|
||||
for i in range(0, snippet.count("@@@")):
|
||||
param_count = random.randint(1,3)
|
||||
param_names.append(', '.join(
|
||||
random.sample(WORDS, param_count)))
|
||||
|
||||
for sentence in snippet, phrase:
|
||||
# this is how you duplicate a list or string
|
||||
result = sentence[:]
|
||||
|
||||
# fake class names
|
||||
for word in class_names:
|
||||
result = result.replace("%%%", word, 1)
|
||||
|
||||
# fake other names
|
||||
for word in other_names:
|
||||
result = result.replace("***", word, 1)
|
||||
|
||||
# fake parameter lists
|
||||
for word in param_names:
|
||||
result = result.replace("@@@", word, 1)
|
||||
|
||||
results.append(result)
|
||||
return results
|
||||
|
||||
|
||||
# keep going until they hit CTRL-D
|
||||
try:
|
||||
while True:
|
||||
snippets = list(PHRASES.keys())
|
||||
random.shuffle(snippets)
|
||||
|
||||
for snippet in snippets:
|
||||
phrase = PHRASES[snippet]
|
||||
question, answer = convert(snippet, phrase)
|
||||
if PHRASE_FIRST:
|
||||
question, answer = answer, question
|
||||
|
||||
print(question)
|
||||
input("> ")
|
||||
print(f"ANSWER: {answer}\n\n")
|
||||
|
||||
except EOFError:
|
||||
print("\nBye")
|
||||
|
||||
|
||||
|
83
kjg/python-the-hard-way/e42.py
Normal file
83
kjg/python-the-hard-way/e42.py
Normal file
|
@ -0,0 +1,83 @@
|
|||
## Animal is-a object (yes, sort of confusing) look at the extra credit
|
||||
class Animal(object):
|
||||
def something(self):
|
||||
print("base")
|
||||
|
||||
|
||||
## Dog is-a Animal
|
||||
class Dog(Animal):
|
||||
def __init__(self, name):
|
||||
## Dog has-a name
|
||||
self.name = name
|
||||
|
||||
|
||||
## Cat is-a Animal
|
||||
class Cat(Animal):
|
||||
def __init__(self, name):
|
||||
## Cat has-a name
|
||||
self.name = name
|
||||
|
||||
|
||||
## Person is-a object
|
||||
class Person(object):
|
||||
def __init__(self, name):
|
||||
## Person has-a name
|
||||
self.name = name
|
||||
## Person has-a pet of some kind
|
||||
self.pet = None
|
||||
|
||||
|
||||
## Employee is-a person
|
||||
class Employee(Person):
|
||||
def __init__(self, name, salary):
|
||||
## heritage from parents
|
||||
super(Employee, self).__init__(name)
|
||||
## Employee has-a salary
|
||||
self.salary = salary
|
||||
|
||||
|
||||
## Fish is-a object
|
||||
class Fish(object):
|
||||
def __init__(self):
|
||||
print("Base Fish")
|
||||
|
||||
|
||||
## Salmon is-a Fish
|
||||
class Salmon(Fish):
|
||||
pass
|
||||
|
||||
|
||||
## Halibut is-a Fish
|
||||
class Halibut(Fish):
|
||||
pass
|
||||
|
||||
|
||||
## rover is-a Dog
|
||||
rover = Dog("Rover")
|
||||
rover.something()
|
||||
## satan is-a Cat
|
||||
satan = Cat("Satan")
|
||||
|
||||
## mary is-a Person
|
||||
mary = Person("Mary")
|
||||
|
||||
## mary's pet is satan
|
||||
mary.pet = satan
|
||||
print(mary.pet.name)
|
||||
|
||||
## frank is-a Employee
|
||||
frank = Employee("Frank", 120000)
|
||||
|
||||
## frank's pet is rover
|
||||
frank.pet = rover
|
||||
print(frank.name)
|
||||
print(frank.pet.name)
|
||||
print(frank.salary)
|
||||
## flipper is-a Fish
|
||||
flipper = Fish()
|
||||
|
||||
## crouse is-a Salmon
|
||||
crouse = Salmon()
|
||||
|
||||
## harry is-a Halibut
|
||||
harry = Halibut()
|
253
kjg/python-the-hard-way/e43.py
Normal file
253
kjg/python-the-hard-way/e43.py
Normal file
|
@ -0,0 +1,253 @@
|
|||
from sys import exit
|
||||
from random import randint
|
||||
from textwrap import dedent
|
||||
|
||||
|
||||
class Scene(object):
|
||||
def enter(self):
|
||||
print("This scene is not yet configured.")
|
||||
print("Subclass it and implement enter().")
|
||||
exit(1)
|
||||
|
||||
|
||||
class Engine(object):
|
||||
def __init__(self, scene_map):
|
||||
self.scene_map = scene_map
|
||||
|
||||
def play(self):
|
||||
current_scene = self.scene_map.opening_scene()
|
||||
last_scene = self.scene_map.next_scene('finished')
|
||||
|
||||
while current_scene != last_scene:
|
||||
next_scene_name = current_scene.enter()
|
||||
current_scene = self.scene_map.next_scene(next_scene_name)
|
||||
|
||||
# be sure to print out the last scene
|
||||
current_scene.enter()
|
||||
|
||||
|
||||
class Death(Scene):
|
||||
quips = [
|
||||
"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.",
|
||||
"You're worse than your Dad's jokes."
|
||||
]
|
||||
|
||||
def enter(self):
|
||||
print(Death.quips[randint(0, len(self.quips)-1)])
|
||||
exit(1)
|
||||
|
||||
|
||||
class CentralCorridor(Scene):
|
||||
def enter(self):
|
||||
print(dedent("""
|
||||
The Gothons of Planet Percal #25 have invaded your ship and
|
||||
destroyed your entire crew. You are the last surviving
|
||||
member and your last mission is to get the neutron destruct
|
||||
bomb from the Weapons Armory, put it in the bridge, and
|
||||
blow the ship up after getting into an escape pod.
|
||||
|
||||
You're running down the central corridor to the Weapons
|
||||
Armory when a Gothon jumps out, red scaly skin, dark grimy
|
||||
teeth, and evil clown costume flowing around his hate
|
||||
filled body. He's blocking the door to the Armory and
|
||||
about to pull a weapon to blast you.
|
||||
"""))
|
||||
|
||||
action = input("> ")
|
||||
|
||||
if action == "handshake!":
|
||||
print(dedent("""
|
||||
Quick on the draw you yank out your blaster and fire
|
||||
it at the Gothon. His clown costume is flowing and
|
||||
moving around his body, which throws off your aim.
|
||||
Your laser hits his costume but misses him entirely.
|
||||
This completely ruins his brand new costume his mother
|
||||
bought him, which makes him fly into an insane rage
|
||||
and blast you repeatedly in the face until you are
|
||||
dead. Then he eats you.
|
||||
"""))
|
||||
return 'death'
|
||||
elif action == "dodge!":
|
||||
print(dedent("""
|
||||
Like a world class boxer you dodge, weave, slip and
|
||||
slide right as the Gothon's blaster cranks a laser
|
||||
past your head. In the middle of your artful dodge
|
||||
your foot slips and you bang your head on the metal
|
||||
wall and pass out. You wake up shortly after only to
|
||||
die as the Gothon stomps on your head and eats you.
|
||||
"""))
|
||||
return 'death'
|
||||
|
||||
elif action == "tell a joke":
|
||||
print(dedent("""
|
||||
Lucky for you they made you learn Gothon insults in
|
||||
the academy. You tell the one Gothon joke you know:
|
||||
Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr,
|
||||
fur fvgf nebhaq gur ubhfr. The Gothon stops, tries
|
||||
not to laugh, then busts out laughing and can't move.
|
||||
While he's laughing you run up and shoot him square in
|
||||
the head putting him down, then jump through the
|
||||
Weapon Armory door.
|
||||
"""))
|
||||
return 'laser_weapon_armory'
|
||||
|
||||
elif action == "cheat game":
|
||||
print(dedent("""
|
||||
you pass the gaem
|
||||
You win the gaem
|
||||
"""))
|
||||
return 'finished'
|
||||
else:
|
||||
print("DOES NOT COMPUTE!")
|
||||
return 'central_corridor'
|
||||
|
||||
|
||||
class LaserWeaponArmory(Scene):
|
||||
def enter(self):
|
||||
print(dedent("""
|
||||
You do a dive roll into the Weapon Armory, crouch and scan
|
||||
the room for more Gothons that might be hiding. It's dead
|
||||
quiet, too quiet. You stand up and run to the far side of
|
||||
the room and find the neutron bomb in its container.
|
||||
There's a keypad lock on the box and you need the code to
|
||||
get the bomb out. If you get the code wrong 10 times then
|
||||
the lock closes forever and you can't get the bomb. The
|
||||
code is 3 digits.
|
||||
"""))
|
||||
|
||||
code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
|
||||
guess = input("[keypad]> ")
|
||||
guesses = 0
|
||||
|
||||
while guess != code and guesses < 10:
|
||||
print("BZZZZEDDD!")
|
||||
guesses += 1
|
||||
guess = input("[keypad]> ")
|
||||
|
||||
if guess == code:
|
||||
print(dedent("""
|
||||
The container clicks open and the seal breaks, letting
|
||||
gas out. You grab the neutron bomb and run as fast as
|
||||
you can to the bridge where you must place it in the
|
||||
right spot.
|
||||
"""))
|
||||
return 'the_bridge'
|
||||
else:
|
||||
print(dedent("""
|
||||
The lock buzzes one last time and then you hear a
|
||||
sickening melting sound as the mechanism is fused
|
||||
together. You decide to sit there, and finally the
|
||||
Gothons blow up the ship from their ship and you die.
|
||||
"""))
|
||||
return 'death'
|
||||
|
||||
|
||||
class TheBridge(Scene):
|
||||
def enter(self):
|
||||
print(dedent("""
|
||||
You burst onto the Bridge with the netron destruct bomb
|
||||
under your arm and surprise 5 Gothons who are trying to
|
||||
take control of the ship. Each of them has an even uglier
|
||||
clown costume than the last. They haven't pulled their
|
||||
weapons out yet, as they see the active bomb under your
|
||||
arm and don't want to set it off.
|
||||
"""))
|
||||
|
||||
action = input("> ")
|
||||
|
||||
if action == "throw the bomb":
|
||||
print(dedent("""
|
||||
In a panic you throw the bomb at the group of Gothons
|
||||
and make a leap for the door. Right as you drop it a
|
||||
Gothon shoots you right in the back killing you. As
|
||||
you die you see another Gothon frantically try to
|
||||
disarm the bomb. You die knowing they will probably
|
||||
blow up when it goes off.
|
||||
"""))
|
||||
return 'death'
|
||||
elif action == "slowly place the bomb":
|
||||
print(dedent("""
|
||||
You point your blaster at the bomb under your arm and
|
||||
the Gothons put their hands up and start to sweat.
|
||||
You inch backward to the door, open it, and then
|
||||
carefully place the bomb on the floor, pointing your
|
||||
blaster at it. You then jump back through the door,
|
||||
punch the close button and blast the lock so the
|
||||
Gothons can't get out. Now that the bomb is placed
|
||||
you run to the escape pod to get off this tin can.
|
||||
"""))
|
||||
return 'escape_pod'
|
||||
else:
|
||||
print("DOES NOT COMPUTE!")
|
||||
return "the_bridge"
|
||||
|
||||
|
||||
class EscapePod(Scene):
|
||||
def enter(self):
|
||||
print(dedent("""
|
||||
You rush through the ship desperately trying to make it to
|
||||
the escape pod before the whole ship explodes. It seems
|
||||
like hardly any Gothons are on the ship, so your run is
|
||||
clear of interference. You get to the chamber with the
|
||||
escape pods, and now need to pick one to take. Some of
|
||||
them could be damaged but you don't have time to look.
|
||||
There's 5 pods, which one do you take?
|
||||
"""))
|
||||
|
||||
good_pod = randint(1,5)
|
||||
guess = input("[pod #]> ")
|
||||
|
||||
if int(guess) != good_pod:
|
||||
print(dedent(f"""
|
||||
You jump into pod {guess} and hit the eject button.
|
||||
The pod escapes out into the void of space, then
|
||||
implodes as the hull ruptures, crushing your body into
|
||||
jam jelly.
|
||||
"""))
|
||||
return 'death'
|
||||
else:
|
||||
print(dedent(f"""
|
||||
You jump into pod {guess} and hit the eject button.
|
||||
The pod easily slides out into space heading to the
|
||||
planet below. As it flies to the planet, you look
|
||||
back and see your ship implode then explode like a
|
||||
bright star, taking out the Gothon ship at the same
|
||||
time. You won!
|
||||
"""))
|
||||
|
||||
return 'finished'
|
||||
|
||||
|
||||
class Finished(Scene):
|
||||
def enter(self):
|
||||
print("You won! Good job.")
|
||||
return 'finished'
|
||||
|
||||
|
||||
class Map(object):
|
||||
scenes = {
|
||||
'central_corridor': CentralCorridor(),
|
||||
'laser_weapon_armory': LaserWeaponArmory(),
|
||||
'the_bridge': TheBridge(),
|
||||
'escape_pod': EscapePod(),
|
||||
'death': Death(),
|
||||
'finished': Finished(),
|
||||
}
|
||||
|
||||
def __init__(self, start_scene):
|
||||
self.start_scene = start_scene
|
||||
|
||||
def next_scene(self, scene_name):
|
||||
val = Map.scenes.get(scene_name)
|
||||
return val
|
||||
|
||||
def opening_scene(self):
|
||||
return self.next_scene(self.start_scene)
|
||||
|
||||
|
||||
a_map = Map('central_corridor')
|
||||
a_game = Engine(a_map)
|
||||
a_game.play()
|
52
kjg/python-the-hard-way/e43_classes.py
Normal file
52
kjg/python-the-hard-way/e43_classes.py
Normal file
|
@ -0,0 +1,52 @@
|
|||
class Scene(object):
|
||||
def enter(self):
|
||||
pass
|
||||
|
||||
|
||||
class Engine(object):
|
||||
def __init__(self, scene_map):
|
||||
pass
|
||||
|
||||
def play(self):
|
||||
pass
|
||||
|
||||
|
||||
class Death(Scene):
|
||||
def enter(self):
|
||||
pass
|
||||
|
||||
|
||||
class CentralCorridor(Scene):
|
||||
def enter(self):
|
||||
pass
|
||||
|
||||
|
||||
class LaserWeaponArmory(Scene):
|
||||
def enter(self):
|
||||
pass
|
||||
|
||||
|
||||
class TheBridge(Scene):
|
||||
def enter(self):
|
||||
pass
|
||||
|
||||
|
||||
class EscapePod(Scene):
|
||||
def enter(self):
|
||||
pass
|
||||
|
||||
|
||||
class Map(object):
|
||||
def __init__(self, start_scene):
|
||||
pass
|
||||
|
||||
def next_scene(self, scene_name):
|
||||
pass
|
||||
|
||||
def opening_scene(self):
|
||||
pass
|
||||
|
||||
|
||||
a_map = Map('central_corridor')
|
||||
a_game = Engine(a_map)
|
||||
a_game.play()
|
13
kjg/python-the-hard-way/e44a.py
Normal file
13
kjg/python-the-hard-way/e44a.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
class Parent(object):
|
||||
def implicit(self):
|
||||
print("PARENT implicit()")
|
||||
|
||||
|
||||
class Child(Parent):
|
||||
pass
|
||||
|
||||
|
||||
dad = Parent()
|
||||
son = Child()
|
||||
dad.implicit()
|
||||
son.implicit()
|
14
kjg/python-the-hard-way/e44b.py
Normal file
14
kjg/python-the-hard-way/e44b.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
class Parent(object):
|
||||
def override(self):
|
||||
print("PARENT override()")
|
||||
|
||||
|
||||
class Child(Parent):
|
||||
def override(self):
|
||||
print("CHILD override()")
|
||||
|
||||
|
||||
dad = Parent()
|
||||
son = Child()
|
||||
dad.override()
|
||||
son.override()
|
16
kjg/python-the-hard-way/e44c.py
Normal file
16
kjg/python-the-hard-way/e44c.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
class Parent(object):
|
||||
def altered(self):
|
||||
print("PARENT altered()")
|
||||
|
||||
|
||||
class Child(Parent):
|
||||
def altered(self):
|
||||
print("CHILD, BEFORE PARENT altered()")
|
||||
super(Child, self).altered()
|
||||
print("CHILD, AFTER PARENT altered()")
|
||||
|
||||
|
||||
dad = Parent()
|
||||
son = Child()
|
||||
dad.altered()
|
||||
son.altered()
|
34
kjg/python-the-hard-way/e44d.py
Normal file
34
kjg/python-the-hard-way/e44d.py
Normal file
|
@ -0,0 +1,34 @@
|
|||
class Parent(object):
|
||||
|
||||
def override(self):
|
||||
print("PARENT override()")
|
||||
|
||||
def implicit(self):
|
||||
print("PARENT implicit()")
|
||||
|
||||
def altered(self):
|
||||
print("PARENT altered()")
|
||||
|
||||
|
||||
class Child(Parent):
|
||||
|
||||
def override(self):
|
||||
print("CHILD, override()")
|
||||
|
||||
def altered(self):
|
||||
print("CHILD, BERFORE altered()")
|
||||
super(Child, self).altered()
|
||||
print("CHILD, AFTER PARENT altered()")
|
||||
|
||||
|
||||
dad = Parent()
|
||||
son = Child()
|
||||
|
||||
dad.implicit()
|
||||
son.implicit()
|
||||
|
||||
dad.override()
|
||||
son.override()
|
||||
|
||||
dad.altered()
|
||||
son.altered()
|
32
kjg/python-the-hard-way/e44e.py
Normal file
32
kjg/python-the-hard-way/e44e.py
Normal file
|
@ -0,0 +1,32 @@
|
|||
class Other(object):
|
||||
def override(self):
|
||||
print("OTHER override()")
|
||||
|
||||
def implicit(self):
|
||||
print("OTHER implicit()")
|
||||
|
||||
def altered(self):
|
||||
print("OTHER altered()")
|
||||
|
||||
|
||||
class Child(object):
|
||||
def __init__(self):
|
||||
self.other = Other()
|
||||
|
||||
def implicit(self):
|
||||
self.other.implicit()
|
||||
|
||||
def override(self):
|
||||
print("CHILD override()")
|
||||
|
||||
def altered(self):
|
||||
print("CHILD, BEFORE OTHER altered()")
|
||||
self.other.altered()
|
||||
print("CHILD, AFTER OTHER altered()")
|
||||
|
||||
|
||||
son = Child()
|
||||
|
||||
son.implicit()
|
||||
son.override()
|
||||
son.altered()
|
0
kjg/python-the-hard-way/sum.txt
Normal file
0
kjg/python-the-hard-way/sum.txt
Normal file
|
@ -133,3 +133,28 @@ How to use Accessing Elements of Lists
|
|||
practice function, while, if
|
||||
**** ex36
|
||||
some rules of if, loop and tips for debugging
|
||||
*** Python applying learnings from 1..6
|
||||
create calc.py
|
||||
*** Python #7
|
||||
**** ex37
|
||||
analysis sample codes
|
||||
**** ex38
|
||||
append list
|
||||
**** ex39
|
||||
How to use dictionary
|
||||
*** Python #8
|
||||
**** ex40
|
||||
How to use class
|
||||
**** ex41
|
||||
practice class
|
||||
*** Python #9
|
||||
**** ex42
|
||||
review class and object
|
||||
*** Python #10
|
||||
**** ex43
|
||||
Analysis and Design object
|
||||
*** Python #11
|
||||
**** ex44
|
||||
difference with inheritance and compositon
|
||||
*** Python #12
|
||||
create game
|
||||
|
|
Loading…
Reference in a new issue