Python: Making my adventure game code, begin to "do something." - python

absolute beginner here. I am making a text adventure game to sharpen beginner skills. Can someone give me an example of what could go in my
"def firstBattle", function?
Something like a small example of a battle, and updating the Stats and Inventory? Thanks
def displayIntro():
# I will update this as I think of more to add
print(""" You are lord Deadra. You have been sent to Citiel to
overthrow the current King Navator. Throughout your
travels, you will encounter various enemies of all
types. Good luck. """)
def displayInventory():
# Keeps a list of stuff in a dictionary. Because I returned
# stuff, I can use this function in other functions to update
print("Inventory:")
stuff = {"health potions": 5,
"poison": 5,
"stamina potions": 5,
"go crazy potion": 5,
"arrows": 50,
"hunting bow": 1,
"hunting knife": 1,
"big sword": 1,
"magic shield": 1}
return stuff
def displayStats():
# Displays initial health stats
print()
print("Stats:")
health = 100
stamina = 100
confidence = 100
return "health:",health, "stamina:",stamina, "confidence:",confidence
def firstBattle():
# First encounter with an enemy. After battle, update inventory
# and health stats

You need a damage variable.
Implement an enemyDamage, enemyHealth and yourDamage variable.
def battleScene():
print("ENTER to Attack.")
input()
health = health - enemyDamage
enemyHealth = enemyHealth - yourDamage
stamina = stamina - # What ever number you want stamina to go down
print("Your HP: " + health)
print("Enemy HP: " + enemyHealth)
To implement the weapons change their damage values using the a class block.

Related

Combat sequence for a text-based RPG

This is the code.
#When I try to make the variable ‘enemy’ save globally, it says ‘Variable referenced before assignment.’, or something along those lines. How do I fix this?
#If you are going to suggest to make it all one function, I tried and it didn't work out. I am doing this so I can keep repeating the turn function until the player enters a vaild command.
#Player and enemy stat blocks. Order of stat blocks is: Health, Weapon, Weapon damage, Armor, and Armor type.
PC = [50, 'shortsword', 20, 'chain mail', 10]
goblin = [30, 'dagger', 15, 'leather', 5]
# Function for a single turn.
def turn(enemy):
turn1 = input('Your turn. What would you like to do? ').lower()
if turn1 != 'attack':
print('Invalid command.')
turn(enemy)
elif turn == 'attack':
global enemy
enemy[0] = enemy[0] - PC[2]
# Function for the entirety of combat.
def combat(enemy):
while enemy[0] > 0:
turn1 = input('Your turn. What would you like to do?')
turn(enemy)
combat(goblin)

How to take away health points when using a class?

I'm working on a game in python and I can't figure out how to take away health once attack function has taken place. I can run the program and the attack function works fine, it shows a random integer between 1 and 50 but doesn't actually take away health from castlehealth = 100
Underneath print("You attacked for " + str(self.attack)) I left the next line blank because I don't know what to type in, I tried a lot of different things and just can't get the attack to take away from castlehealth.
Here is my code:
import os
import time
from random import randint
class GameActions:
def __init__(self):
castlehealth = 100
self.castlehealth = castlehealth
def health(self):
print("Castle health is: " + str(self.castlehealth))
print()
def attack(self):
attack = randint(0, 50)
self.attack = attack
print("You attacked for " + str(self.attack))
def game():
while True:
game_actions = GameActions()
print("What do you want to do?")
print()
print("attack, view hp")
ans = input()
if ans == "hp":
game_actions.health()
if ans == "attack":
game_actions.attack()
You want the following:
self.castlehealth -= attack
Try something like self.castlehealth -= attack. I also fixed some potential indentation issues for you.
Your full code sample could look this this:
import os
import time
from random import randint
class GameActions:
def __init__(self):
castlehealth = 100
self.castlehealth = castlehealth
def health(self):
print("Castle health is: " + str(self.castlehealth))
print()
def attack(self):
attack = randint(0, 50)
self.attack = attack
print("You attacked for " + str(self.attack))
self.castlehealth -= attack
def game():
while True:
game_actions = GameActions()
print("What do you want to do?")
print()
print("attack, view hp")
ans = input()
if ans == "hp":
game_actions.health()
if ans == "attack":
game_actions.attack()
Explanation: self.castlehealth is an instance variable of your GameActions class. The function GameActions.attack() creates a new attack variable as a random integer and then subtracts that value from the instance variable self.castlehealth of the GameActions class. Now self.castlehealth will be the updated value. Consider also tracking the various attacks and resulting healths in a data structure, since every time you have a new attack self.castlehealth and self.attack will change values and you will lose the ability to access the previous values.

Call a class function in a self in another function so that the attributes only include one and the variable not included but is self function?

This code is in the main function:
Player and Computer are lists in this format:
player = ["name", 10, 20, 30]
10 is the health, 20 is the strength, and 30 is the dexterity
# Get the character for the user and the computer.
player = character_choices.get_and_remove_character(choice)
computer = character_choices.get_random_character()
# Preparation for the battle
print ("You have picked a " + player.name)
print ("The computer picked " + computer.name)
print ("Let's battle!\n")
# Battle Loop
rnd = 1
while (player.hit_points > 0 and computer.hit_points > 0):
print ("Round: " + str(rnd))
player.attack (computer)
computer.attack (player)
This is the function:
def attack (self, enemy):
self.player = [self]
if self.player[3] == enemy[3]:
I do not know how to call the player variable within the attack function in this format I can not change the attributes and I do not know how to get the player list items to compare to the enemies list items and fight.
self is a variable commonly related to objects in python by convention.
In your case, to make use of self, you should read up on python object oriented programming.
https://realpython.com/python3-object-oriented-programming/
Go through the tutorial in the link and once you are done, you will have a better understanding of what you want to achieve using your code. Have fun!

Pokemon game in python: classes/objects, battle and deepcopy

I'm new on python and I'm trying to do a Pokemon game (like the gameboy and nds games). I've created the pokemon and trainer classes and I want to implement the battle mechanics. I thought it was working fine, but then I found that if I lose the battle the program enters in an infinite loop.
I tried a lot to found the error and I discovered that when it exits the 'while alive(pokemon1) and alive(pokemon2)' loop, the pokemon1 hp returns to full hp but the pokemon2 remains with the current hp (I've put a print to show it). It makes non sense for me because the code is identical for both trainers. Anyone knows why is it happening? I want it to continue with the current hp of both pokemon at the end of the loops and battle.
Here is a sample of my code:
import copy
import random
class Pokemon(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
def ataque(self, oponent):
oponent.hp = oponent.hp - 150 #just for a test
class Trainer(object):
def __init__(self, name, *pokemon):
self.name = name
self.pokemon, self.pokemonname = [], []
for pkmn in pokemon:
self.pokemon.append(copy.deepcopy(pkmn))
self.pokemonname.append(pkmn.name)
weavile = Pokemon ('Weavile', 150) #change the hp to more than 150 if you want to win
garchomp = Pokemon ('Garchomp', 250)
roserade = Pokemon ('Roserade', 160)
ambipom = Pokemon ('Ambipom', 160)
me = Trainer('You', weavile) #or choose ambipom to win
cynthia = Trainer('Cynthia', garchomp)
def alive(pokemon): #check if the pokemon is alive
if pokemon.hp>0:
return True
if pokemon.hp<=0:
pokemon.hp=0
return False
def battle(trainer1, trainer2): #battle between two trainers
fight1, fight2 = True, True
while fight1 and fight2:
print ('Choose a pokemon:', trainer1.pokemonname)
pokemon1 = eval(input())
while not alive(pokemon1):
print (pokemon1.name, 'is out of batlle. Choose another pokemon')
pokemon1 = eval(input())
pokemon2 = random.choice(trainer2.pokemon)
while not alive(pokemon2):
pokemon2 = random.choice(trainer2.pokemon)
print (trainer1.name, 'chose', pokemon1.name, '\n', trainer2.name, 'chose', pokemon2.name)
while alive(pokemon1) and alive(pokemon2):
pokemon1.ataque(pokemon2)
if alive(pokemon2):
pokemon2.ataque(pokemon1)
print (pokemon1.name, pokemon1.hp)
print (pokemon2.name, pokemon2.hp)
print (trainer1.pokemon[0].name, trainer1.pokemon[0].hp) #here its returning the original hp
print (trainer2.pokemon[0].name, trainer2.pokemon[0].hp) #here its returning the current hp, as it should
if not any(alive(pokemon) for pokemon in trainer1.pokemon):
fight1 = False
if not any(alive(pokemon) for pokemon in trainer2.pokemon):
fight2 = False
battle(me, cynthia)
If you run the code in the way I wrote here, you need to choose one of your pokemon on the list (there's only one: weavile - to simplify), so just type weavile. After that, weavile will attack and then be attacked by garchomp. Weavile will be defeated (0 hp) in the first hit but after the loop 'while alive(pokemon1)...' it will show that weavile still has 150 hp and it will continue to ask you to choose a pokemon even if it's already dead.
If you want to win: choose ambipom instead of weavile in 'me' object or change the weavile hp to more than 150 in weavile object. If you do this it will run as I want and end the battle.

RPG Battle, monsters health after attack with dictionaries

I've asked about this before, because I'm still not too familiar with dictionaries, but what's happening is every time I attack the monsters health resets automatically:
#MONSTER STATS
corpsefinder_stats = {
"corpsefinder_strength" : 7,
"corpsefinder_speed" : 1,
"corpsefinder_mana" : 0,
"corpsefinder_health" : 45,
}
#GAME START
if game_start==True:
time.sleep(0.6)
print(username, "wakes up, the cold snow on their face as they lie down in bewilderment, wondering where they could of come from and why they are here. As they stand up, they notice a small village in the distance, but before they can even begin to think of venturing over, a small bug-like creature approaches, primed for battle")
time.sleep(8)
while corpsefinder_stats["corpsefinder_health"] >= 1 or health >= 1:
tutorialbattle=input("\nA CORPSE-FINDER gets ready to attack!\nWhat will you do?\n\n##########\n# Attack #\n##########\n\n##########\n# Defend #\n##########\n")
tutorialbattle=tutorialbattle.lower()
if tutorialbattle=="attack":
corpsefinder_stats["corpsefinder_health"] -(random.randint(strength-10, strength))
print(username, " attack!\nCORPSE-FINDER HP: ", corpsefinder_stats["corpsefinder_health"])
print("CORPSE-FINDER attacks!\n", username, " HP: ", health-(random.randint(corpsefinder_stats["corpsefinder_strength"]-6, corpsefinder_stats["corpsefinder_stren
When you do :
corpsefinder_stats["corpsefinder_health"] -(random.randint(strength-10, strength))
you are just performing the mathematical operation, not assigning it to anything.
You need to do :
corpsefinder_stats["corpsefinder_health"] = corpsefinder_stats["corpsefinder_health"] -(random.randint(strength-10, strength))

Categories

Resources