I am trying to create an object oriented program in Python for a whac-a-mole program.
I want to keep this simple where there are just a hammer and a mole and when the hammer turtle makes contact with the mole turtle.
I have created 4 classes, one for Game which is the super class, one for sprite which inherits from Turtle and one each for hammer and mole which both inherit from Sprite.
What I am asking is how to instantiate the mole and hammer turtles I have made use of inheritance but want to minimize the amount of methods I am using:
import random
import turtle
wn=turtle.Screen()
wn.addshape("moleSmall.gif")
wn.addshape("Mole.gif")
wn.addshape("Hammer.gif")
turtle.setup(800, 600)
class Game():
def __init__(self):
self.score=0
self.pointsDisplay=Points()
def update_score(self,x,y):
self.score = self.score + 2
print("Score:", self.score)
self.callDisplayScore()
def decrease_score(self,x,y):
self.score = self.score -1
print("Score: ", self.score)
self.callDisplayScore()
def callDisplayScore(self):
score = self.score
class Sprite(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.x=0
self.y=0
crash =False
self.crash=crash
def randomMove(self):
leftbound = -self.wn.window_width()/2
rightbound = self.wn.window_width()/2
topbound = self.wn.window_height()/2
bottombound = -self.wn.window_height()/2
rand_x = random.randint(leftbound , rightbound)
rand_y = random.randint(bottombound, topbound)
self.mole.setpos(rand_x,rand_y)
def collisionCheck(self,turtle1, turtle2):
self.crash = False
turtle1X = turtle1.xcor()
turtle1Y = turtle1.ycor()
turtle2X = turtle2.xcor()
turtle2Y = turtle2.ycor()
turtle1Pos = (int(turtle1X), int(turtle1Y))
turtle2Pos = (int(turtle2X), int(turtle2Y))
if turtle1Pos == turtle2Pos or turtle1X < turtle2X - 50 and \
turtle1Y > turtle2Y - 50 and turtle1X < turtle2X - 50 and\
turtle1Y > turtle2Y + 50:
self.crash = True
return self.crash
class Mole(Sprite):
def __init__(self):
Sprite.__init__(self)
self.mole.pu()
self.mole.shape("moleSmall.gif")
self.x= self.mole.xcor()
self.y = self.mole.ycor()
self.randomMove()
class Hammer(Sprite):
def __init__(self):
Sprite.__init__(self)
self.counter = 0
self.hammer.penup()
self.hammer.shape("Hammer.gif")
self.hammer.penup()
leftbound = -self.wn.window_width()/2
rightbound = self.wn.window_width()/2
topbound = self.wn.window_height()/2
bottombound = -self.wn.window_height()/2
rand_x = random.randint(leftbound , rightbound)
rand_y = random.randint(bottombound, topbound)
self.hammer.setpos(rand_x,rand_y)
def HammerMove(self):
self.hammer.pu()
self.hammer.clear()
self.wn.onscreenclick(self.hammer.goto)
while self.collisionCheck(self.mole, self.hammer) == False:
self.randomMove()
if self.collisionCheck(self.mole, self.hammer) == True:
self.score = self.score + 1
print(self.score)
from module import *
to prevent clutter from theturtle.Screen()
andturtle.setup()
\$\endgroup\$import turtle as tl
if you really want to save on typing. \$\endgroup\$