I created a code as a collaboration for a game a few friends and I are making for fun, and I am a complete noob at python. I created a class for a battle arena as part of the game:
from tkinter import *
import random
root = Tk()
class battle:
def __init__(self, MonHealth):
self.Distance = 10
self.Center = 5
self.MonHealth = MonHealth
def LEFT1(self):
if self.Center < 20:
self.Distance += 1
distance = abs(self.Distance)
self.Center += 1
center = abs(self.Center)
print (str(distance) + " meters" + " " + str(center) + " meters")
def right1(self):
if self.Center > -20:
self.Distance -= 1
self.Center -= 1
center = abs(self.Center)
distance = abs(self.Distance)
print (str(distance) + " meters" + " " + str(center) + " meters")
def Lunge1(self):
hit = [0,1,2,3,4]
random.shuffle(hit)
if abs(self.Distance) <= 1 and hit[0] >= 2:
print ("strike")
self.MonHealth -= 10
if self.MonHealth < 0:
print ("YOU WIN")
elif abs(self.Distance) <= 1:
print ("blocked")
else:
print ("miss")
def block1(self):
print ("blocked enemy")
root.bind("<Left>", LEFT1)
root.bind("<Right>", right1)
root.bind("<Return>", Lunge1)
root.bind("<Shift_L>", block1)
When I run the class, I get the following error:
AttributeError: 'Event' object has no attribute 'Center'
How do I fix this problem?
I read other explanations and solutions about/for attribute errors, but they were all about 'str' objects.
As a side note, if I delete 'Center' entirely, it gives me the same error for MonHealth. I think I just completely screwed up this code, but is there any way to salvage it? Thanks!
You're using your class wrongly. You have ti initialize it first:
a=battle(45) # you can use any number you want instead of 45
Then you have to bind
as follows:
root.bind("<Left>", a.LEFT1)
root.bind("<Right>", a.right1)
root.bind("<Return>", a.Lunge1)
root.bind("<Shift_L>", a.block1)
You can also decorate your class's methods as @classmethod
, but it won't make much sense in your case as you'll still have to initialize the self.MonHealth
variable.