# Start with this file:
events-starter-code.py
class Monster(object):
def __init__(monster, cx, cy, color, strength):
monster.cx = cx
monster.cy = cy
monster.r = 20
monster.color = color
monster.strength = strength
def init(data):
data.monsters = [ ]
data.colors = ['red', 'orange', 'yellow', 'lightGreen', 'cyan']
data.colorIndex = 0
def getNextColor(data):
nextColor = data.colors[data.colorIndex]
data.colorIndex = (data.colorIndex + 1) % len(data.colors)
return nextColor
def monsterContainsPoint(monster, x, y):
d = ((monster.cx - x)**2 + (monster.cy - y)**2)**0.5
return (d <= monster.r)
def findMonster(data, x, y):
for monster in data.monsters:
if (monsterContainsPoint(monster, x, y) == True):
return monster
return None
def mousePressed(event, data):
monster = findMonster(data, event.x, event.y)
if (monster == None):
# did not click on a monster, so make a new one!
monster = Monster(event.x, event.y, getNextColor(data), 5)
data.monsters.append(monster)
else:
# clicked on a monster, so reduce its strength
monster.strength -= 1
if (monster.strength == 0):
data.monsters.remove(monster)
def drawAll(canvas, data):
# Title text
canvas.create_text(data.width/2, 20, text='Creating Objects Demo!', font='Arial 26 bold')
canvas.create_text(data.width/2, 50, text='Click to create monsters', font='Arial 20 bold')
canvas.create_text(data.width/2, 80, text='Click on monsters to reduce strength', font='Arial 20 bold')
canvas.create_text(data.width/2, 110, text='Monsters with zero strength disappear', font='Arial 20 bold')
# Monsters
for monster in data.monsters:
canvas.create_oval(monster.cx-monster.r, monster.cy-monster.r,
monster.cx+monster.r, monster.cy+monster.r,
fill=monster.color)
canvas.create_text(monster.cx, monster.cy, text=monster.strength, font='Arial 20 bold')