简体   繁体   English

我正在尝试制作基于文本的游戏,我想知道如何使用 elif 语句制作保存游戏

[英]I'm trying to make a text-based game and I'm wondering how I could make a save game using an elif statement

How would I be able to make a save option in this game using elif?如何使用 elif 在此游戏中设置保存选项? In every tutorial I see, they use an autosave or save when they reach a certain point, like getting to a certain level or corridor.在我看到的每个教程中,他们都会在到达某个点时使用自动保存或保存,例如到达某个级别或走廊。 I would like it so when a user chooses to save the game on line 113, it would save all their progress.我希望这样当用户选择在第 113 行保存游戏时,它会保存他们的所有进度。

Here is my code:这是我的代码:

#Imports
import time
import os
import sys
#Func's
def typingPrint(text):
  for character in text:
    sys.stdout.write(character)
    sys.stdout.flush()
    time.sleep(0.05)
  
def typingInput(text):
  for character in text:
    sys.stdout.write(character)
    sys.stdout.flush()
    time.sleep(0.05)
  value = input()  
  return value 

def typingAscii (text):
  for character in text:
    sys.stdout.write(character)
    sys.stdout.flush()
    time.sleep(0.08)

def save():
  list = [
    pet_name,
    energy,
    hunger,
    health,
    training,
    pet_food,
    money,
    animal
  ]
  f = open("load.txt", "w")
  for item in list:
    f.write(item + "/n")
  f.close
  

#Var's
health = 'good'
energy = 8
hunger = 0
training = 0
pet_food = 10
things_at_store = ('bone', 'yarn', 'sunken boat', 'mini cave', 'fake tree')
done_choosing = False
choice = 0
choice2 = 0
money = 100
animal = 'None'
print("------------------------------------------------------------------------------------------")

words = ("""                                                                   
                                              888                                 
 8888b.  .d8888b   .d8888b 888 888     .d8888b  88888b.   .d88b.   .d88b.  88888b.  
    "88b 88K      d88P"    888 888     88K      888 "88b d8P  Y8b d8P  Y8b 888 "88b 
.d888888 "Y8888b. 888      888 888     "Y8888b. 888  888 88888888 88888888 888  888 
888  888      X88 Y88b.    888 888          X88 888  888 Y8b.     Y8b.     888 d88P 
"Y888888  88888P'  "Y8888P 888 888      88888P' 888  888  "Y8888   "Y8888  88888P"  
                                                                           888      
                                                                           888  """)

for line in words.split('\n'):
   time.sleep(0.2)
   sys.stdout.write(line + '\n')
   sys.stdout.flush()

                                                                           
print("------------------------------------------------------------------------------------------")
time.sleep(1)
typingPrint('Enter pet:')   
print("""
""")
typingPrint('1.Sheep')
print("""
""")

#Choose a pet, repeat until a valid choice is entered.
while done_choosing == False:
 choice = typingInput('Which do you choose? (enter the number)')
 if choice == '1':
   animal = 'Sheep'
   done_choosing = True 
 else:
     typingPrint ('Sorry, that is not a choice. Please enter something else.')
     
#Name pet
pet_name = typingInput ("What do you want to name your pet? ")
print ('Okay, you now have a', animal ,'named', pet_name + '.')
print('')
print ('Your', animal ,'is at', health, 'health right now. You can check it at any time.')

#list choices
print('')
typingPrint('1.Feed your pet')
print('')
typingPrint('2.Buy more food')
print('')
typingPrint('3.Take your pet for a walk')
print('')
typingPrint('4.Play a game with your pet')
print('')
typingPrint('5.Train your pet')
print('')
typingPrint('6.Rest and check stats (pet health, money, etc.)')
print('')
typingPrint('7.Buy a toy for your pet')
print('')
typingPrint("8.Save Game")
print('')
typingPrint("9.Load Game")
#forever loop of things to do

while True:
 print('')
 choice = typingInput('What would you like to do?')

#Feed your pet
 if choice == '1':
  if pet_food > 5:
    if hunger > 0:
      pet_food -= 5
      hunger -= 1
      print("------------------------------------------------------------------------------------------")
      typingPrint('Your pet has been fed!')
      print("------------------------------------------------------------------------------------------")
      print('You now have ', pet_food, ' pet food, and your pets remaining hunger is at ', hunger, '.')
      
    else:
      print("------------------------------------------------------------------------------------------")
      print(pet_name, 'waits next to the food, not eating.')
  else:
    print("------------------------------------------------------------------------------------------")
    typingPrint("You'll need to get some more food first...")

#Buy more food
 elif choice == '2':
     if money > 9:
      money -= 10
      pet_food += 5
      print("------------------------------------------------------------------------------------------")
      print('Food bought! Money = ', money, 'Pet food = ', pet_food)
      print("------------------------------------------------------------------------------------------")

#Take pet for walk
 elif choice == '3':
     if animal == 'Sheep':
       if energy > 5:
         energy -= 3
         hunger += 1 
         print('You go for a nice walk with ' +  pet_name + '. Your pet now has', energy, 'energy and', hunger, 'hunger.')
       else: 
         print('Your', animal, 'seems a bit too tired to go for a walk today.')
     else:
       print('Your', animal, 'stares at you like you are crazy.')

#Play a game
 elif choice == '4':
     if energy > 5:
         energy -= 3
         hunger += 2 
         print('You play with ' + pet_name + '!', pet_name,("now has"), energy, 'energy and', hunger, 'hunger.')

#Train your pet

 elif choice == '5':
     print('')
#Rest your pet and check stats

 elif choice == '6':
     print('')
     typingPrint ('Okay, here are the stats.')
     print('Health:', health)
     print ('Pet energy (0-10):', energy ,)
     print ('Hunger (0 = full 5 = starving):', hunger ,)
     print ('Training (max 10):', training ,)
     print('Pet food:', pet_food)     
     print ('Money:', money ,)
     energy += 2

#Buy a toy
 elif choice == '7':
    print('Here are the items at the store:', things_at_store)

#Save
 elif choice == '8':
  save()
  

#Input doesn't match any choices
 else:
     typingPrint ('Sorry, that is not a choice. Please enter something else.')

it looks like you already added a save() function that writes your variables to a text file.看起来您已经添加了一个 save() function ,它将您的变量写入文本文件。

A few things need to be fixed there:那里需要解决一些问题:

  1. you will need to convert integer/float variables to string before you can combine them with a "\n" string您需要将整数/浮点变量转换为字符串,然后才能将它们与“\n”字符串组合
  2. you do a linebreak with \n你用\n换行
  3. list is an in-built name, it's better not to overwrite it list是一个内置名称,最好不要覆盖它

So what you get is:所以你得到的是:

def save():
  my_list = [
    pet_name,
    energy,
    hunger,
    health,
    training,
    pet_food,
    money,
    animal
  ]
  f = open("load.txt", "w+")
  for item in my_list:
    f.write(str(item) + "\n")
  f.close()

in general it might be easier dumping and loading the entire objects to files, for instance using a dictionary and json files一般来说,将整个对象转储和加载到文件可能更容易,例如使用字典和 json 文件

example:例子:

import json

def save():

  game_variables = {
    "pet_name": pet_name,
    "energy": energy,
    "hunger": hunger,
    "health": health,
    "training": training,
    "pet_food": pet_food,
    "money": money,
    "animal": animal
  }

  with open("load.json", "w+") as f:
      json_save = json.dumps(game_variables, indent=4)
      f.write(json_save)

which you would load with:您将加载:

with open('load.json', 'r') as f:
    game_variables = json.load(f)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我试图让用户忽略我在 Python 中为 class 的文本游戏的情况 - I'm trying to allow the user to ignore the case for my text-based game in Python for a class 我正在尝试制作 2 人 tron 游戏,但我不知道如何进行游戏开始倒计时 - I'm trying to make a 2 player tron game, and I don't know how to make a countdown to start the game 我正在尝试制作康威生活游戏,但发生了一些事情 - I'm trying to make conway game of life but something happening 我如何让用户在Visual Studio Code的基于文本的rpg中保存和加载他们的游戏? - How can I have a user save and load their game in my text-based rpg in Visual Studio Code? 我正在尝试制作一个程序,但“if”语句不起作用 - I'm trying to make a program but the "if" statement is not working 我正在尝试用 python 制作游戏,首先是让角色移动,但我一直遇到同样的错误 - I'm trying to make a game in python, starting by getting the character moving, but i keep getting the same error 我正在用python创建一个基于文本的冒险游戏,并尝试添加第三个选项,但是它不起作用 - I'm making a text based adventuere game in python and trying to add a third option but it's not working 我正在尝试制作一个平台游戏,其关卡在完成上一个后出现 - I'm trying to make a platforming game with levels which appear after completion of the previous 我正试图用pygame制作一个2人赛车游戏,event.key不起作用 - i'm trying to make a 2 players racing game with pygame and event.key don't work 在测验游戏中,我试图制作一个记分牌,告诉你每个问题之前和之后的分数 - In the quiz game I'm trying to make a scoreboard that tells you the score before and after each question
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM