I am working on a rather simple game, but I'm struggling with implementing a feature where when a player has a weapon and chooses to attack, I want to find if any players are within the weapon's attack distance (within the circumference of that distance) and if I find any other players, then I want to eliminate them.
The space that I'm working on in under "game.py -> processPlayerInput", I have a current attempt at a solution for the "grenade", but it's not elegant, and it's not really easy to implement for my larger "gun" range.
Game.py is as follows:
from treasure import Treasure
from player import Player
from randomNum import Random
import sys
from randomNum import Random
rand= Random()
if len(sys.argv) > 1:
rand.setSeed(int(sys.argv[1]))
from weapon import Weapon
class Game:
# the constructor (initialize all game variables)
def __init__(self, w, h, numPlayers):
self.gameBoardWidth = w;
self.gameBoardHeight = h;
self.listOfPlayers = []
self.listOfTreasures = []
self.listOfWeapons = []
for player in range(numPlayers):
player = Player(rand.randrange(w), rand.randrange(h), str(player + 1))
self.listOfPlayers.append(player)
t1 = Treasure("silver","S", 20, rand.randrange(w), rand.randrange(h))
self.listOfTreasures.append(t1)
t2 = Treasure("gold","G", 25, rand.randrange(w), rand.randrange(h))
self.listOfTreasures.append(t2)
t3 = Treasure("platinum", "P", 50, rand.randrange(w), rand.randrange(h))
self.listOfTreasures.append(t3)
t4 = Treasure("diamond", "D", 40, rand.randrange(w), rand.randrange(h))
self.listOfTreasures.append(t4)
t5 = Treasure("emerald", "E", 35, rand.randrange(w), rand.randrange(h))
self.listOfTreasures.append(t5)
w1 = Weapon("gun", "/", 7, rand.randrange(w), rand.randrange(h))
self.listOfWeapons.append(w1)
w2 = Weapon("grenade", "o", 4, rand.randrange(w), rand.randrange(h))
self.listOfWeapons.append(w2)
def play(self):
self.printInstructions()
self.drawUpdatedGameBoard()
# MAIN GAME LOOP to ask players what they want to do
currentPlayerNum = 0
while (len(self.listOfTreasures) >= 1) and (len(self.listOfPlayers) > 1):
# get the player object for the player whose turn it is
currentPlayer = self.listOfPlayers[currentPlayerNum];
# ask the player what they would like to do
choice = input("Player " + currentPlayer.gameBoardSymbol + ", do you want to (m)ove or (r)est? ")
self.processPlayerInput(currentPlayer, choice)
# show the updated player information and game board
self.printUpdatedPlayerInformation();
self.drawUpdatedGameBoard()
# update whose turn it is
currentPlayerNum += 1
if currentPlayerNum >= len(self.listOfPlayers):
currentPlayerNum = 0
var = ""
var_score = 0
for i in self.listOfPlayers:
if i.getPoints() > var_score:
var = i.gameBoardSymbol
var_score = i.getPoints()
print("Player " + var + " wins!")
def processPlayerInput(self, plyr, action) :
if action == "m": # move
direction = input("Which direction (r, l, u, or d)? ")
distance = int(input("How Far? "))
if plyr.energy >= distance / 2:
plyr.move(direction,distance)
plyr.energy -= distance / 2
else:
plyr.move(direction, (plyr.energy * 2))
plyr.energy = 0.0
# check to see if player moved to the location of another game item
for treasure in self.listOfTreasures:
if plyr.x == treasure.x and plyr.y == treasure.y:
plyr.collectTreasure(treasure)
print("You collected",treasure.name,"worth",treasure.pointValue,"points!")
self.listOfTreasures.remove(treasure) # remove the treasure from the list of available treasures
break
for weapon in self.listOfWeapons:
if plyr.x == weapon.x and plyr.y == weapon.y:
plyr.collectWeapon(weapon)
print("You aquired the" + str(weapon.name) + "!")
self.listOfWeapons.remove(weapon)
break
for player in self.listOfPlayers:
if plyr.x == player.x and plyr.y == player.y and plyr.gameBoardSymbol != player.gameBoardSymbol:
self.listOfPlayers.remove(player)
print("You eliminated player",player.gameBoardSymbol,"from the game!")
break
elif action == "r":
plyr.energy += 4
elif action == "a": #the player wants to use a weapon to attack other players
#if the player has a gun, use that, otherwise use a grenade, if player has neither, do nothing. check if players are within the weapon striking distance circumference in any direction and eliminate them
if plyr.hasWeapon("gun"):
for player in self.listOfPlayers:
for weaponRange in range(-7,7):
if (player.x == plyr.x and player.y == plyr.y + weaponRange) or (player.y == plyr.y and player.x == plyr.x + weaponRange):
self.listOfPlayers.remove(player)
if (player.x == (plyr.x) or player.x == (plyr.x+1) or player.x == (plyr.x-1)) and (player.y == (plyr.y + 7) or player.y == (plyr.y - 7)):
self.listOfPlayers.remove(player)
elif (player.y == (plyr.y) or player.y == (plyr.y+1) or player.y == (plyr.y-1)) and (player.x == (plyr.x + 7) or player.x == (plyr.x - 7)):
self.listOfPlayers.remove(player)
elif plyr.hasWeapon("grenade"):
for player in self.listOfPlayers:
for weaponRange in range(-3,3):
if (player.x == plyr.x and player.y == plyr.y + weaponRange) or (player.y == plyr.y and player.x == plyr.x + weaponRange):
self.listOfPlayers.remove(player)
if (player.x == (plyr.x) or player.x == (plyr.x+1) or player.x == (plyr.x-1)) and (player.y == (plyr.y + 4) or player.y == (plyr.y - 4)):
self.listOfPlayers.remove(player)
elif (player.y == (plyr.y) or player.y == (plyr.y+1) or player.y == (plyr.y-1)) and (player.x == (plyr.x + 4) or player.x == (plyr.x - 4)):
self.listOfPlayers.remove(player)
else :
print("Sorry, that is not a valid choice")
def printUpdatedPlayerInformation(self):
for p in self.listOfPlayers:
print("Player " + p.gameBoardSymbol + " has " + str(p.getPoints()) + " points and has " + str(p.energy) + " energy")
def drawUpdatedGameBoard(self) :
# loop through each game board space and either print the gameboard symbol
# for what is located there or print a dot to represent nothing is there
for y in range(0,self.gameBoardHeight):
for x in range(0,self.gameBoardWidth):
symbolToPrint = "."
for treasure in self.listOfTreasures:
if treasure.x == x and treasure.y == y:
symbolToPrint = treasure.gameBoardSymbol
for player in self.listOfPlayers:
if player.x == x and player.y == y:
symbolToPrint = player.gameBoardSymbol
for weapon in self.listOfWeapons:
if weapon.x == x and weapon.y == y:
symbolToPrint = weapon.gameBoardSymbol
print(symbolToPrint,end="")
print() # go to next row
print()
def printInstructions(self) :
print("Players move around the game board collecting treasures worth points")
print("The game ends when all treasures have been collected or only 1 player is left")
print("Here are the point values of all of the treasures:")
for treasure in self.listOfTreasures :
print( " " + treasure.name + "(" + treasure.gameBoardSymbol + ") " + str(treasure.pointValue) )
print()
If you would like the other classes, please let me know and I can attach them here as well.
Seem you just need to compare distance (here squared euclidean distance):
for player in self.listOfPlayers:
if (player.x-plyr.x)**2+(player.y-plyr.y)**2 <= grenaderadius**2:
self.listOfPlayers.remove(player)
Also note that removing players from the list during iteration might a bad idea (potential cause of errors).
At some parts of my code its just stop and doesn't go back to the move(). I want it to add the score and i did that with score = score + 100 BUT it just disrupts the code ;-;. Its a bit messy and i'm sorry about that but please help I have NO clue why it does this. Fyi I'm using this code on pythonroom if that helps.
import random
weapon = "Wooden Sword"
Damage0 = 1
Damage1 = 8
Speed = 6
lives = 5
score = 0
gold = 80
armor = "Nothing"
health = 20
def please():
name = input("Please put a name and not nothing.")
if name == "":
please1(name)
else:
yon(name)
def please1(name):
name = input("Please put a name and not nothing.")
if name == "":
please1(name)
else:
yon1(name)
def yon(name):
print("So your name is " + name + "?")
yon = input("Is this your name? ''" + name + "'' [Yes] or [No]?")
if yon == "Yes":
begining()
elif yon == "yes":
begining()
else:
sorry(name)
def yon1(name):
yon = input("Is this your +name? ''" + name + "'' [Yes] or [No]?")
if yon == "Yes":
begining()
elif yon == "yes":
begining()
else:
sorry1(name)
def sorry(name):
print(" ")
print("I'm sorry, so what is your name?")
print(" ")
name = input("What is you name?")
if name != "":
yon(name)
else:
please1(name)
def sorry1(name):
name = input("What is you name?")
if name != "":
yon1(name)
else:
please1(name)
def move():
Next = input("Will you go and fight a monster or check stats or quit the game? [Fight] [Stats] [Travel] [Quit]")
Next = Next.lower()
if "tat" in Next:
Stats()
elif "ight" in Next:
Fight()
elif "ravel" in Next:
travel()
elif "uit" in Next:
print("As you quit the game your character disapears...")
else:
move()
def Fight():
your_speed = Speed
enemy_speed = 2
if enemy_speed >= your_speed:
print("The " + enemy + " is faster, it goes first!")
enemy_first()
else:
print("You're faster and get to go first!")
your_first()
def end(enemy_health,your_health):
if your_health > 0:
print(" ")
print("You defeat the Ork")
score = score + 100
gold = gold + 50 'it stops here and won't continue why?
print(gold)
print(score)
move()
else:
print("The ork beat you!")
move()
def your_first():
enemy_health = 20
your_health = health
while your_health > 0 and enemy_health > 0:
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
enemy_health = 0
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
enemy_damage = random.choice(range(3, 12))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
end(enemy_health,your_health)
else:
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
def enemy_first():
enemy_health = 20
your_health = health
while your_health > 0 and enemy_health > 0:
enemy_damage = random.choice(range(3, 12))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
end(enemy_health,your_health)
else:
print(" ")
print("Ork dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("Enemy's health:" + str(enemy_health))
def Stats():
if weapon == "Wooden Sword":
Damage = 1, 8
Damage0 = 1
Damage1 = 8
Speed = 6
if weapon == "Rusty Sword":
Damage = 13, 17
Damage0 = 13
Damage1 = 17
Speed = 4
if weapon == "Bow":
Damage = 2, 13
Damage0 = 2
Damage1 = 13
Speed = 10
if weapon == "Bronze Sword":
Damage = 18, 24
Damage0 = 18
Damage1 = 24
Speed = 1
if weapon == "Magic Spell":
Damage = 25, 33
Damage0 = 25
Damage1 = 33
Speed = 10
if armor == "Nothing":
health = 20
print(" ")
print(" ")
print("(+)~~~~~~~~~~~~~~~~~~~~~~")
print(" | Your | Health: ")
print(" | Stats | " + str(health) + " ")
print(" |----------------------- ")
print(" | Weapon Stats: ")
print(" | Damage: "+str(Damage)+" ")
print(" | Speed: "+str(Speed)+" ")
print("(+)~~~~~~~~~~~~~~~~~~~~~~")
print(" Your Score:"+ str(score) +" ")
print(" ")
print(" ")
move()
def begining():
print(" ")
print("Welcome to the nexus!")
print("It is the center of this world.")
print("It is also called the hub.")
print("During the game you can gather items and get xp")
print("At the end of the game you can see your score based")
print("on how well you did and how many items you found!")
move()
def travel():
travel = input("Where will you travel to? [Cave] [Market] [Boss]")
if "ve" in travel:
cave()
elif "et" in travel:
market()
elif "ss" in travel:
Boss_fight()
else:
move()
def cave():
print("pie")
def market():
print("pie")
def Boss_fight():
your_speed = Speed
enemy_speed = 2
if enemy_speed >= your_speed:
print("The " + enemy + " is faster, it goes first!")
Boss_Boss_first
else:
print("You're faster and get to go first!")
Boss_Your_First()
def Boss_end(enemy_health,your_health):
if your_health > 0:
print(" ")
print("You defeat The Boss")
score = score + 2000
move()
else:
print(" ")
if lives == 3 or lives == 2 or lives == 1:
print("The Boss beats you!")
lives = lives - 1
print("You have " + str(lives) + " left")
move()
else:
start= input("Restart or Quit?")
if "start" in start or "try" in start:
reset(xp,lvl,weapon)
else:
print(" ")
def Boss_Your_First():
enemy_health = 50
your_health = health
while your_health > 0 and enemy_health > 0:
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
enemy_health = 0
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
enemy_damage = random.choice(range(15, 19))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
def Boss_Boss_first():
enemy_health = 50
your_health = health
while your_health > 0 and enemy_health > 0:
enemy_damage = random.choice(range(15, 19))
your_health -= enemy_damage
if your_health <= 0:
your_health = 0
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("The Boss dealt " + str(enemy_damage) + " damage!")
print("Your health:" + str(your_health))
your_damage = random.choice(range(Damage0, Damage1))
enemy_health -= your_damage
if enemy_health <= 0:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
Boss_end(enemy_health,your_health)
else:
print(" ")
print("You dealt " + str(your_damage) + " damage!")
print("The Boss's health:" + str(enemy_health))
print(" ")
print("Hello. What is your name?")
print(" ")
name = input("What is you name?")
if name == "":
please()
else:
yon(name)
You're trying to assign to global variable score within function end like this:
val = 5
def func():
val += 5
It won't work and will result to UnboundLocalError. In order to fix the issue just use keyword global:
val = 5
def func():
global val
val += 5
Here's the error I'm getting:
Traceback (most recent call last):
File "E:\python\cloud.py", line 34, in <module>
c = Cloud()
File "E:\python\cloud.py", line 18, in __init__
self.cweaponAttack = self.weaponAttack[0]
IndexError: list index out of range
I'm having trouble with my code and I have checked for spelling errors everywhere but I haven't found any.
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
self.sp = 1
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.cweapon = self.weapon
self.money = 10000
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
addaps = self.cweaponAttack * self.attackPower
self.dmg = self.cweaponAttack + addaps
self.hp = 100
self.mhp = 100
self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")
The lines above is where i'm positive that the error is coming from, but just in case, here's the rest of the code. Warning: It's very long.
import random
import time
import sys
def asky():
ask = input("Would you like to check you player stats and inventory or go to the next battle? Say inventory for inventory or say next for the next battle: ")
if "inventory" in ask:
inventory()
elif "next" in ask:
user()
def Type(t):
t = list(t)
for a in t:
sys.stdout.write(a)
time.sleep(.035)
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
self.sp = 1
self.armor = list()
self.armorReduction = list()
self.weapon = list()
self.cweapon = self.weapon
self.money = 10000
self.lvl = 0
self.exp = 0
self.mexp = 100
self.attackPower = 0
addaps = self.cweaponAttack * self.attackPower
self.dmg = self.cweaponAttack + addaps
self.hp = 100
self.mhp = 100
self.name = "Cloud"
c = Cloud()
armors = ["No Armor","Belice Armor","Yoron's Armor","Andrew's Custom Armor","Zeus' Armor"]
armorReduce = [0, .025, .05, .10, .15]
c.armor.append(armors[0])
c.armorReduction.append(armorReduce[0])
w = random.randint(0, 10)
weapons = ["The Sword of Wizdom","The Sword of Kindness", "The Sword of Power", "The Sword of Elctricity", "The Sword of Fire", "The Sword of Wind", "The Sword of Ice", "The Sword of Self Appreciation", "The Sword of Love", "The Earth Sword", "The Sword of The Universe"]
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c.weapon.append(weapons[w])
c.weaponAttack.append(weaponAttacks[w])
print("You have recieved the ", weapons[w])
print("")
print("It does ", weaponAttacks[w]," attack power!")
print("")
class Soldier:
def __init__(self):
dmg = random.randint(5,20)
self.lvl = 0
self.attackPower = dmg
self.hp = 100
self.mhp = 100
self.name = "Soldier"
s = Soldier()
def enemy():
ad = random.randint(0,2)
if ad >= 1: #Attack
Type("Soldier attacks!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
hm = random.randint(0, 2)
if hm == 0:
Type("Miss!")
print("")
elif hm > 0:
crit = random.randint(0,10)
if crit == 0:
print("CRITICAL HIT!")
crithit = int((s.attackPower) * (.5))
c.hp = c.hp - (s.attackPower + crithit)
elif crit >= 1:
c.hp = c.hp - s.attackPower
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
asky()
c.exp = c.exp + 100
else:
user()
elif ad == 0:#Defend
Type("Soldier Defends!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if s.hp == s.mhp:
print("")
elif s.hp > (s.mhp - 15) and s.hp < s.mhp:
add = s.mhp - s.hp
s.hp = add + s.hp
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
elif s.hp < (s.mhp - 15):
s.hp = s.hp + 15
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
asky()
c.exp = c.exp + 100
else:
user()
def user():
User = input("attack or defend? ")
if "attack" in User:#attack
Type("Cloud attacks!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
hm = random.randint(0,4)
if hm == 0:
Type("Miss!")
print("")
elif hm > 0:
crit = random.randint(0,7)
if crit == 0:
print("CRITICAL HIT!")
crithit = int((c.dmg) * (.5))
s.hp = s.hp - (c.dmg + crithit)
elif crit >= 1:
s.hp = s.hp - c.dmg
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
c.exp = c.exp + 100
asky()
else:
enemy()
elif "defend" in User:#defend
Type("Cloud Heals!")
print("")
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp == c.mhp:
Type("You are at the maximum amount of health. Cannot add more health.")
print("")
elif c.hp > (c.mhp - 15) and c.hp < c.mhp:
add = c.mhp - c.hp
c.hp = add + c.hp
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
elif c.hp <= (c.mhp - 15):
c.hp = c.hp + 15
Type("Cloud Health: ")
print(c.hp)
Type("Enemy Health: ")
print(s.hp)
if c.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("GAME OVER")
print("")
Type("You Lost!")
print("")
elif s.hp <= 0:
adds = s.mhp - s.hp
s.hp = s.hp + adds
Type("Congratulations!")
print("")
Type("You Won!")
print("")
Type("You recieved 100 crystals to spend at the shop!")
print("")
c.money = c.money + 100
c.exp = c.exp + 100
asky()
else:
enemy()
else:
Type("The option you have entered is not in the game database. Please try again")
print("")
user()
def inventory():
if c.exp == c.mexp:
print("LEVEL UP!")
c.exp = 0
adde = int((c.mexp) * (.5))
c.mexp = c.mexp + adde
c.sp = c.sp + 1
c.lvl = c.lvl + 1
if c.lvl > s.lvl:
s.lvl = s.lvl + 1
print("")
print("")
print("Level: ", c.lvl)
print("")
nextlvl = c.lvl + 1
print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
print("")
print("Amount of Skill Points:", c.sp)
print("")
for i in range(0, len(c.weapon)):
print(i)
print("Weapon: ", c.weapon[i])
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
for j in range(0, len(c.armor)):
print("Armor: ", c.armor[j])
print("Armor Damage Reduction: ", c.armorReduction[j])
print("")
print("Amount of Crystals: ", c.money)
print("")
print("")
print("Stats:")
print("")
print("Maximum Health: ", c.mhp)
print("")
print("Current Health: ", c.hp)
print("")
dtop = 100 * c.attackPower
print("Attack Power: Adds", dtop, "% of sword damage")
print("")
print("Overall Damage: ", c.dmg)
print("")
print("Your Name: ", c.name)
print("")
print("")
sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), or say, *help* for help: ")
print("")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "weapon" in sn:
weapChange()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
def helpp():
Type("The goal of this game is to fight all the enemies, kill the miniboss, and finally, kill the boss! each time you kill an enemy you gain *crystals*, currency which you can use to buy weapons, armor, and health. You can spend these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to defeat. Once you level up, you gain one skill point. This skill point is then used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack power.")
print("")
continu = input("Say, *back*, to go back to your inventory screen. ")
if "back" in continu:
inventory()
else:
Type("The word you have entered is invalid. Please try again.")
print("")
helpp()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
else:
print("Level: ", c.lvl)
print("")
nextlvl = c.lvl + 1
print("Experience: [", c.exp, "/", c.mexp, "]level", nextlvl)
print("")
print("Amount of Skill Points:", c.sp)
print("")
for i in range(0, len(c.weapon)):
print("Weapon:", c.weapon[i])
print("")
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
for i in range(0, len(c.armor)):
print("Armor: ", c.armor[i])
print("")
print("Armor Damage Reduction: ", c.armorReduction[i])
print("")
print("Amount of Crystals: ", c.money)
print("")
print("")
print("Stats:")
print("")
print("Maximum Health: ", c.mhp)
print("")
print("Current Health: ", c.hp)
print("")
dtop = 100 * c.attackPower
print("Attack Power: Adds", dtop, "% of sword damage")
print("")
print("Your Name: ", c.name)
print("")
print("")
sn = input("To heal yourself, you need to go to the shop. Say, *shop* to go to the shop, say *name* to change your name, say, *next* to fight another battle, say, *level* to use your skill point(s), say, *weapon* to switch your current weapon, or say, *help* for help: ")
if "name" in sn:
c.name = input("Enter Your name here: ")
print("Success! Your name has been changed to ", c.name)
inventory()
elif "weapon" in sn:
weapChange()
elif "next" in sn:
Type("3")
print("")
Type("2")
print("")
Type("1")
print("")
Type("FIGHT!")
print("")
user()
elif "help" in sn:
def helpp():
Type("The goal of this game is to fight all the enemies, kill the miniboss, and finally, kill the boss! each time you kill an enemy you gain *crystals*, currency which you can use to buy weapons, armor, and health. You can spend these *crystals* at the shop. To go to the shop, just say *shop* when you are in your inventory. Although, each time you level up, they get harder to defeat. Once you level up, you gain one skill point. This skill point is then used while in your inventory by saying the word *level*. You can use your skill point(s) to upgrade your stats, such as, your maximum health, and your attack power. To switch out your weapons, type in, *weapon*.")
print("")
continu = input("Say, *back*, to go back to your inventory screen. ")
if "back" in continu:
inventory()
else:
Type("The word you have entered is invalid. Please try again.")
print("")
helpp()
helpp()
elif "shop" in sn:
shop()
elif "level" in sn:
skills()
def weapChange():
for i in range(0, len(c.weapon)):
print("Weapon:", "To equip", c.weapon[i], ",say", i)
print("Weapon Attack Damage: ", c.weaponAttack[i])
print("")
weapchoice = input("Enter the weapon ID to the sword you would like to equip, or say, *cancel*, to go back to your inventory. ")
print("")
if "0" in weapchoice:
c.cweapon = c.weapon[0]
c.cweaponAttack = c.weaponAttack[0]
print("Success!", c.weapon[0], "is now equipped!")
inventory()
elif "1" in weapchoice:
c.cweapon = c.weapon[1]
print("Success!", c.weapon[1], "is now equipped!")
inventory()
c.cweaponAttack = c.weaponAttack[1]
elif "2" in weapchoice:
c.cweaponAttack = c.weaponAttack[2]
c.cweapon = c.weapon[2]
print("Success!", c.weapon[2], "is now equipped!")
inventory()
elif "3" in weapchoice:
c.cweaponAttack = c.weaponAttack[3]
c.cweapon = c.weapon[3]
print("Success!", c.weapon[3], "is now equipped!")
inventory()
elif "4" in weapchoice:
c.cweaponAttack = c.weaponAttack[4]
c.cweapon = c.weapon[4]
print("Success!", c.weapon[4], "is now equipped!")
inventory()
elif "5" in weapchoice:
c.cweaponAttack = c.weaponAttack[5]
c.cweapon = c.weapon[5]
print("Success!", c.weapon[5], "is now equipped!")
inventory()
elif "6" in weapchoice:
c.cweaponAttack = c.weaponAttack[6]
c.cweapon = c.weapon[6]
print("Success!", c.weapon[6], "is now equipped!")
inventory()
elif "7" in weapchoice:
c.cweaponAttack = c.weaponAttack[7]
c.cweapon = c.weapon[7]
print("Success!", c.weapon[7], "is now equipped!")
inventory()
elif "8" in weapchoice:
c.cweaponAttack = c.weaponAttack[8]
c.cweapon = c.weapon[8]
print("Success!", c.weapon[8], "is now equipped!")
inventory()
elif "9" in weapchoice:
c.cweaponAttack = c.weaponAttack[9]
c.cweapon = c.weapon[9]
print("Success!", c.weapon[9], "is now equipped!")
inventory()
elif "cancel" in weapchoice:
inventory()
else:
Type("The word or number you have entered is invalid. Please try again.")
print("")
print("")
weapChange()
def skills():
print("")
print("You have", c.sp, "skill points to use.")
print("")
print("Upgrade attack power *press the number 1*")
print("")
print("Upgrade maximum health *press the number 2*")
print("")
skill = input("Enter the number of the skill you wish to upgrade, or say, cancel, to go back to your inventory screen. ")
print("")
if "1" in skill:
sure = input("Are you sure you want to upgrade your character attack power in return for 1 skill point? *yes or no* ")
print("")
if "yes" in sure:
if c.sp == 0:
Type("I'm sorry but you do not have sufficient skill points to upgrade your attack power. ")
print("")
skills()
elif c.sp >= 1:
c.sp = c.sp - 1
c.attackPower = float(c.attackPower + .1)
addsap = int(100 * c.attackPower)
print("Your attack power has been upgraded to deal", addsap, "% more damage")
skills()
else:
Type("How the fuck did you get negative skill points?! ")
print("")
skills()
if "no" in sure:
skills()
elif "2" in skill:
sure = input("Are you sure you want to upgrade your maximum health in return for 1 skill point? *yes or no* ")
print("")
if "yes" in sure:
if c.sp == 0:
Type("I'm sorry but you do not have sufficient skill points to upgrade your maximum health. ")
print("")
skills()
elif c.sp >= 1:
c.sp = c.sp - 1
c.mhp = c.mhp + 30
skills()
else:
Type("How the fuck did you get negative skill points?! ")
print("")
skills()
if "no" in sure:
skills()
elif "cancel" in skill:
inventory()
else:
Type("The word or number you have entered is invalid. Please try again.")
print("")
skills()
def shop():
print("")
Type("Welcome to Andrew's Blacksmith! Here you will find all the weapons, armor, and health you need, to defeat the horrid beast who goes by the name of Murlor! ")
print("")
print("")
print("Who's Murlor? *To ask this question, type in the number 1*")
print("")
print("Can you heal me? *To ask this question, type in the number 2*")
print("")
print("What weapons do you have? *To ask this question, type in the number 3*")
print("")
print("Got any armor? *To ask this question, type in the number 4*")
print("")
ask1 = input("Enter desired number here or say, cancel, to go back to your inventory screen. ")
print("")
if "1" in ask1:
def murlor():
Type("Murlor is a devil-like creature that lives deep among the caves of Bricegate. He has been terrorising the people of this village for centuries.")
print("")
print("")
print("What is Bricegate? *To choose this option, type in the number 1*")
print("")
print("Got any more information about this village? *To choose this option, type in the number 2*")
print("")
print("Thank you! *To choose this option, type in the number 3*")
print("")
ask3 = input("Enter desired number here, or say, cancel, to go back to the main shop screen. ")
print("")
if "1" in ask3:
def questionTown():
Type("That's the name of this town.")
print("")
print("")
town = input("Go back? *Say, yes, to go back to the previous screen*")
print("")
if "yes" in town:
murlor()
else:
Type("I'm sorry but the word you have entered is invalid. Please try again.")
print("")
print("")
questionTown()
questionTown()
elif "2" in ask3:
def askquest1():
Type("Well I DO know that there's this secret underground dungeon. It's VERY dangerous but it comes with a huge reward. If you ever consider it, could you get my lucky axe? I dropped it down a hole leading to the dungeon and i was too afraid to get it back. *If you accept the quest, say yes, if you want to go back, say, no.*")
quest1 = input(" ")
print("")
if "yes" in quest1:
quest1()
elif "no" in quest1:
murlor()
else:
Type("The option you have selected is not valid. Please try again")
print("")
print("")
askquest1()
askquest1()
elif "3" in ask3:
shop()
else:
Type("The number or word you have entered is invalid. please try again.")
print("")
print("")
murlor()
murlor()
elif "2" in ask1:
def heal():
if c.hp == c.mhp:
Type("I can't heal you because there's nothing to heal.")
print("")
print("")
shop()
elif c.hp > 10 and c.hp < c.mhp:
Type("Sure! That'll be 30 crystals.")
ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
print("")
if "okay" in ask2:
if c.money < 30:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
print("")
shop()
elif c.money >= 30:
c.money = c.money - 30
Type("30 crystals has been removed from your inventory.")
print("")
print("")
addn = c.mhp - c.hp
c.hp = c.hp + addn
Type("You have been healed!")
print("")
print("")
shop()
elif "no" in ask2:
shop()
else:
Type("The option you have chosen is invalid. Please try again")
print("")
print("")
heal()
elif c.hp > 0 and c.hp <= 10:
Type("How are you still alive?!")
print("")
print("")
Type("That'll be 50 crystals.")
ask2 = input(" *say, okay, to confirm the purchase or say, no, to cancel the pruchase* ")
print("")
if "okay" in ask2:
if c.money < 30:
Type("I'm sorry sir, but you don't have enough crystals to buy this.")
print("")
print("")
shop()
elif c.money >= 30:
c.money = c.money - 30
Type("30 crystals has been removed from your inventory.")
print("")
print("")
addn = c.mhp - c.hp
c.hp = c.hp + addn
Type("You have been healed!")
print("")
print("")
shop()
elif "no" in ask2:
shop()
else:
Type("The option you have chosen is invalid. Please try again")
print("")
print("")
heal()
else:
Type("HELP!! IT'S THE WALKING DEAD!!")
print("")
print("")
shop()
heal()
user()
class Cloud:
def __init__(self):
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
You set self.weaponAttack to be an empty list, and then try to assign cweaponAttack to be the element at index 0 in weaponAttack - empty lists don't have anything at index 0, as they are empty. I'm guessing you want self.cweaponAttack to be nothing when a new Cloud instance is created, in which case if you need it to be nothing you can set it to be None, else you can just assign to it when needed.
self.cweaponAttack = None
self.weaponAttack = list()
self.cweaponAttack = self.weaponAttack[0]
At the time of the second line, self.weaponAttackis an empty list, and therefore doesn't have any elements. Hence, an index of 0 is out of range for self.weaponAttack.
At the time the instance of the class is first created with Cloud(), self.weaponAttack is an empty list, and there will be no such thing as an index 0.
You may consider passing a non-empty list to self.weaponAttack as an argument via the class constructor:
weaponAttacks = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
c = Cloud(weaponAttacks)
And your class becomes:
class Cloud:
'''This is the Cloud class etc.'''
weaponAttack = list()
def __init__(self, weaponAttacks):
self.weaponAttack = weaponAttacks
self.cweaponAttack = self.weaponAttack[0]
Well here's the problem my game() function wont go to my firstlevel() function and just keeps says process exited with exit code 0 And I have no clue why I even tried changing the function name And still no luck I truly have no clue what to do I am just a beginner...
code:
import winsound
import random as ran
import pickle
profile = {}
def fightsound():
winsound.PlaySound('fight2.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
def ranking():
if profile['xp'] >= 20:
profile['level'] += 1
if profile['xp'] >= 50:
profile['level'] += 1
if profile['xp'] >= 100:
profile['level'] += 1
game()
else:
game()
else:
game()
else:
game()
def play_bgmusic():
winsound.PlaySound('mk.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
def load_game():
global profile
profile = pickle.load(open("save.txt", "rb"))
game()
def fatality():
winsound.PlaySound('fatal2.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)
def game():
global profile
print("Player: " + profile['player'])
print("XP: ", profile['xp'])
print("Level: ", profile['level'])
print("win: ", profile['win'])
print("loss: ", profile['loss'])
if profile['level'] >= 1:
print("1.) The ogre king...")
if profile['level'] >= 2:
print("2.) The realm of the witch!")
y = input("Select an option -> ")
if y == 1:
firstlevel()
def firstlevel():
global profile
fightsound()
enemyhp = 50
hp = 100
while enemyhp > 0:
print("Your hp: ", hp, " Enemy hp: ", enemyhp)
input("Press enter to attack...")
damage = ran.randint(0, 25)
enemyhp -= damage
damage = ran.randint(0, 25)
hp -= damage
if hp <= 0:
profile['xp'] += 5
profile['loss'] += 1
pickle.dump(profile, open("save.txt", "wb"))
print("You died, press enter to continue...")
game()
fatality()
profile['xp'] += 10
profile['win'] += 1
pickle.dump(profile, open("save.txt", "wb"))
input("You win! Press enter to continue...")
ranking()
def new_game():
global profile
player = input("Enter a player name -> ")
profile['player'] = player
profile['xp'] = 0
profile['level'] = 1
profile['win'] = 0
profile['loss'] = 0
pickle.dump(profile, open("save.txt", "wb"))
game()
def main():
play_bgmusic()
print(20 * "-")
print("| |")
print("| 1.) New Game |")
print("| 2.) Load Game |")
print("| 3.) Credits |")
print("| |")
print(20 * "-")
x = int(input("Select an option -> "))
if x == 1:
new_game()
if x == 2:
load_game()
if x == 3:
pass
main()
The problem is these three lines:
y = input("Select an option -> ")
if y == 1:
firstlevel()
When you get input, it will come back as a string. You are comparing the string "1" to the integer 1. The two are not equal, so firstlevel() is never called.
You should convert the string to an integer, or change the integer to a string, so that you are comparing two objects of the same type.
Gonna bet it's cause y isn't what you think it is. Try printing it out or putting a breakpoint on it to make sure it is an integer with value 1.
The problem is here:
y = input("Select an option -> ")
if y == 1:
input() returns a string, so it will never be equal to the integer 1. Simply use int() on y before your comparison and you'll be good to go.