首页 > 解决方案 > 文字冒险游戏 (Python) 中的项目类

问题描述

我正在用python制作一个文本冒险游戏。我有大部分基本项目设置,例如链接位置和保存功能。(我在设置保存功能时遇到了一点困难,所以如果有更好的方法请告诉我)。

现在我想制作物品。具体来说,我希望该项目位于某个位置(可能以与其他位置相互链接相同的方式链接到它),并且当玩家与它们交互时(例如拾取它),他们更新了该项目的位置。我希望用户必须输入命令并认识到他们需要该物品,并且一旦他们进入一个区域就不会被动地拾取该物品。(商店也没有功能,如果你能指点我怎么做最好+维护玩家的库存)

我知道这将包括很多东西,例如一个新类,以及一些专门规定哪些命令可以工作的新函数。我朝它开了一枪,但很快就撞到了墙上。如果你们中的任何人可以帮助我,那就太棒了。(另外,有更好/更快的方法来做某事,指出来,我会考虑添加它)。

这是代码:

import pickle
import time

# Constants/Valid Commands
# This is a mess, ignore it unless it causes a problem.

invalidChars = '\"\'()*&^%$#@!~`-=_+{}[]\|:;<,>.?/'
validLogin = 'log in', 'log', 'saved', 'in', 'load', 'logging in', 'load game', 'load'
validNewGame = 'new', 'new game', 'new save'
directions = ['north', 'south', 'east', 'west'] 
possibleGenders = ['boy', 'girl']
examineCommands = ['examine yourself', 'look at yourself', 'my stats', 'my statistics', 'stats', 'statistics', 'examine statistics', 'examine stats']
invalidExamine = ['examine', 'look at' ]
stop = ['stop', 'exit', 'cancel']



# FUNCTIONS

def start():


  print("Welcome to XXXXX, created by Ironflame007") #XXXX is the name placeholder. I haven't decided what it will be yet
  while True:
    command = input("Are you making a new game, or logging in?\n> ")
    if command in validNewGame:
      clear()
      newGame()
      break
    elif command in validLogin:
      clear()
      login()
      break
    else:
      clear()
      print("Thats not a valid command. If you wish to exit, type exit\n")



def newGame():
  while True:
    username = input('Type in your username. If you wish to exit, type exit\n> ')
    if username[0] in invalidChars:
      clear()
      print('Your username can\'t start with a space or any other type of misc. character. Just letters please')
    elif username in stop:
      clear()
      start()
    else:
      break

  password = input('Type in your password\n> ')
  playerName = input("What is your character's name?\n> ")

  while True:
    playerGender = input("Is your character a boy or a girl?\n> ".lower())
    if playerGender not in possibleGenders:
      print("That's not a valid gender...")
    else:
      clear()
      break

  inventory = []
  health = 100
  player = Player(playerName, playerGender, 0, 1, inventory, health, password)

  file = username + '.pickle'
  pickle_out = open(file, 'wb')
  pickle.dump(player.player_stats, pickle_out)
  pickle_out.close()


  print("You wake up. You get off of the ground... dirt. You didn't fall asleep on dirt. You look around an observe your surroundings\n(If you need help, use the command help)") # hasn't been made yet

  game('default', username, player.player_stats)





def examine(string, dictionary):
  if string in examineCommands:
    print(dictionary)
  elif string in invalidExamine:
    print('There is nothing to {0}'.format(string))
  else:
    print('Thats an invalid command')



def clear():
  print('\n' * 50)

def game(startLoc, username, dictionary):
  if startLoc == 'default':
    currentLoc = locations['woods']
  else:
    currentLoc = dictionary['location']

  while True:
    print(currentLoc.description)
    for linkDirection,linkedLocation in currentLoc.linkedLocations.items():
      print(linkDirection + ': ' + locations[linkedLocation].name)
    command = input("> ").lower()
    if command in directions:
      if command not in currentLoc.linkedLocations:
        clear()
        print("You cannot go this way")
      else:
        newLocID = currentLoc.linkedLocations[command]
        currentLoc = locations[newLocID]
        clear()
    else:
      clear()
      if command in examineCommands:
        examine(command, dictionary)
      elif command in invalidExamine:
        examine(command, dictionary)
      elif command == 'log out':
        logout(username, dictionary, currentLoc)
        break
      else:
        print('That\'s an invalid command.')
        print("Try one of these directions: {0}\n If you are trying to log out, use the command log out.".format(directions))


def login():
  while True:
    while True:
      print('If you wish to exit, type exit or cancel')
      username = input("What is your username\n> ")
      if username in stop:
        clear()
        start()
        break
      else:
        break
    inputPass = input("What is your password\n> ")
    try:
      filename = username + '.pickle'
      pickle_in = open(filename, 'rb') 
      loaded_stats = pickle.load(pickle_in, )
      if loaded_stats['password'] == inputPass:
        clear()
        print("Your game was succesfully loaded")
        game('location', username, loaded_stats)
        break
      else:
        clear()
        print("That's an invalid username or password.")
    except:
      clear()
      print("Thats an invalid username or password.")



def logout(username, dictionary, currentLoc):
  print("Please don't close the window, the programming is saving.")
  dictionary.update({'location': currentLoc})
  file = username + '.pickle'
  pickle_out = open(file, 'wb')
  pickle.dump(dictionary, pickle_out)
  pickle_out.close()
  time.sleep(3)
  print("Your game has been saved. You may close the window now")


class Location:
  def __init__(self, name, description):
    self.name = name
    self.description = description
    self.linkedLocations = {} # stores linked locations in this dictionary

  def addLink(self, direction, destination):
    # adds link to the linked locations dictionary (assuming the direction and destination are valid)
    if direction not in directions:
      raise ValueError("Invalid Direction")
    elif destination not in locations:
      raise ValueError("Invalid Destination")
    else:
      self.linkedLocations[direction] = destination


class Player:

  def __init__(self, name, gender, gold, lvl, inventory, health, password):
    self.name = name
    self.gender = gender
    self.gold = gold
    self.lvl = lvl
    self.inventory = inventory
    self.health = health
    self.player_stats = {'name': name, 'gender': gender, 'gold': gold, 'lvl': lvl, 'inventory': inventory, 'health': health, 'password': password, 'location': 'default'}

# ACTUALLY WHERE THE PROGRAM STARTS

locations = {'woods': Location("The Woods", "You are surrounded by trees. You realize you are in the woods."),
'lake': Location("The Lake", "You go north and are at the lake. It is very watery."),
'town': Location("The Town", "You go north, and find yourself in town."),
'shop': Location("The Shop", "You go east, and walk into the shop. The shop owner asks what you want")
} 



locations['woods'].addLink('north', 'lake')
locations['lake'].addLink('south', 'woods')
locations['lake'].addLink('north', 'town')
locations['town'].addLink('south', 'lake')
locations['town'].addLink('east', 'shop')
locations['shop'].addLink('west', 'town')




start()

标签: pythonpython-3.x

解决方案


至于捡东西,您可以在播放器类中有一个方法,将物品附加到播放器的库存列表中。如果您希望该项目位于特定位置,则可以在该位置提供一个可用项目列表,该列表可通过检查功能访问。

因此,Class Location:您可以在其中添加类位置:

def __init__(self, name, description):
    self.name = name
    self.description = description
    self.linkedLocations = {} # stores linked locations in this dictionary
    self.items = items        # List of items on location

Class Player:你可以添加,

Class Player:

def PickUp(self, Location, item):
    Location.items.remove(item)
    self.inventory.append(item)

您不必像实施 Locations 那样实施项目,因为项目不会有任何邻居。

我希望用户必须输入命令并认识到他们需要该物品,并且一旦他们进入一个区域就不会被动地拾取该物品。

我猜这应该在你的检查函数中。除了在某个位置调用的检查函数应该产生该特定位置的项目列表。也许通过制作一个较小的版本来了解冒险游戏(您最喜欢的游戏之一)的工作原理可能会帮助您了解它们之间的抽象交互是如何的。我想添加一个具体的例子可以引发关于交互的讨论。祝你游戏好运!!

干杯


推荐阅读