Менял атрибуты класса робота, не получалось достичь желаемого (изменение поведения), пока пришлось использовать два одинаковых класса робота
#!/usr/bin/python
# -*- coding: utf-8 -*-
# python2.7
#------------------------------------------------
import sys
from PyQt4 import QtCore, QtGui, uic
from output import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import random
slova = [u'виселица',u'смартфон',u'маргарин',u'мегагерц',u'страница',u'креветка',u'микрофон',u'квартира',u'скорость',u'художник',u'жидкость',u'карантин',u'интернет',u'документ',u'мембрана',u'радиация',u'мавзолей',u'терминал',u'водитель']
class Proba(QMainWindow, Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
self.robot = Robot()
self.robot.scale(1.2, 1.2)
self.robot.setPos(0, 0)
self.robotK = RobotK()
self.robotK.scale(1.2, 1.2)
self.robotK.setPos(0, -70)
self.scene = QtGui.QGraphicsScene()
self.scene_view = QtGui.QGraphicsView(self.scene, self)
self.scene_view.resize(300, 350)
self.scene_view.move(40, 50)
self.item = QtGui.QGraphicsEllipseItem(-18, -120, 40, 50)
self.line = QtGui.QGraphicsLineItem(-150, -200, 100, -200)
self.line2 = QtGui.QGraphicsLineItem(-150, -200, -150, 100)
self.line3 = QtGui.QGraphicsLineItem(-70, -200, -150, -100)
self.line4 = QtGui.QGraphicsLineItem(0, -120, 0, -200)
self.line5 = QtGui.QGraphicsLineItem(0, -200, 0, -100)
self.win = 0
self.defeat = 0
self.win2 = 0
self.defeat2 = 0
self.wo = None
self.wor = []
self.clear.clicked.connect(self.clear_Click) # Обработка нажатия на кнопку очистить
self.help.clicked.connect(self.help_Click) # Обработка нажатия на кнопку помощь
self.start.clicked.connect(self.start_Click) # Обработка нажатия на кнопку старт
self.connect(self.pushButton_b, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_z, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_i, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_j, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_a, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_d, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_e, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_g, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_v, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_e2, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_i2, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_k, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_l, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_m, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_n, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_o, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_p, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_r, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_s, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_t, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_y, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_ph, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_x, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_cs, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_h, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_hsh, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_hc, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_33, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_34, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_35, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_36, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_37, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
self.connect(self.pushButton_38, QtCore.SIGNAL("clicked()"), self.on_button_clicked)
def on_button_clicked(self):
tokens = (self.lineEdit_2, self.lineEdit_3, self.lineEdit_4,
self.lineEdit_5, self.lineEdit_6, self.lineEdit_7)
button = self.sender()
u = button.text()
print self.wo
if unicode(u) in self.wor:
key_ = self.wor.index(unicode(u))
self.wor[key_] = '1'
out = tokens[int(key_)]
out.setProperty('text', unicode(u))
self.win = self.win + 1
if self.win == 6:
try:
self.scene.removeItem(self.line)
except: pass
try:
self.scene.removeItem(self.line2)
except: pass
try:
self.scene.removeItem(self.line3)
except: pass
try:
self.scene.removeItem(self.line4)
except: pass
try:
self.scene.removeItem(self.line5)
except: pass
try:
self.scene.removeItem(self.item)
except: pass
else:
self.defeat = self.defeat + 1
print self.defeat
men = (self.line,self.line2,self.line3,self.line4)
try:
sj = men[self.defeat-1]
self.scene.addItem(sj)
except: pass
if self.defeat == 5:
self.scene.addItem(self.item)
if self.defeat == 6:
self.scene.removeItem(self.robot)
#self.scene.clear()
self.scene.removeItem(self.item)
self.scene.addItem(self.line5)
self.scene.addItem(self.robotK)
if unicode(u) in self.wor:
try:
key_2 = self.wor.index(unicode(u))
self.wor[key_2] = '1'
print key_2
out = tokens[int(key_2)]
out.setProperty('text', unicode(u))
self.win = self.win + 1
except: pass
if unicode(u) in self.wor:
try:
key_3 = self.wor.index(unicode(u))
self.wor[key_3] = '1'
print key_3
out = tokens[int(key_3)]
out.setProperty('text', unicode(u))
self.win = self.win + 1
except: pass
if self.win == 6:
self.win2 = self.win2 + 1
self.lcdNumber.setProperty("intValue", self.win2)
if self.defeat == 6:
self.defeat2 = self.defeat2 + 1
self.lcdNumber_2.setProperty("intValue", self.defeat2)
return self.defeat
def clear_Click (self):
self.lcdNumber.setProperty("intValue", 0)
self.lcdNumber_2.setProperty("intValue", 0)
print u"Очистить"
def help_Click (self):
print u"Помощь"
msgBox = QtGui.QMessageBox()
msgBox.setText(u'''
Принцип игры
Андроид загадывает слово — пишет на бумаге
первую и последнюю букву слова и отмечает
места для остальных букв, например чертами .
Игрок предлагает букву, которая может входить
в это слово.Если такая буква есть в слове,
то Андроид пишет её над соответствующими этой
букве чертами — столько раз, сколько она
встречается в слове.Если такой буквы нет, то
рисуется часть виселицы. Игрок продолжает
отгадывать буквы до тех пор,пока не
отгадает всё слово. За каждый
неправильный ответ Андроид добавляет одну часть
к виселице(их 5, и шестая ошибка фатальная).
Если виселица нарисована
полностью, то отгадывающий игрок проигрывает,
считается повешенным.
Если игроку удаётся угадать слово, он выигрывает.
''')
ret = msgBox.exec_();
def start_Click (self):
self.scene.removeItem(self.robotK)
self.scene.removeItem(self.line)
self.scene.removeItem(self.line2)
self.scene.removeItem(self.line3)
self.scene.removeItem(self.line4)
self.scene.removeItem(self.line5)
self.scene.addItem(self.robot)
self.wo = None
self.wor = []
self.win = 0
self.defeat = 0
self.lineEdit_2.setProperty('text', '')
self.lineEdit_3.setProperty('text', '')
self.lineEdit_4.setProperty('text', '')
self.lineEdit_5.setProperty('text', '')
self.lineEdit_6.setProperty('text', '')
self.lineEdit_7.setProperty('text', '')
self.word = random.choice(slova) # выбираем рандомно слово
self.wo = self.word[1:-1] # отрезаем от слова первую и последнюю букву
for i in self.wo:
self.wor.append(i)
f1 = self.word[0]
f2 = self.word[-1]
self.lineEdit.setProperty('text', f1)
self.lineEdit_8.setProperty('text', f2)
#############################################################
# первый робот
class RobotPart(QtGui.QGraphicsItem):
def __init__(self, parent=None):
super(RobotPart, self).__init__(parent)
self.color = QtGui.QColor(QtCore.Qt.lightGray)
self.pixmap = None
self.dragOver = False
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasColor() or \
(isinstance(self, RobotHead) and event.mimeData().hasImage()):
event.setAccepted(True)
self.dragOver = True
self.update()
else:
event.setAccepted(False)
def dragLeaveEvent(self, event):
self.dragOver = False
self.update()
def dropEvent(self, event):
self.dragOver = False
if event.mimeData().hasColor():
self.color = QtGui.QColor(event.mimeData().colorData())
elif event.mimeData().hasImage():
self.pixmap = QtGui.QPixmap(event.mimeData().imageData())
self.update()
class RobotHead(RobotPart):
def boundingRect(self):
return QtCore.QRectF(-15, -50, 30, 50)
def paint(self, painter, option, widget=None):
if not self.pixmap:
painter.setBrush(self.dragOver and self.color.light(130)
or self.color)
painter.drawRoundedRect(-10, -30, 20, 30, 25, 25,
QtCore.Qt.RelativeSize)
painter.setBrush(QtCore.Qt.white)
painter.drawEllipse(-7, -3 - 20, 7, 7)
painter.drawEllipse(0, -3 - 20, 7, 7)
painter.setBrush(QtCore.Qt.black)
painter.drawEllipse(-5, -1 - 20, 2, 2)
painter.drawEllipse(2, -1 - 20, 2, 2)
painter.setPen(QtGui.QPen(QtCore.Qt.black, 2))
painter.setBrush(QtCore.Qt.NoBrush)
painter.drawArc(-6, -2 - 20, 12, 15, 190 * 16, 160 * 16)
else:
painter.scale(.2272, .2824)
painter.drawPixmap(QtCore.QPointF(-15*4.4, -50*3.54), self.pixmap)
class RobotTorso(RobotPart):
def boundingRect(self):
return QtCore.QRectF(-30, -20, 60, 60)
def paint(self, painter, option, widget=None):
painter.setBrush(self.dragOver and self.color.light(130)
or self.color)
painter.drawRoundedRect(-20, -20, 40, 60, 25, 25,
QtCore.Qt.RelativeSize)
painter.drawEllipse(-25, -20, 20, 20)
painter.drawEllipse(5, -20, 20, 20)
painter.drawEllipse(-20, 22, 20, 20)
painter.drawEllipse(0, 22, 20, 20)
class RobotLimb(RobotPart):
def boundingRect(self):
return QtCore.QRectF(-5, -5, 40, 10)
def paint(self, painter, option, widget=None):
painter.setBrush(self.dragOver and self.color.light(130) or self.color)
painter.drawRoundedRect(self.boundingRect(), 50, 50,
QtCore.Qt.RelativeSize)
painter.drawEllipse(-5, -5, 10, 10)
class Robot(RobotPart):
def __init__(self):
super(Robot, self).__init__()
self.torsoItem = RobotTorso(self)
self.headItem = RobotHead(self.torsoItem)
self.upperLeftArmItem = RobotLimb(self.torsoItem)
self.lowerLeftArmItem = RobotLimb(self.upperLeftArmItem)
self.upperRightArmItem = RobotLimb(self.torsoItem)
self.lowerRightArmItem = RobotLimb(self.upperRightArmItem)
self.upperRightLegItem = RobotLimb(self.torsoItem)
self.lowerRightLegItem = RobotLimb(self.upperRightLegItem)
self.upperLeftLegItem = RobotLimb(self.torsoItem)
self.lowerLeftLegItem = RobotLimb(self.upperLeftLegItem)
self.timeline = QtCore.QTimeLine()
self.settings = [
# item position rotation at
# x y time 0 / 1
( self.headItem, 0, -18, 20, -20 ),
( self.upperLeftArmItem, -15, -10, 190, 180 ),
( self.lowerLeftArmItem, 30, 0, 50, 10 ),
( self.upperRightArmItem, 15, -10, 300, 310 ),
( self.lowerRightArmItem, 30, 0, 0, -70 ),
( self.upperRightLegItem, 10, 32, 40, 120 ),
( self.lowerRightLegItem, 30, 0, 10, 50 ),
( self.upperLeftLegItem, -10, 32, 150, 80 ),
( self.lowerLeftLegItem, 30, 0, 70, 10 ),
( self.torsoItem, 0, 0, 5, -20 )
]
self.animations = []
for item, pos_x, pos_y, rotation1, rotation2 in self.settings:
item.setPos(pos_x,pos_y)
animation = QtGui.QGraphicsItemAnimation()
animation.setItem(item)
animation.setTimeLine(self.timeline)
animation.setRotationAt(0, rotation1)
animation.setRotationAt(1, rotation2)
self.animations.append(animation)
self.animations[0].setScaleAt(1, 1.1, 1.1)
self.timeline.setUpdateInterval(1000 / 25)
self.timeline.setCurveShape(QtCore.QTimeLine.SineCurve)
self.timeline.setLoopCount(0)
self.timeline.setDuration(2000)
self.timeline.start()
def boundingRect(self):
return QtCore.QRectF()
def paint(self, painter, option, widget=None):
pass
#############################################################
#второй робот
class RobotPart2(QtGui.QGraphicsItem):
def __init__(self, parent=None):
super(RobotPart2, self).__init__(parent)
self.color = QtGui.QColor(QtCore.Qt.lightGray)
self.pixmap = None
self.dragOver = False
self.setAcceptDrops(True)
def dragEnterEvent2(self, event):
if event.mimeData().hasColor() or \
(isinstance(self, RobotHead) and event.mimeData().hasImage()):
event.setAccepted(True)
self.dragOver = True
self.update()
else:
event.setAccepted(False)
def dragLeaveEvent2(self, event):
self.dragOver = False
self.update()
def dropEvent2(self, event):
self.dragOver = False
if event.mimeData().hasColor():
self.color = QtGui.QColor(event.mimeData().colorData())
elif event.mimeData().hasImage():
self.pixmap = QtGui.QPixmap(event.mimeData().imageData())
self.update()
class RobotHead2(RobotPart2):
def boundingRect(self):
return QtCore.QRectF(-15, -50, 30, 50)
def paint(self, painter, option, widget=None):
if not self.pixmap:
painter.setBrush(self.dragOver and self.color.light(130)
or self.color)
painter.drawRoundedRect(-10, -30, 20, 30, 25, 25,
QtCore.Qt.RelativeSize)
painter.setBrush(QtCore.Qt.white)
painter.drawEllipse(-7, -3 - 20, 7, 7)
painter.drawEllipse(0, -3 - 20, 7, 7)
painter.setBrush(QtCore.Qt.black)
painter.drawEllipse(-5, -1 - 20, 2, 2)
painter.drawEllipse(2, -1 - 20, 2, 2)
painter.setPen(QtGui.QPen(QtCore.Qt.black, 2))
painter.setBrush(QtCore.Qt.NoBrush)
painter.drawArc(-6, -2 - 10, 12, 15, 190 / 16, 160 * 16)
else:
painter.scale(.2272, .2824)
painter.drawPixmap(QtCore.QPointF(-15*4.4, -50*3.54), self.pixmap)
class RobotTorso2(RobotPart2):
def boundingRect(self):
return QtCore.QRectF(-30, -20, 60, 60)
def paint(self, painter, option, widget=None):
painter.setBrush(self.dragOver and self.color.light(130)
or self.color)
painter.drawRoundedRect(-20, -20, 40, 60, 25, 25,
QtCore.Qt.RelativeSize)
painter.drawEllipse(-25, -20, 20, 20)
painter.drawEllipse(5, -20, 20, 20)
painter.drawEllipse(-20, 22, 20, 20)
painter.drawEllipse(0, 22, 20, 20)
class RobotLimb2(RobotPart2):
def boundingRect(self):
return QtCore.QRectF(-5, -5, 40, 10)
def paint(self, painter, option, widget=None):
painter.setBrush(self.dragOver and self.color.light(130) or self.color)
painter.drawRoundedRect(self.boundingRect(), 50, 50,
QtCore.Qt.RelativeSize)
painter.drawEllipse(-5, -5, 10, 10)
class RobotK(RobotPart2):
def __init__(self):
super(RobotK, self).__init__()
self.torsoItem = RobotTorso2(self)
self.headItem = RobotHead2(self.torsoItem)
self.upperLeftArmItem = RobotLimb2(self.torsoItem)
self.lowerLeftArmItem = RobotLimb2(self.upperLeftArmItem)
self.upperRightArmItem = RobotLimb2(self.torsoItem)
self.lowerRightArmItem = RobotLimb2(self.upperRightArmItem)
self.upperRightLegItem = RobotLimb2(self.torsoItem)
self.lowerRightLegItem = RobotLimb2(self.upperRightLegItem)
self.upperLeftLegItem = RobotLimb2(self.torsoItem)
self.lowerLeftLegItem = RobotLimb2(self.upperLeftLegItem)
self.timeline = QtCore.QTimeLine()
settings = [
# item position rotation at
# x y time 0 / 1
( self.headItem, 0, -18, 20, -20 ),
( self.upperLeftArmItem, -15, -10, 190, 80 ),
( self.lowerLeftArmItem, 30, 0, -50, 10 ),
( self.upperRightArmItem, 15, -10, 500, 410 ),
( self.lowerRightArmItem, 30, 0, -10, 70 ),
( self.upperRightLegItem, 10, 32, 40, 120 ),
( self.lowerRightLegItem, 30, 0, 10, 50 ),
( self.upperLeftLegItem, -10, 32, 100, 80 ),
( self.lowerLeftLegItem, 30, 0, 70, 10 ),
( self.torsoItem, 0, 0, 5, -20 )
]
self.animations = []
for item, pos_x, pos_y, rotation1, rotation2 in settings:
item.setPos(pos_x,pos_y)
animation = QtGui.QGraphicsItemAnimation()
animation.setItem(item)
animation.setTimeLine(self.timeline)
animation.setRotationAt(0, rotation1)
animation.setRotationAt(1, rotation2)
self.animations.append(animation)
self.animations[0].setScaleAt(1, 1.1, 1.1)
self.timeline.setUpdateInterval(1000 / 25)
self.timeline.setCurveShape(QtCore.QTimeLine.SineCurve)
self.timeline.setLoopCount(0)
self.timeline.setDuration(2000)
self.timeline.start()
def boundingRect(self):
return QtCore.QRectF()
def paint(self, painter, option, widget=None):
pass
app = QtGui.QApplication(sys.argv)
w = Proba()
w.show()
sys.exit(app.exec_())