2015-10-20 2 views
-2
import random 
import time 
import sys 
inventory = [] 
print "~~~~~~~~~~~~~~~~~~~~~~~~" 
print "  Welcome   " 
print "~~~~~~~~~~~~~~~~~~~~~~~~" 
print "You find youself waking up in a cold dark room." 
print "" 
print "You look around and find 3 door ways in front of you: One to the left, one to the right and one in the middle and a chest." 
print "" 
print "You have to make a choice. Type the direction of the room to enter the room or type 'Search' to search the chest." 
print "" 
choice = raw_input("Please make your selection:") 



if choice == ("Search") or ("search"): 
    print "You slowly walk towards the chest and reach in and find:" 
    x = random.randint(1,2) 
    if x == 1: 
     print "You find a sword!" 
     inventory.append("Sword") 
    if x == 2: 
     print "You find an axe!" 
     inventory.append("Axe") 
    print "You search some more..." 
    time.sleep(3) 
    y = random.randint(1,2) 
    if y == 1: 
     print "You also found a torch." 
     inventory.append("Torch") 
    if y == 2: 
     print "You also found a shield." 
     inventory.append("Shield") 
    choice = raw_input("Please pick a direction you'd like to go:") 



if choice == ("Left") or ("left"): 
    time.sleep(2) 
    print "You enter the room to the left" 
    string = "Torch" 
    if string in inventory: 
     print "You take your torch and look around." 
     time.sleep(2) 
     print"You notice a glimmer in the corner of the room." 
     time.sleep(2) 
     print"As you step closer you find that the glimmer starts to grow." 
     time.sleep(2) 
     print "As you come feet away, your torch reveales a giant spider!" 
     string = "Torch" 
     if string in inventory: 
      time.sleep(1) 
      print "You take out your torch!" 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      print ("     Fighting...     ") 
      print (" YOU MUST HIT ABOVE A 5 TO KILL THE SPIDER ") 
      print ("IF THE SPIDER HITS HIGHER THAN YOU, YOU WILL DIE") 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      time.sleep(2) 
      PDmg = int(random.randint(3, 10)) 
      EDmg = int(random.randint(1, 5)) 
      print ("You hit a", PDmg) 
      print ("The spider hits a", EDmg) 
      time.sleep(2) 
      #This part calculates who won 
      if EDmg > PDmg: 
       print ("The spider has done more damage and killed you!") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       print ("     GAME IS OVER!     ") 
       print ("     QUITTING PROGRAM    ") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       time.sleep(5) 
       sys.exit() 
      elif PDmg < 5: 
       print ("You managed to hit injure the spider, but not kill it.") 
       print ("Luckily, you escaped to the main room") 
       choice = raw_input("Please select a room to enter:") 
      elif PDmg > 5: 
       print "You killed the spider, congratulations!" 
       print "You have been rewarded with armour!" 
       print "You return to the main room!" 
       spider = 1 
       inventory.append("Armour") 
       choice = raw_input("Please select a room to enter:") 



    else: 
     print "You cannot see a thing! You squint to try and find any resources" 
     time.sleep(2) 
     print "You see a glimmer come closer and closer, what could it be!" 
     time.sleep(2) 
     print "It appears to be a giant spider!" 
     string = "Shield" 
     if string in inventory: 
      time.sleep(1) 
      print "You take out your trusty shield!" 
      time.sleep(2) 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      print ("     Fighting...     ") 
      print (" YOU MUST HIT ABOVE A 5 TO KILL THE SPIDER ") 
      print ("IF THE SPIDER HITS HIGHER THAN YOU, YOU WILL DIE") 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      time.sleep(2) 
      PDmg = int(random.randint(3, 10)) 
      EDmg = int(random.randint(1, 4)) 
      print ("You hit a", PDmg) 
      print ("The spider hits a", EDmg) 
      time.sleep(2) 
      #This part calculates who won 
      if EDmg > PDmg: 
       print ("The spider has done more damage and killed you!") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       print ("     GAME IS OVER!     ") 
       print ("     QUITTING PROGRAM    ") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       time.sleep(5) 
       sys.exit() 
      elif PDmg < 5: 
       print ("You managed to hit injure the spider, but not kill it.") 
       print ("Luckily, you escaped to the main room") 
       choice = raw_input("Please select a room to enter:") 
      elif PDmg > 5: 
       print "You killed the spider, congratulations!" 
       print "You have been rewarded with armour!" 
       print "You return to the main room!" 
       spider = 1 
       inventory.append("Armour") 
       choice = raw_input("Please select a room to enter:") 
     else: 
      print "You don't have anything in your inventory!" 
      print "You attempt to fight the spider..." 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      print ("     Fighting...     ") 
      print (" YOU MUST HIT ABOVE A 5 TO KILL THE SPIDER ") 
      print ("IF THE SPIDER HITS HIGHER THAN YOU, YOU WILL DIE") 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      time.sleep(2) 
      PDmg = int(random.randint(1, 2)) 
      EDmg = int(random.randint(1, 50)) 
      print ("You hit a", PDmg) 
      print ("The spider hits a", EDmg) 
      if EDmg > PDmg: 
       print ("The spider has done more damage and killed you!") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       print ("     GAME IS OVER!     ") 
       print ("     QUITTING PROGRAM    ") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       time.sleep(5) 
       sys.exit() 
      if PDmg > EDmg: 
       print "Somehow, you managed to tap the spider and run away alive!" 
       choice = raw_input("Please select a room to enter:") 

if choice == ("Right") or ("right"): 
    time.sleep(1) 
    print "You walk into the Right room." 
    time.sleep(1) 
    print "You find 3 bridges, and a sign:" 
    print "You may either leave empty handed, or pick the right path for a bounty." 
    Bchoice = input("Please select which bridge to cross: 1 , 2 , or , 3:") 
    if Bchoice == 2: 
     string = "Armour" 
     if string in inventory: 
      print "Crossing..." 
      time.sleep(2) 
      print "The bridge has not crumbled, you see a glimmering chest." 
      print "You find an extra sharp blade, it seems to be for cutting stone." 
      inventory.append("SharpBlade") 
      choice = raw_input("Please select a room:") 
     else: 
      print "Crossing..." 
      time.sleep(2) 
      print "The bridge has crumbled, you have fallen to your death." 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      print ("     GAME IS OVER!     ") 
      print ("     QUITTING PROGRAM    ") 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      time.sleep(5) 
      sys.exit() 
    else: 
     print "Crossing..." 
     time.sleep(2) 
     print "The bridge has crumbled, you have fallen to your death." 
     print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
     print ("     GAME IS OVER!     ") 
     print ("     QUITTING PROGRAM    ") 
     print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
     time.sleep(5) 
     sys.exit() 
if choice == ("Straight") or ("straight"): 
    print "You enter the middle room." 
    time.sleep(1) 
    print "You find a gargoyle towering 50 feet above you!" 
    print "You have 3 options, climb, fight or flee." 
    Fchoice = raw_input("Please decide to Climb, Fight or Flee.") 
    while Fchoice != "Flee": 
     while Fchoice == ("Climb") , ("climb"): 
      print "You have climbed the gargoyle and prepare to cut off the head." 
      string = "SharpBlade" 
      if string in inventory: 
       time.sleep(2) 
       print "Your extra sharp blade cuts off the head and the gargoyle falls!" 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       print ("     YOU WON!!!!!!!!!    ") 
       print ("     QUITTING PROGRAM    ") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       time.sleep(5) 
       sys.exit("You have beat the puzzle RPG text based adventure game!") 
      else: 
       print "You fail to cut off the head." 
       print "The gargoyle throws you off and kills you." 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       print ("     GAME IS OVER!     ") 
       print ("     QUITTING PROGRAM    ") 
       print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
       time.sleep(5) 
       sys.exit() 
     if Fchoice == "Fight": 
      print "You un-shealth your sword, only to find the gargoyles hand ontop of your body." 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      print ("     GAME IS OVER!     ") 
      print ("     QUITTING PROGRAM    ") 
      print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
      time.sleep(5) 
      sys.exit() 
    print "You try to flee, but the Gargoyle stops you by kicking you against the wall!" 
    print "You un-shealth your sword, only to find the gargoyles hand ontop of your body." 
    print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
    print ("     GAME IS OVER!     ") 
    print ("     QUITTING PROGRAM    ") 
    print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") 
    time.sleep(5) 
    sys.exit() 

Я создаю текстовую игру на основе RPG с небольшим количеством битвы. Существует определенный порядок получения вещей и входа в комнаты.В любом случае, чтобы не повторять код здесь?

В принципе, я знаю, что повторяющийся код плохой, но я не уверен, какие шаги я должен предпринять для этого. Я уверен, что мне нужно использовать функции и def main(). Любая помощь приветствуется!

+1

положить его в функцию и просто вызовите функцию – SirParselot

+1

Там довольно несколько учебников о написании текста приключения на сети: https://www.google.com/search?q=python+text+adventure Вы можете найти некоторые из них полезными; более общие рекомендации могут привести к хорошим идеям для вашего собственного кода. –

+1

вам нужно узнать о циклах и функциях. ... –

ответ

0

Вы хотите отделить свою логику больше, чем у вас уже есть. Когда вы это делаете, это становится намного более ясным, когда не рекомендуется повторять что-то.

Так что давайте начнем с самого начала.

Ваша игра легко подпадает под архитектуру MVC. В архитектуре MVC вы делите свою логику на модели, представления и контроллеры.

Ваш инвентарь - это модель, каждый раз, когда вы печатаете на экране, вы должны вызывать представление, и вся логика управления вашей игрой будет вашим контроллером.

Хорошая планировка для этого должна заключаться в том, чтобы начать с класса Game. Этот класс будет вашим контроллером. Затем создайте класс Interface. Создайте методы в своем Interface, которые будут вызываться каждый раз, когда вы печатаете на экране или запрашиваете пользователя. В вашем игровом классе у вас может быть логика запуска приложения, запрос пользователя, вызов представления, когда вы хотите распечатать на экране, и вызов инвентаря для его обновления по мере необходимости.

Вот некоторые ресурсы, чтобы посмотреть на: http://www.tutorialspoint.com/python/python_classes_objects.htm http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/functions.html

Это выглядит как учебник для что-то похожее на то, что вы пытаетесь сделать: http://letstalkdata.com/2014/08/how-to-write-a-text-adventure-in-python/

Добро пожаловать к программированию! Удачи!

0

Я не собираюсь вводить всю вещь, но я думаю, что вам будет намного лучше справляться с «характером» с объектами и отслеживать hp, инвентарь и т. Д. Посмотрите на борьбу паука и как объект делает всю работу за вас. Большинство настроек сцены можно зацикливать, но ради меня не хочется писать все это, я оставлю это как есть.

import random, time, sys 
welcome_message = ''' 
~~~~~~~~~~~~~~~~~~~~~~~~ 
\tWelcome   
~~~~~~~~~~~~~~~~~~~~~~~~ 
You find youself waking up in a cold dark room. 

You look around and find 3 door ways in front of you: One to the left, one to the right and one in the middle and a chest. 

You have to make a choice. Type the direction of the room to enter the room or type 'Search' to search the chest. 

''' 

class Character(object): 

    def __init__(self, name): 
     self.name = name 
     self.hp = 100 
     self.is_dead = False 

    def take_damage(self, damage): 
     self.damage = damage 
     print '{0} has taken {1} damage!'.format(self, self.damage) 
     self.hp = self.hp - self.damage 
     if self.hp <= 0: 
      self.is_dead = True 

    def is_alive(self): 
     if self.is_dead: 
      print '{0} has died!'.format(self) 
      return False 
     return True 

    def damage_taken(self): 
     return self.damage 

    def __repr__(self): 
     return self.name 

class Spider(Character): 
    def __init__(self, name): 
     super(Spider, self).__init__(name) 

class Adventurer(Character): 

    def __init__(self, name): 
     super(Adventurer, self).__init__(name) 
     self.inventory = [] 

    def has_inventory(self, item): 
     if item.lower() in self.inventory: 
      return True 
     return False 

    def is_alive(self): 
     if self.is_dead: 
      print 'You have died.' 
      sys.exit() 
     return True 

    def show_inventory(self): 
     return self.inventory 

    def add_inventory(self, item): 
     if item.lower() not in self.inventory: 
      self.inventory.append(item.lower()) 

adventurer = Adventurer('Tom') 

print welcome_message 
user_choice = raw_input('Please make your selection:').lower() 

if user_choice == 'search': 
    print 'You slowly walk towards the chest and reach in and find:' 
    weapon = random.choice(['Axe', 'Sword']) 
    print 'You find a {0}'.format(weapon) 
    adventurer.add_to_inventory(weapon) 
    ... 
    ... 
    user_choice = raw_input('Please pick a direction you\'d like to go:').lower() 

if user_choice == 'left': 

    if adventurer.has_inventory('Torch'): 
     ... 
     ... 

     spider = Spider('Spider') 

     while spider.is_alive() and adventurer.is_alive(): 
      spider.take_damage(random.randint(3, 10)) 
      adventurer.take_damage(random.randint(1, 5)) 
Смежные вопросы