我正在尝试用Python创建一个面向对象的程序,用于打击鼹鼠程序。
我想保持这个简单,只有锤子和鼹鼠,当锤龟与鼹鼠龟接触。
我为Game创建了4个类,一个是超类,一个是从Turtle继承的精灵,另一个是锤子和鼹鼠,它们都是从Sprite继承的。
我要问的是如何实例化我使用遗传的鼹鼠和锤子龟但是想尽量减少我使用的方法的数量 我使用的代码是
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)