Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14: Difference between revisions
(Created page with '{{Template:I18n/Language Navigation Bar|Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14}} {{TutorialBrowser| series=[[Development/Tutorials/Qt4_Ruby_Tutorial|Qt4 Ruby Tutoria...') |
No edit summary |
||
(7 intermediate revisions by 4 users not shown) | |||
Line 1: | Line 1: | ||
<languages /> | |||
pre=[[Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_13|Tutorial 13 - Game Over]] | {{<translate><!--T:1--> | ||
TutorialBrowser</translate>| | |||
series=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial|<translate><!--T:2--> | |||
Qt4 Ruby Tutorial</translate>]]| | |||
name=<translate><!--T:3--> | |||
Facing the Wall</translate>| | |||
pre=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_13|<translate><!--T:4--> | |||
Tutorial 13 - Game Over</translate>]] | |||
}} | }} | ||
== Facing the Wall == | <translate> | ||
== Facing the Wall == <!--T:5--> | |||
</translate> | |||
<translate> | |||
<!--T:6--> | |||
[[Image:Qt4_Ruby_Tutorial_Screenshot_14.png|center]] | [[Image:Qt4_Ruby_Tutorial_Screenshot_14.png|center]] | ||
</translate> | |||
<translate> | |||
<!--T:7--> | |||
Files: | Files: | ||
</translate> | |||
* [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/lcdrange.rb lcdrange.rb] | * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/lcdrange.rb lcdrange.rb] | ||
* [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/gamebrd.rb gamebrd.rb] | * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/gamebrd.rb gamebrd.rb] | ||
Line 16: | Line 28: | ||
* [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/cannon.rb cannon.rb] | * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/cannon.rb cannon.rb] | ||
=== Overview === | <translate> | ||
=== Overview === <!--T:8--> | |||
<!--T:9--> | |||
This is the final example: a complete game. | This is the final example: a complete game. | ||
We add keyboard accelerators and introduce mouse events to CannonField. We put a frame around the CannonField and add a barrier (wall) to make the game more challenging. | <!--T:10--> | ||
We add keyboard accelerators and introduce mouse events to '''<tt>CannonField</tt>'''. We put a frame around the '''<tt>CannonField</tt>''' and add a barrier (wall) to make the game more challenging. | |||
=== Line by Line Walkthrough === | === Line by Line Walkthrough === <!--T:11--> | ||
</translate> | |||
'''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/cannon.rb cannon.rb]''' | '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/cannon.rb cannon.rb]''' | ||
The CannonField can now receive mouse events to make the user aim the barrel by clicking on it and dragging. CannonField also has a barrier wall. | <translate> | ||
<!--T:12--> | |||
The '''<tt>CannonField</tt>''' can now receive mouse events to make the user aim the barrel by clicking on it and dragging. '''<tt>CannonField</tt>''' also has a barrier wall. | |||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
@barrelPressed = false | |||
</syntaxhighlight> | |||
<translate> | |||
<!--T:13--> | |||
This line has been added to the constructor. Initially, the mouse is not pressed on the barrel. | This line has been added to the constructor. Initially, the mouse is not pressed on the barrel. | ||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
elsif shotR.x() > width() || shotR.y() > height() || | |||
shotR.intersects(barrierRect()) | |||
</syntaxhighlight> | |||
Now that we have a barrier, there are three ways to miss. We test for the third, too. (In moveShot().) | <translate> | ||
<!--T:14--> | |||
Now that we have a barrier, there are three ways to miss. We test for the third, too. (In '''<tt>moveShot()</tt>'''.) | |||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
def mousePressEvent(event) | |||
unless event.button() == Qt::LeftButton | |||
return | |||
end | |||
if barrelHit(event.pos()) | |||
@barrelPressed = true | |||
end | end | ||
end | |||
</syntaxhighlight> | |||
<translate> | |||
<!--T:15--> | |||
This is a Qt event handler. It is called when the user presses a mouse button when the mouse cursor is over the widget. | This is a Qt event handler. It is called when the user presses a mouse button when the mouse cursor is over the widget. | ||
If the event was not generated by the left mouse button, we return immediately. Otherwise, we check if the position of the mouse cursor is within the cannon's barrel. If it is, we set barrelPressed to true. | <!--T:16--> | ||
If the event was not generated by the left mouse button, we return immediately. Otherwise, we check if the position of the mouse cursor is within the cannon's barrel. If it is, we set '''<tt>barrelPressed</tt>''' to true. | |||
Notice that the Qt::MouseEvent::pos() function returns a point in the widget's coordinate system. | <!--T:17--> | ||
Notice that the [http://doc.qt.nokia.com/latest/qmouseevent.html#pos Qt::MouseEvent::pos()] function returns a point in the widget's coordinate system. | |||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
def mouseMoveEvent(event) | |||
unless @barrelPressed | |||
return | |||
end | |||
pos = event.pos(); | |||
if pos.x() <= 0 | |||
pos.setX(1) | |||
end | |||
if pos.y() >= height() | |||
pos.setY(height() - 1) | |||
end | |||
rad = atan2((rect().bottom() - pos.y()), pos.x()) | |||
setAngle((rad * 180 / 3.14159265).round()) | |||
end | |||
</syntaxhighlight> | |||
This is another Qt event handler. It is called when the user already has pressed the mouse button inside this widget and then moves/drags the mouse. (You can make Qt send mouse move events even when no buttons are pressed. See Qt::Widget::setMouseTracking().) | <translate> | ||
<!--T:18--> | |||
This is another Qt event handler. It is called when the user already has pressed the mouse button inside this widget and then moves/drags the mouse. (You can make Qt send mouse move events even when no buttons are pressed. See [http://doc.qt.nokia.com/latest/qwidget.html#mouseTracking-prop Qt::Widget::setMouseTracking()].) | |||
<!--T:19--> | |||
This handler repositions the cannon's barrel according to the position of the mouse cursor. | This handler repositions the cannon's barrel according to the position of the mouse cursor. | ||
<!--T:20--> | |||
First, if the barrel is not pressed, we return. Next, we fetch the mouse cursor's position. If the mouse cursor is to the left or below the widget, we adjust the point to be inside the widget. | First, if the barrel is not pressed, we return. Next, we fetch the mouse cursor's position. If the mouse cursor is to the left or below the widget, we adjust the point to be inside the widget. | ||
<!--T:21--> | |||
Then we calculate the angle between the bottom edge of the widget and the imaginary line between the bottom-left corner of the widget and the cursor position. Finally we set the cannon's angle to the new value converted to degrees. | Then we calculate the angle between the bottom edge of the widget and the imaginary line between the bottom-left corner of the widget and the cursor position. Finally we set the cannon's angle to the new value converted to degrees. | ||
Remember that setAngle() redraws the cannon. | <!--T:22--> | ||
Remember that '''<tt>setAngle()</tt>''' redraws the cannon. | |||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
def mouseReleaseEvent(event) | |||
if event.button() == Qt::LeftButton | |||
@barrelPressed = false | |||
end | end | ||
end | |||
</syntaxhighlight> | |||
<translate> | |||
<!--T:23--> | |||
This Qt event handler is called whenever the user releases a mouse button and it was pressed inside this widget. | This Qt event handler is called whenever the user releases a mouse button and it was pressed inside this widget. | ||
<!--T:24--> | |||
If the left button is released, we can be sure that the barrel is no longer pressed. | If the left button is released, we can be sure that the barrel is no longer pressed. | ||
<!--T:25--> | |||
The paint event has one extra line: | The paint event has one extra line: | ||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
paintBarrier(painter) | |||
</syntaxhighlight> | |||
paintBarrier() does the same sort of thing as paintShot(), paintTarget(), and paintCannon(). | <translate> | ||
<!--T:26--> | |||
'''<tt>paintBarrier()</tt>''' does the same sort of thing as '''<tt>paintShot()</tt>''', '''<tt>paintTarget()</tt>''', and '''<tt>paintCannon()</tt>'''. | |||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
def paintBarrier( painter ) | |||
painter.setBrush(Qt::Brush.new(Qt::yellow)) | |||
painter.setPen(Qt::Color.new(Qt::black)) | |||
painter.drawRect(barrierRect()) | |||
end | |||
</syntaxhighlight> | |||
<translate> | |||
<!--T:27--> | |||
This function paints the barrier as a rectangle filled with yellow and with a black outline. | This function paints the barrier as a rectangle filled with yellow and with a black outline. | ||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
def barrierRect() | |||
return Qt::Rect.new(145, height() - 100, 15, 99) | |||
end | |||
</syntaxhighlight> | |||
<translate> | |||
<!--T:28--> | |||
This function returns the rectangle of the barrier. We fix the bottom edge of the barrier to the bottom edge of the widget. | This function returns the rectangle of the barrier. We fix the bottom edge of the barrier to the bottom edge of the widget. | ||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
def barrelHit(pos) | |||
matrix = Qt::Matrix.new() | |||
matrix.translate(0, height()) | |||
matrix.rotate(-@currentAngle) | |||
matrix = matrix.inverted() | |||
return @barrelRect.contains(matrix.map(pos)) | |||
end | |||
</syntaxhighlight> | |||
This function returns true if the point is in the barrel; otherwise it returns false. | <translate> | ||
<!--T:29--> | |||
This function returns '''<tt>true</tt>''' if the point is in the barrel; otherwise it returns '''<tt>false</tt>'''. | |||
Here we use the class Qt::Matrix. Qt::Matrix defines a coordinate system mapping. It can perform the same transformations as the Qt::Painter. | <!--T:30--> | ||
Here we use the class [http://doc.qt.nokia.com/latest/qmatrix.html Qt::Matrix]. [http://doc.qt.nokia.com/latest/qmatrix.html Qt::Matrix] defines a coordinate system mapping. It can perform the same transformations as the [http://doc.qt.nokia.com/latest/qpainter.html Qt::Painter]. | |||
Here we perform the same transformation steps as we do when drawing the barrel in the paintCannon() function. First we translate the coordinate system and then we rotate it. | <!--T:31--> | ||
Here we perform the same transformation steps as we do when drawing the barrel in the '''<tt>paintCannon()</tt>''' function. First we translate the coordinate system and then we rotate it. | |||
Now we need to check whether the point pos (in widget coordinates) lies inside the barrel. To do this, we invert the transformation matrix. The inverted matrix performs the inverse transformation that we used when drawing the barrel. We map the point pos using the inverted matrix and return true if it is inside the original barrel rectangle. | <!--T:32--> | ||
Now we need to check whether the point '''<tt>pos</tt>''' (in widget coordinates) lies inside the barrel. To do this, we invert the transformation matrix. The inverted matrix performs the inverse transformation that we used when drawing the barrel. We map the point '''<tt>pos</tt>''' using the inverted matrix and return '''<tt>true</tt>''' if it is inside the original barrel rectangle. | |||
</translate> | |||
'''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/gamebrd.rb gamebrd.rb]''' | '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t14/gamebrd.rb gamebrd.rb]''' | ||
<syntaxhighlight lang="ruby"> | |||
cannonBox = Qt::Frame.new() | |||
cannonBox.setFrameStyle(Qt::Frame::WinPanel | Qt::Frame::Sunken) | |||
</syntaxhighlight> | |||
We create and set up a Qt::Frame, and set its frame style. This results in a 3D frame around the CannonField. | <translate> | ||
<!--T:33--> | |||
We create and set up a [http://doc.qt.nokia.com/latest/qframe.html Qt::Frame], and set its frame style. This results in a 3D frame around the '''<tt>CannonField</tt>'''. | |||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
Qt::Shortcut.new(Qt::KeySequence.new(Qt::Key_Enter.to_i), | |||
self, SLOT('fire()')) | |||
Qt::Shortcut.new(Qt::KeySequence.new(Qt::Key_Return.to_i), | |||
self, SLOT('fire()')) | |||
Qt::Shortcut.new(Qt::KeySequence.new(Qt::CTRL.to_i + Qt::Key_Q.to_i), | |||
self, SLOT('close()')) | |||
</syntaxhighlight> | |||
Here we create and set up three Qt::Shortcut objects. These objects intercept keyboard events to a widget and call slots if certain keys are pressed. Note that a Qt::Shortcut object is a child of a widget and will be destroyed when that widget is destroyed. Qt::Shortcut itself is not a widget and has no visible effect on its parent. | <translate> | ||
<!--T:34--> | |||
Here we create and set up three [http://doc.qt.nokia.com/latest/qshortcut.html Qt::Shortcut] objects. These objects intercept keyboard events to a widget and call slots if certain keys are pressed. Note that a [http://doc.qt.nokia.com/latest/qshortcut.html Qt::Shortcut] object is a child of a widget and will be destroyed when that widget is destroyed. [http://doc.qt.nokia.com/latest/qshortcut.html Qt::Shortcut] itself is not a widget and has no visible effect on its parent. | |||
We define three shortcut keys. We want the fire() slot to be called when the user presses Enter or Return. We also want the application to quit when key Ctrl+Q is pressed. Instead of connecting to Qt::CoreApplication::quit(), we connect to Qt::Widget::close() this time. Since the GameBoard is the application's main widget, this has the same effect as QCoreApplication::quit(). | <!--T:35--> | ||
We define three shortcut keys. We want the '''<tt>fire()</tt>''' slot to be called when the user presses Enter or Return. We also want the application to quit when key Ctrl+Q is pressed. Instead of connecting to [http://doc.qt.nokia.com/latest/qcoreapplication.html#quit Qt::CoreApplication::quit()], we connect to [http://doc.qt.nokia.com/latest/qwidget.html#close Qt::Widget::close()] this time. Since the '''<tt>GameBoard</tt>''' is the application's main widget, this has the same effect as [http://doc.qt.nokia.com/latest/qcoreapplication.html#quit QCoreApplication::quit()]. | |||
<!--T:36--> | |||
Qt::CTRL, Qt::Key_Enter, Qt::Key_Return, and Qt::Key_Q are all constants declared in the Qt namespace. Unfortunately, in the current version of qtruby, they need to be converted to integers before we can use them in our shortcuts. | Qt::CTRL, Qt::Key_Enter, Qt::Key_Return, and Qt::Key_Q are all constants declared in the Qt namespace. Unfortunately, in the current version of qtruby, they need to be converted to integers before we can use them in our shortcuts. | ||
</translate> | |||
<syntaxhighlight lang="ruby"> | |||
leftLayout = Qt::VBoxLayout.new() | |||
leftLayout.addWidget(angle) | |||
leftLayout.addWidget(force) | |||
gridLayout = Qt::GridLayout.new() | |||
gridLayout.addWidget(quit, 0, 0) | |||
gridLayout.addLayout(topLayout, 0, 1) | |||
gridLayout.addLayout(leftLayout, 1, 0) | |||
gridLayout.addWidget(@cannonField, 1, 1, 2, 1) | |||
gridLayout.setColumnStretch(1, 10) | |||
setLayout(gridLayout) | |||
</syntaxhighlight> | |||
We give cannonBox its own Qt::VBoxLayout, and we add | <translate> | ||
<!--T:37--> | |||
We give '''<tt>cannonBox</tt>''' its own [http://doc.qt.nokia.com/latest/qvboxlayout.html Qt::VBoxLayout], and we add '''<tt>CannonField</tt>''' to that layout. This implicitly makes '''<tt>CannonField</tt>''' a child of '''<tt>cannonBox</tt>'''. Because nothing else is in the box, the effect is that the [http://doc.qt.nokia.com/latest/qvboxlayout.html Qt::VBoxLayout] will put a frame around the '''<tt>CannonField</tt>'''. We put '''<tt>cannonBox</tt>''', not '''<tt>CannonField</tt>''', in the grid layout. | |||
</translate> | |||
=== Running the Application === | <translate> | ||
=== Running the Application === <!--T:38--> | |||
=== Exercises === | <!--T:39--> | ||
The cannon now shoots when you press Enter. You can also position the cannon's angle using the mouse. The barrier makes it a little more challenging to play the game. We also have a nice looking frame around the '''<tt>CannonField</tt>'''. | |||
=== Exercises === <!--T:40--> | |||
<!--T:41--> | |||
Write a space invaders game. | Write a space invaders game. | ||
<!--T:42--> | |||
The new exercise is: Write a Breakout game. | The new exercise is: Write a Breakout game. | ||
<!--T:43--> | |||
Final exhortation: Go forth now and create masterpieces of the programming art! | Final exhortation: Go forth now and create masterpieces of the programming art! | ||
<!--T:44--> | |||
[[Category:Ruby]] | |||
</translate> |
Latest revision as of 14:26, 18 July 2012
Tutorial Series | Qt4 Ruby Tutorial |
Previous | Tutorial 13 - Game Over |
What's Next | n/a |
Further Reading | n/a |
Facing the Wall
Files:
Overview
This is the final example: a complete game.
We add keyboard accelerators and introduce mouse events to CannonField. We put a frame around the CannonField and add a barrier (wall) to make the game more challenging.
Line by Line Walkthrough
The CannonField can now receive mouse events to make the user aim the barrel by clicking on it and dragging. CannonField also has a barrier wall.
@barrelPressed = false
This line has been added to the constructor. Initially, the mouse is not pressed on the barrel.
elsif shotR.x() > width() || shotR.y() > height() ||
shotR.intersects(barrierRect())
Now that we have a barrier, there are three ways to miss. We test for the third, too. (In moveShot().)
def mousePressEvent(event)
unless event.button() == Qt::LeftButton
return
end
if barrelHit(event.pos())
@barrelPressed = true
end
end
This is a Qt event handler. It is called when the user presses a mouse button when the mouse cursor is over the widget.
If the event was not generated by the left mouse button, we return immediately. Otherwise, we check if the position of the mouse cursor is within the cannon's barrel. If it is, we set barrelPressed to true.
Notice that the Qt::MouseEvent::pos() function returns a point in the widget's coordinate system.
def mouseMoveEvent(event)
unless @barrelPressed
return
end
pos = event.pos();
if pos.x() <= 0
pos.setX(1)
end
if pos.y() >= height()
pos.setY(height() - 1)
end
rad = atan2((rect().bottom() - pos.y()), pos.x())
setAngle((rad * 180 / 3.14159265).round())
end
This is another Qt event handler. It is called when the user already has pressed the mouse button inside this widget and then moves/drags the mouse. (You can make Qt send mouse move events even when no buttons are pressed. See Qt::Widget::setMouseTracking().)
This handler repositions the cannon's barrel according to the position of the mouse cursor.
First, if the barrel is not pressed, we return. Next, we fetch the mouse cursor's position. If the mouse cursor is to the left or below the widget, we adjust the point to be inside the widget.
Then we calculate the angle between the bottom edge of the widget and the imaginary line between the bottom-left corner of the widget and the cursor position. Finally we set the cannon's angle to the new value converted to degrees.
Remember that setAngle() redraws the cannon.
def mouseReleaseEvent(event)
if event.button() == Qt::LeftButton
@barrelPressed = false
end
end
This Qt event handler is called whenever the user releases a mouse button and it was pressed inside this widget.
If the left button is released, we can be sure that the barrel is no longer pressed.
The paint event has one extra line:
paintBarrier(painter)
paintBarrier() does the same sort of thing as paintShot(), paintTarget(), and paintCannon().
def paintBarrier( painter )
painter.setBrush(Qt::Brush.new(Qt::yellow))
painter.setPen(Qt::Color.new(Qt::black))
painter.drawRect(barrierRect())
end
This function paints the barrier as a rectangle filled with yellow and with a black outline.
def barrierRect()
return Qt::Rect.new(145, height() - 100, 15, 99)
end
This function returns the rectangle of the barrier. We fix the bottom edge of the barrier to the bottom edge of the widget.
def barrelHit(pos)
matrix = Qt::Matrix.new()
matrix.translate(0, height())
matrix.rotate(-@currentAngle)
matrix = matrix.inverted()
return @barrelRect.contains(matrix.map(pos))
end
This function returns true if the point is in the barrel; otherwise it returns false.
Here we use the class Qt::Matrix. Qt::Matrix defines a coordinate system mapping. It can perform the same transformations as the Qt::Painter.
Here we perform the same transformation steps as we do when drawing the barrel in the paintCannon() function. First we translate the coordinate system and then we rotate it.
Now we need to check whether the point pos (in widget coordinates) lies inside the barrel. To do this, we invert the transformation matrix. The inverted matrix performs the inverse transformation that we used when drawing the barrel. We map the point pos using the inverted matrix and return true if it is inside the original barrel rectangle.
cannonBox = Qt::Frame.new()
cannonBox.setFrameStyle(Qt::Frame::WinPanel | Qt::Frame::Sunken)
We create and set up a Qt::Frame, and set its frame style. This results in a 3D frame around the CannonField.
Qt::Shortcut.new(Qt::KeySequence.new(Qt::Key_Enter.to_i),
self, SLOT('fire()'))
Qt::Shortcut.new(Qt::KeySequence.new(Qt::Key_Return.to_i),
self, SLOT('fire()'))
Qt::Shortcut.new(Qt::KeySequence.new(Qt::CTRL.to_i + Qt::Key_Q.to_i),
self, SLOT('close()'))
Here we create and set up three Qt::Shortcut objects. These objects intercept keyboard events to a widget and call slots if certain keys are pressed. Note that a Qt::Shortcut object is a child of a widget and will be destroyed when that widget is destroyed. Qt::Shortcut itself is not a widget and has no visible effect on its parent.
We define three shortcut keys. We want the fire() slot to be called when the user presses Enter or Return. We also want the application to quit when key Ctrl+Q is pressed. Instead of connecting to Qt::CoreApplication::quit(), we connect to Qt::Widget::close() this time. Since the GameBoard is the application's main widget, this has the same effect as QCoreApplication::quit().
Qt::CTRL, Qt::Key_Enter, Qt::Key_Return, and Qt::Key_Q are all constants declared in the Qt namespace. Unfortunately, in the current version of qtruby, they need to be converted to integers before we can use them in our shortcuts.
leftLayout = Qt::VBoxLayout.new()
leftLayout.addWidget(angle)
leftLayout.addWidget(force)
gridLayout = Qt::GridLayout.new()
gridLayout.addWidget(quit, 0, 0)
gridLayout.addLayout(topLayout, 0, 1)
gridLayout.addLayout(leftLayout, 1, 0)
gridLayout.addWidget(@cannonField, 1, 1, 2, 1)
gridLayout.setColumnStretch(1, 10)
setLayout(gridLayout)
We give cannonBox its own Qt::VBoxLayout, and we add CannonField to that layout. This implicitly makes CannonField a child of cannonBox. Because nothing else is in the box, the effect is that the Qt::VBoxLayout will put a frame around the CannonField. We put cannonBox, not CannonField, in the grid layout.
Running the Application
The cannon now shoots when you press Enter. You can also position the cannon's angle using the mouse. The barrier makes it a little more challenging to play the game. We also have a nice looking frame around the CannonField.
Exercises
Write a space invaders game.
The new exercise is: Write a Breakout game.
Final exhortation: Go forth now and create masterpieces of the programming art!