Python Forum
Thread Rating:
  • 2 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic RPG
#1
This is a basic RPG where you fight Goblins and Giant Rats until you die. I will make this a part of a larger more interesting game in the future maybe. The stat calculations are unbalanced, and it's really unpolished, but it's basically just my way of trying to teach myself Python.

import random
import sys

#Enemies
goblin = {}
goblin['Name'] = 'Goblin'
goblin['Health'] = 50.0
goblin['Agility'] = 40.0
goblin['Strength'] = 35.0
goblin['Level'] = 1

giant_rat = {}
giant_rat['Name'] = 'Giant Rat'
giant_rat['Health'] = 40.0
giant_rat['Agility'] = 55.0
giant_rat['Strength'] = 30.0
giant_rat['Level'] = 1

def Death():
    print("You have died!")
    print("GAME OVER")
    exit_game = raw_input()
    sys.exit()	

def Fight(enemy):
    print("All of a sudden a " + str(enemy['Name']) + " attacks you!")
    Enemy = enemy.copy()
    while Enemy['Health'] > 0:
        Attack = False
        A = raw_input("Type A to attack the " + str(Enemy['Name']) + ". ")
        if A == "Attack" or "attack" or "A" or "a":
            Attack = True
        else:
            pass
        if Attack == True:
            print("You swing at the " + str(Enemy['Name']) + " with your sword!...")
            Player_attack_lands = False
            Enemy_attack_lands = False
            if (Enemy['Agility'] - player['Agility'] + (random.random() - random.random()) * 100) <= 0:
                Player_attack_lands = True
            else:
                pass
            if Player_attack_lands == True:
                print("You strike the " + str(Enemy['Name']) + "!")
                Enemy['Health'] = Enemy['Health'] - player['Strength']
                print("You've done " + str(player['Strength']) +" damage! ")
                print("The " + str(Enemy['Name']) + " now has " + str(Enemy['Health']) + " left. ")
                if Enemy['Health'] <= 0:
                    pass
                else:
                    print("The " + str(Enemy['Name']) + " launches an attack at you! ")
                    if (Enemy['Agility'] - player['Agility'] + (random.random() - random.random()) * 100) <= 0:
                        Enemy_attack_lands = True
                    else:
                        print("The " + str(Enemy['Name']) + " missed! ")
                    if Enemy_attack_lands == True:
                        print("The " + str(Enemy['Name']) + " lands its attack! ")
                        player['Health'] = player['Health'] - Enemy['Strength']
                        print("The " + str(Enemy['Name']) + " deals " + str(Enemy['Strength']) + " damage to you. ")
                        print("You have " + str(player['Health']) + " Health left. ")
                        if player['Health'] <= 0:
                            Death()
                        else:
                            pass
                    else:
                        pass      
            else:
                print("You miss!")
                print("The " + str(Enemy['Name']) + " launches an attack at you! ")
                if (Enemy['Agility'] - player['Agility'] + (random.random() - random.random()) * 100) <= 0:
                    Enemy_attack_lands = True
                else:
                    print("The " + str(Enemy['Name']) + " missed! ")
                if Enemy_attack_lands == True:
                    print("The " + str(Enemy['Name']) + " lands its attack! ")
                    player['Health'] = player['Health'] - Enemy['Strength']
                    print("The " + str(Enemy['Name']) + " deals " + str(Enemy['Strength']) + " damage to you. ")
                    print("You have " + str(player['Health']) + " Health left. ")
                    if player['Health'] <= 0:
                        Death()
                    else:
                        pass
    print("You've killed the " + str(enemy['Name']) + "!")

#Character Creaion
player={}
player['Name'] = raw_input("Please enter your character's name. ")
player['Sex'] = raw_input("Please enter your character's sex. ")
player['Experience'] = 0
player['Level'] = 1
if player['Sex'] == 'female' or 'f' or 'F':
    player['Sex'] = 'Female'
elif player['Sex'] == 'male' or 'm' or 'M':
    player['Sex'] = 'Male'
else:
    pass
if player['Sex'] != 'Female' and player['Sex'] != 'Male':
    player['Sex'] = raw_input("Please enter your character's sex again. Please enter Male or Female. ")
else:
    pass
player['Strength'] = (random.random() * 100)
player['Agility'] = ((random.random() * 100) + 70) / 2
player['Health'] = (random.random() * 100 + 100)
#End Character Creation

while player['Health'] > 0:
    Fight(goblin)
    print("")
    Fight(giant_rat)
    print("")
Reply
#2
You scared me a bit. RPG was an old IBM language. I never liked it, and I'm thinking OH NO,
someones writing RPG in Python!

Thought I'd share
Reply
#3
Added Level up, Rest, Explore, Stats, and ability to save and load progress even after closing program.

import random
import sys

player = {} #Makes player{} dictionary global

#Enemies
goblin = {}
goblin['Name'] = 'Goblin'
goblin['Health'] = 50
goblin['Agility'] = 40
goblin['Strength'] = 25
goblin['Level'] = 1

giant_rat = {}
giant_rat['Name'] = 'Giant Rat'
giant_rat['Health'] = 40
giant_rat['Agility'] = 55
giant_rat['Strength'] = 20
giant_rat['Level'] = 1

feral_dog = {}
feral_dog['Name'] = 'Feral Dog'
feral_dog['Health'] = 50
feral_dog['Agility'] = 45
feral_dog['Strength'] = 20
feral_dog['Level'] = 1

def Death():
    print("You have died!")
    print("GAME OVER")
    player = {}
    exit_game = raw_input()
    Main() #Restarts game

def Stats():
    print("Current Stats:")
    print("Current Health: " + str(player['Health']))
    print("Max Health: " + str(player['Healthmax']))
    print("Agility: " + str(player['Agility']))
    print("Strength: " + str(player['Strength']))
    return("Level: " + str(player['Level']))

def Fight(enemy):
    print(" ")
    print("All of a sudden a " + str(enemy['Name']) + " attacks you!")
    Enemy = enemy.copy() #Copies enemy dictionary so the original doesn't get overwritten
    while Enemy['Health'] > 0:
        A = raw_input("Type A to attack the " + str(Enemy['Name']) + ". ") #Does player want to attack?
        if A in ["Attack", "attack", "A", "a"]:
            print("")
            print("You swing at the " + str(Enemy['Name']) + " with your sword!...")
            if (Enemy['Agility'] - player['Agility'] + (random.random() - random.random()) * 100) <= 0: #Do this if player hits enemy
                Enemy['Health'] = Enemy['Health'] - player['Strength'] #Enemy is hit and its health lowers
                print("")
                print("You strike the " + str(Enemy['Name']) + " and do " + str(player['Strength']) + " damage!")
                if Enemy['Health'] > 0: #Do this if enemy is still alive
                    print("The " + str(Enemy['Name']) + " now has " + str(Enemy['Health']) + " health left.")
                    print("")
                    print("The " + str(Enemy['Name']) + " launches an attack at you! ")
                    if (Enemy['Agility'] - player['Agility'] + (random.random() - random.random()) * 100) <= 0: #Enemy attacks player. Does the attack land?
                        print("The " + str(Enemy['Name']) + " lands its attack! ")
                        player['Health'] = player['Health'] - Enemy['Strength'] #Player is hit and his health lowers
                        print("")
                        print("The " + str(Enemy['Name']) + " deals " + str(Enemy['Strength']) + " damage to you. ")
                        if player['Health'] > 0:
                            print("You have " + str(player['Health']) + " Health left. ")
                        elif player['Health'] <= 0: #Player dies if he has 0 or less health
                            Death() #Calls Death() function
                    else:
                        print("The " + str(Enemy['Name']) + " missed! ")
                        print(" ")
            else: #Player misses the enemy
                print("")
                print("You miss!")
                print("The " + str(Enemy['Name']) + " launches an attack at you! ") #Enemy attack player
                if (Enemy['Agility'] - player['Agility'] + (random.random() - random.random()) * 100) <= 0: #Do this if enemy hits player?
                    print("The " + str(Enemy['Name']) + " lands its attack! ")
                    player['Health'] = player['Health'] - Enemy['Strength'] #Player is hit and his health lowers
                    print("The " + str(Enemy['Name']) + " deals " + str(Enemy['Strength']) + " damage to you. ")
                    if player['Health'] > 0:
                        print("You have " + str(player['Health']) + " Health left. ")
                        print(" ")
                    elif player['Health'] <= 0:
                        Death() #Calls Death() function
                else:
                    print("The " + str(Enemy['Name']) + " missed! ") #Enemy misses player
    print("")
    print("You've killed the " + str(enemy['Name']) + "!") #Enemy is killed
    player['Experience'] += Enemy['Level'] #Player gains experience
    print("You have gained " + str(Enemy['Level']) + " experience points.")
    print("Experience: " + str(player['Experience']) + "/" + str(player['Level'] + 9))
    if player['Experience'] >= player['Level'] + 9: #If player has enough xp to levels up
        Levelup() #Calls Levelup() function
        
def Levelup():
    player['Level'] += 1 #Increases player's level
    player['Experience'] = 0 #Resets player's xp to 0
    print("You have leveled up!")
    print("")
    raw_input("Press enter to continue. ")
    print("You are now level " + str(player['Level']) + "!")
    print("You have 5 points to spend on your Max Health, Agility, and Strength.")
    print("Your Max Health determines how much damage you can take without dying.")
    print("Your Agility determines how easily you hit your enemies and evade their attacks.")
    print("Your Strength determines how much damage your attacks do.")
    print(" ")
    print(Stats()) #Show player his current stats
    print("")
    raise_healthmax = 0
    raise_agility = 0
    raise_strength = 0 #Declares variables and allows while loop to start
    n = 0
    while raise_healthmax + raise_agility + raise_strength != 5: #Sum of stat points can't equal 5 for loop to start. Will cycle until sum equals 5 though.
        n += 1
        if n >1: #So that player sees this message if this loops more than once
            print("You have to spend exactly 5 points on your stats.")
        raise_healthmax = input("Max Health: ")
        while raise_healthmax not in [0, 1, 2, 3, 4, 5]: #If player enters an invalid number, have them try again.
            print("You must enter 0, 1, 2, 3, 4, or 5. Try again.")
            print("")
            raise_healthmax = input("Max Health: ")
            print(" ")
        raise_agility = input("Agility: ")
        while raise_agility not in [0, 1, 2, 3, 4, 5]: #If player enters an invalid number, have them try again.
            print("You must enter 0, 1, 2, 3, 4, or 5. Try again.")
            print("")
            raise_agility = input("Agility: ")
            print(" ")
        raise_strength = input("Strength: ")
        while raise_strength not in [0, 1, 2, 3, 4, 5]: #If player enters an invalid number, have them try again.
                print("You must enter 0, 1, 2, 3, 4, or 5. Try again.")
                print("")
                raise_strength = input("Strength: ")
                print(" ")
    player['Healthmax'] += raise_healthmax #Raise stats by player's desired amount
    player['Agility'] += raise_agility
    player['Strength'] += raise_strength
    print(Stats()) #Show player his new stats
    print(" ")
    
def Character_creation():
    player['Name'] = raw_input("Please enter your character's name. ")
    player['Sex'] = raw_input("Please enter your character's sex. ")
    player['Experience'] = 0
    player['Level'] = 1
    if player['Sex'] in ["female", "f", "F"]:
        player['Sex'] = 'Female'
    elif player['Sex'] in ["male", "m", "M"]:
        player['Sex'] = 'Male'
    if player['Sex'] != 'Female' and player['Sex'] != 'Male':
        player['Sex'] = raw_input("Please enter your character's sex again. Please enter Male or Female. ")
    player['Strength'] = int(round(((random.random() * 100 + 100) / 3))) #Sets stats
    player['Agility'] = int(round(((random.random() * 100 + 100) / 3)))
    player['Health'] = int(round(((random.random() * 100 + 150) / 2)))
    player['Healthmax'] = player['Health']

def Chapter_01(): #Story
    print("You find yourself in a tavern. Around you, people are drinking and conversing with eachother. You sit by the fireplace, which is roaring with heat.")
    print("There are three people next to you that you can talk to: an elderly lady, a young bearded man , and a young blond haired man. Both of the men appear to be in their early twenties.")
    def dialogue_01_function():
        dialogue_01 = raw_input("Type 1 to talk to the lady, 2 to talk to the bearded man, and 3 to talk to the blonde man. ")
        if dialogue_01 == '1':
            print("one")
        elif dialogue_01 == '2':
            print("two")
        elif dialogue_01 == '3':
            print("three")
        else:
            dialogue_01_function()
    dialogue_01_function()

def Save(file_name):
    save = open(str(file_name) + ".txt", "w+")
    save.write(str(player['Name']) + "\n")
    save.write(str(player['Sex']) + "\n")
    save.write(str(player['Health']) + "\n")
    save.write(str(player['Healthmax']) + "\n")
    save.write(str(player['Agility']) + "\n")
    save.write(str(player['Strength']) + "\n")
    save.write(str(player['Level']) + "\n")
    save.write(str(player['Experience']) + "\n")
    save.close()

def Load(file_name):
    try:
        load = open(str(file_name) + ".txt", "r")
    except:
        print("Sorry this save file doesn't exist.")
        return
    if load.mode == "r":
        contents = load.readlines()
        name = contents[0]
        list_name = list(name)
        del list_name[-1]
        joined_name = ''.join(list_name)
        
        sex = contents[1]
        list_sex = list(sex)
        del list_sex[-1]
        joined_sex = ''.join(list_sex)
        
        health = contents[2]
        list_health = list(health)
        del list_health[-1]
        joined_health = ''.join(list_health)
        int_health = int(joined_health)
        
        healthmax = contents[3]
        list_healthmax = list(healthmax)
        del list_healthmax[-1]
        joined_healthmax = ''.join(healthmax)
        int_healthmax = int(joined_healthmax)
        
        agility = contents[4]
        list_agility = list(agility)
        del list_agility[-1]
        joined_agility = ''.join(list_agility)
        int_agility = int(joined_agility)
        
        strength = contents[5]
        list_strength = list(strength)
        del list_strength[-1]
        joined_strength = ''.join(list_strength)
        int_strength = int(joined_strength)
        
        level = contents[6]
        list_level = list(level)
        del list_level[-1]
        joined_level = ''.join(list_level)
        int_level = int(joined_level)
         
        experience = contents[7]
        list_experience = list(experience)
        del list_experience[-1]
        joined_experience = ''.join(list_experience)
        int_experience = int(joined_experience)

        player['Name'] = joined_name
        player['Sex'] = joined_sex
        player['Health'] = int_health
        player['Healthmax'] = int_healthmax
        player['Agility'] = int_agility
        player['Strength'] = int_strength
        player['Level'] = int_level
        player['Experience'] = int_experience
    
def Rest():
    player['Health'] = player['Healthmax']
    print("You have rested and your health has been restored.")

def Main():
    Character_creation()
    n = 0
    while player['Health'] > 0:
        n += 1
        if n == 1:
            print("Commands: Help, Rest, Explore, Stats, Save, Load")
        menu = raw_input("> ")
        if menu in ["Help", "help"]:
            print("Commands: Help, Rest, Explore, Stats, Save, Load")
        elif menu in ["Rest", "rest"]:
            Rest()
        elif menu in ["Stats", "stats"]:
            print(Stats())
        elif menu in ["Save", "save"]:
            file_name = raw_input("Name your save file. ")
            Save(file_name)
        elif menu in ["Load", "load"]:
            file_name = raw_input("What is the name of your save file? Don't include .txt ")
            Load(file_name)
        elif menu in ["Explore", "explore"]:
            shuffle = random.random() * 10 #Makes chance to fight all 3 enemies 1/3
            if shuffle <= 3:
                Fight(goblin)
            elif shuffle >= 7:
                Fight(giant_rat)
            else:
                Fight(feral_dog)
Main()
Reply
#4
Quote:
if menu in ["Help", "help"]:

That can be a little clearer, if you make menu always lowercase.  That way, the player can also do something wacky like "hELp" and it'll still work:
if menu.lower() == "help":
Reply
#5
Thanks, and I might end up doing:
if menu.lower() in ["help", "h"]:
And allow 1 letter abbreviations for all commands for ease of use.
Reply
#6
I love this script; it reminds me of the choose-your-adventure text games I wrote when I was learning to program.

Here are a couple thoughts on code structure (if you don't mind):

Large if/else blocks such as the one you have in the Fight function can quickly get unwieldy. Consider moving the code that handles "hits" and "misses" into their own functions:
if A in ["Attack", "attack", "A", "a"]:
    print("")
    print("You swing at the " + str(Enemy['Name']) + " with your sword!...")
    if (Enemy['Agility'] - player['Agility'] + (random.random() - random.random()) * 100) <= 0: #Do this if player hits enemy
        hit(Enemy, player)
    else:
        miss(Enemy, player)
As you add functionality/details to each action it's all nice and tidy in the hit() and miss() functions. You may also want to consider putting the "hit" calculation in a function as well to enable more complex "hit decisions" without making your code harder to read.

Also, when you find yourself duplicating code, consider making a function. An example is your LevelUp() function that prompts the user and checks for a valid input. The only difference between each block is what you prompt the user for, so you may want to write a function such as this:

def prompt_for_levelup(prompt_message):
    val = input(prompt_message)
    while val not in [0,1,2,3,4,5]:
       print("Error Message")
       val = input(prompt_message)
    return val
Basically, I'm a huge proponent for writing lots of small functions.

Finally, when you have a minute, take a look at the json module. It's a way to convert objects and data to strings and back again. Your Load and Save functions could be reduced to a couple lines each.
Reply
#7
Here one way to handle enemies.
from random import choice

class Enemies:
	enemy = {}
	
	def __init__(self, name, health, agility, strength, level, special=None):
		self.name = name
		self.health = health
		self.agility = agility
		self.strength = strength
		self.level = level
		self.special = special
		# you could simple make another class to handle special
		
		Enemies.enemy[name] = self # store the enemy
		
	def __repr__(self):
		line = "Enemy(Name:{0}, Health:{1}, Agility:{2}, Strength:{3}, Level:{4})"
		return line.format(self.name, self.health, self.agility, self.strength, self.level)		
		
def main():		
	Enemies('Orgre', 100, 20, 60, 2, {'bash': 10, 'swing': 10}) 
	Enemies('Goblin', 50, 40, 35, 1, {'bite': 10}) 
	Enemies('Giant Rat', 40, 55, 30, 1, {'rabies': 20})
	
	# Fight(Enemies.enemy['Goblin'])
	
	enemy = choice(list(Enemies.enemy.keys()))
	# Fight(Enemies.enemy[enemy])
	print(Enemies.enemy[enemy])
	print(Enemies.enemy.keys())
	
if __name__ == '__main__':
	main()
99 percent of computer problems exists between chair and keyboard.
Reply
#8
Hi!
I've copied your code and modified it, I'm added some features like level_up issues and new fight logic. I'm a beginner with python and this exercise help me a lot, even I tried to do it using class but I wasn't successful on it. But you now what? I'm still happy with it.

import random
import sys
import time

player = {}
rat = {"name": "Rat", "experience": 15, "attack": 15, "defense": 5, "health": 20}
snake = {"name": "Snake", "experience": 10, "attack": 18, "defense": 5, "health": 15}
dragon = {"name": "Dragon", "experience": 150, "attack": 50, "defense": 40, "health": 1000}
next_level = [20, 40, 80, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]


def stats():
    print("Current Stats:")
    print("Name: " + str(player["name"]))
    print("Level: " + str(player["level"]))
    print("Experience: " + str(player["experience"]))
    print("Current Health: " + str(player["health"]))
    print("Max Health: " + str(player["max_health"]))
    print("Defense: " + str(player["defense"]))
    print("Attack: " + str(player["attack"]))
    print("-" * 160)


def character():
    player["name"] = input("Enter your character's name. ")
    player["experience"] = 0
    player["level"] = 1
    player["attack"] = 30
    player["defense"] = 10
    player["health"] = 150
    player["max_health"] = player["health"]


def saving(file_name):
    save = open(str(file_name) + ".txt", "w+")
    save.write(str(player["name"]) + "\n")
    save.write(str(player["health"]) + "\n")
    save.write(str(player["max_health"]) + "\n")
    save.write(str(player["defense"]) + "\n")
    save.write(str(player["attack"]) + "\n")
    save.write(str(player["level"]) + "\n")
    save.write(str(player["experience"]) + "\n")
    save.close()
    print("saving successful!")


def loading(file_name):
    try:
        load = open(str(file_name) + ".txt", "r")
    except:
        print("Sorry this save file doesn't exist.")
        return
    if load.mode == "r":
        contents = load.readlines()
        name = contents[0]
        list_name = list(name)
        del list_name[-1]
        joined_name = ''.join(list_name)

        health = contents[1]
        list_health = list(health)
        del list_health[-1]
        joined_health = ''.join(list_health)
        int_health = int(joined_health)

        max_health = contents[2]
        list_healthmax = list(max_health)
        del list_healthmax[-1]
        joined_healthmax = ''.join(max_health)
        int_max_health = int(joined_healthmax)

        defense = contents[3]
        list_agility = list(defense)
        del list_agility[-1]
        joined_agility = ''.join(list_agility)
        int_defense = int(joined_agility)

        attack = contents[4]
        list_strength = list(attack)
        del list_strength[-1]
        joined_strength = ''.join(list_strength)
        int_attack = int(joined_strength)

        level = contents[5]
        list_level = list(level)
        del list_level[-1]
        joined_level = ''.join(list_level)
        int_level = int(joined_level)

        experience = contents[6]
        list_experience = list(experience)
        del list_experience[-1]
        joined_experience = ''.join(list_experience)
        int_experience = int(joined_experience)

        player["name"] = joined_name
        player["health"] = int_health
        player["max_health"] = int_max_health
        player["defense"] = int_defense
        player["attack"] = int_attack
        player["level"] = int_level
        player["experience"] = int_experience

        print("loading successful!")


def rest():
    player["health"] = player["max_health"]
    print("Your health is full.")


def is_alive() -> bool:
    return player["health"] > 0


def level_up():
    for i in next_level:
        if player["experience"] >= i:
            print("-" * 160)
            player["level"] += 1
            player["max_health"] += 15
            player["attack"] += 5
            player["defense"] += 4
            print("You level up!")
            rest()
            print("-" * 160)
            next_level.pop(0)


def fight(enemy):
    print("All of a sudden a " + str(enemy['name']) + " attacks you!")
    creature = enemy.copy()
    turn: int = 0
    while creature["health"] > 0 and is_alive():
        turn += 1
        print("")
        if turn % 2 == 1:
            print("It is your turn to attack.")
            time.sleep(1)
            hit = random.randint(1, player["attack"]) - random.randint(1, player["defense"])
            if hit <= 0:
                print("You miss...")
            else:
                creature["health"] -= hit
                print("You hit " + str(hit) + " on the enemy")
        else:
            print("It is enemy turn to attack.")
            time.sleep(1)
            hit = random.randint(1, creature["attack"]) - random.randint(1, player["defense"])
            if hit <= 0:
                print("The enemy miss...")
            else:
                player["health"] -= hit
                print("The enemy hits " + str(hit) + " on you")

        if creature["health"] > 0 and not is_alive():
            print("GAME OVER! " + str(player["name"]) + " died.")
            sys.exit()

        if is_alive() and creature["health"] <= 0:
            print("")
            print("You won the battle.")
            print("")
            player["experience"] += creature["experience"]
            print("You won " + str(creature["experience"]) + " experience")
            level_up()


def main():
    character()
    print("Hail Adventurer! Welcome to the MyRPG! Please fulfil the information before start the game")
    print("Type (H)elp for more information")
    while True:
        menu = input(">").lower()
        if menu in ["help", "h"]:
            print("Commands: (H)elp, (R)est, (E)xplore, s(T)ats, (S)ave, (L)oad, (Q)uit")
        elif menu in ["rest", "r"]:
            rest()
        elif menu in ["explore", "e"]:
            shuffle = random.randint(1, 10)  
            if shuffle <= 5:
                fight(snake)
            else:
                fight(rat)
        elif menu in ["stats", "t"]:
            stats()
        elif menu in ["save", "s"]:
            salvar = input("Type the file name to save: ")
            saving(salvar)
        elif menu in ["load", "l"]:
            carregar = input("Type the file name to load: ")
            loading(carregar)
        elif menu in ["quit", "q"]:
            print("You quit the game.")
            sys.exit()
        else:
            print("Invalid Key, please try again")


main()
Reply
#9
uribrasil - why are you answering questions from 2017?
Reply
#10
can't I give a new feedback to the people?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020