Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11: Difference between revisions

    From KDE TechBase
    m (Text replace - "</code>" to "</syntaxhighlight>")
    No edit summary
     
    (2 intermediate revisions by 2 users not shown)
    Line 1: Line 1:
    {{Template:I18n/Language Navigation Bar|Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11}}
    <languages />


    {{TutorialBrowser|


    series=[[Development/Tutorials/Qt4_Ruby_Tutorial|Qt4 Ruby Tutorial]]|


    name=Giving It a Shot|
    {{<translate><!--T:1-->
     
    TutorialBrowser</translate>|
    pre=[[Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_10|Tutorial 10 - Smooth as Silk]]|
    series=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial|<translate><!--T:2-->
     
    Qt4 Ruby Tutorial</translate>]]|
    next=[[Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_12|Tutorial 12 - Hanging in the Air the Way Bricks Don't]]
    name=<translate><!--T:3-->
    Giving It a Shot</translate>|
    pre=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_10|<translate><!--T:4-->
    Tutorial 10 - Smooth as Silk</translate>]]|
    next=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_12|<translate><!--T:5-->
    Tutorial 12 - Hanging in the Air the Way Bricks Don't</translate>]]
    }}
    }}
    == Giving It a Shot ==
    <translate>
    == Giving It a Shot == <!--T:6-->
    </translate>
    <translate>
    <!--T:7-->
    [[Image:Qt4_Ruby_Tutorial_Screenshot_11.png|center]]
    [[Image:Qt4_Ruby_Tutorial_Screenshot_11.png|center]]
    </translate>
    <translate>
    <!--T:8-->
    Files:
    Files:
    </translate>
    * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/lcdrange.rb lcdrange.rb]
    * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/lcdrange.rb lcdrange.rb]
    * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/t11.rb t11.rb]
    * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/t11.rb t11.rb]
    * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/cannon.rb cannon.rb]
    * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/cannon.rb cannon.rb]


    === Overview ===
    <translate>
    === Overview === <!--T:9-->
     
    <!--T:10-->
    In this example we introduce a timer to implement animated shooting.  
    In this example we introduce a timer to implement animated shooting.  


    === Line by Line Walkthrough ===
    === Line by Line Walkthrough === <!--T:11-->
    </translate>
    '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/cannon.rb cannon.rb]'''
    '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/cannon.rb cannon.rb]'''


    <translate>
    <!--T:12-->
    The '''<tt>CannonField</tt>''' now has shooting capabilities.
    The '''<tt>CannonField</tt>''' now has shooting capabilities.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 30: Line 48:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:13-->
    We include '''<tt>Math</tt>''' because we need the '''<tt>sin()</tt>''' and '''<tt>cos()</tt>''' functions.
    We include '''<tt>Math</tt>''' because we need the '''<tt>sin()</tt>''' and '''<tt>cos()</tt>''' functions.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 43: Line 64:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:14-->
    We initialize our new private variables and connect the [http://doc.qt.nokia.com/latest/qtimer.html#timeout Qt::Timer::timeout()] signal to our '''<tt>moveShot()</tt>''' slot. We'll move the shot every time the timer times out.
    We initialize our new private variables and connect the [http://doc.qt.nokia.com/latest/qtimer.html#timeout Qt::Timer::timeout()] signal to our '''<tt>moveShot()</tt>''' slot. We'll move the shot every time the timer times out.


    <!--T:15-->
    The '''<tt>timerCount</tt>''' keeps track of the time passed since the shot was fired. The '''<tt>shootAngle</tt>''' is the cannon angle and '''<tt>shootForce</tt>''' is the cannon force when the shot was fired.
    The '''<tt>timerCount</tt>''' keeps track of the time passed since the shot was fired. The '''<tt>shootAngle</tt>''' is the cannon angle and '''<tt>shootForce</tt>''' is the cannon force when the shot was fired.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 60: Line 85:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:16-->
    This function shoots a shot unless a shot is in the air. The '''<tt>timerCount</tt>''' is reset to zero. The '''<tt>shootAngle</tt>''' and '''<tt>shootForce</tt>''' variables are set to the current cannon angle and force. Finally, we start the timer.
    This function shoots a shot unless a shot is in the air. The '''<tt>timerCount</tt>''' is reset to zero. The '''<tt>shootAngle</tt>''' and '''<tt>shootForce</tt>''' variables are set to the current cannon angle and force. Finally, we start the timer.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 78: Line 106:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:17-->
    '''<tt>moveShot()</tt>''' is the slot that moves the shot, called every 5 milliseconds when the [http://doc.qt.nokia.com/latest/qtimer.html Qt::Timer] fires.
    '''<tt>moveShot()</tt>''' is the slot that moves the shot, called every 5 milliseconds when the [http://doc.qt.nokia.com/latest/qtimer.html Qt::Timer] fires.


    <!--T:18-->
    Its tasks are to compute the new position, update the screen with the shot in the new position, and if necessary, stop the timer.
    Its tasks are to compute the new position, update the screen with the shot in the new position, and if necessary, stop the timer.


    <!--T:19-->
    First we make a [http://doc.qt.nokia.com/latest/qregion.html Qt::Region] that holds the old '''<tt>shotRect()</tt>'''. A [http://doc.qt.nokia.com/latest/qregion.html Qt::Region] is capable of holding any sort of region, and we'll use it here to simplify the painting. '''<tt>shotRect()</tt>''' returns the rectangle where the shot is now. It is explained in detail later.
    First we make a [http://doc.qt.nokia.com/latest/qregion.html Qt::Region] that holds the old '''<tt>shotRect()</tt>'''. A [http://doc.qt.nokia.com/latest/qregion.html Qt::Region] is capable of holding any sort of region, and we'll use it here to simplify the painting. '''<tt>shotRect()</tt>''' returns the rectangle where the shot is now. It is explained in detail later.


    <!--T:20-->
    Then we increment the '''<tt>timerCount</tt>''', which has the effect of moving the shot one step along its trajectory.
    Then we increment the '''<tt>timerCount</tt>''', which has the effect of moving the shot one step along its trajectory.


    <!--T:21-->
    Next we fetch the new shot rectangle.
    Next we fetch the new shot rectangle.


    <!--T:22-->
    If the shot has moved beyond the right or bottom edge of the widget we stop the timer, or we add the new '''<tt>shotRect()</tt>''' to the [http://doc.qt.nokia.com/latest/qregion.html Qt::Region].
    If the shot has moved beyond the right or bottom edge of the widget we stop the timer, or we add the new '''<tt>shotRect()</tt>''' to the [http://doc.qt.nokia.com/latest/qregion.html Qt::Region].


    <!--T:23-->
    Finally, we repaint the [http://doc.qt.nokia.com/latest/qregion.html Qt::Region]. This will send a single paint event for just the one or two rectangles that need updating.
    Finally, we repaint the [http://doc.qt.nokia.com/latest/qregion.html Qt::Region]. This will send a single paint event for just the one or two rectangles that need updating.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 105: Line 142:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:24-->
    The paint event function has been simplified since the previous chapter. Most of the logic has been moved to the new '''<tt>paintShot()</tt>''' and '''<tt>paintCannon()</tt>''' functions.
    The paint event function has been simplified since the previous chapter. Most of the logic has been moved to the new '''<tt>paintShot()</tt>''' and '''<tt>paintCannon()</tt>''' functions.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 115: Line 155:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:25-->
    This private function paints the shot by drawing a black filled rectangle.
    This private function paints the shot by drawing a black filled rectangle.


    <!--T:26-->
    We leave out the implementation of '''<tt>paintCannon()</tt>'''; it is the same as the [http://doc.qt.nokia.com/latest/qwidget.html#paintEvent Qt::Widget::paintEvent()] reimplementation from the previous chapter.
    We leave out the implementation of '''<tt>paintCannon()</tt>'''; it is the same as the [http://doc.qt.nokia.com/latest/qwidget.html#paintEvent Qt::Widget::paintEvent()] reimplementation from the previous chapter.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 140: Line 184:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:27-->
    This private function calculates the center point of the shot and returns the enclosing rectangle of the shot. It uses the initial cannon force and angle in addition to '''<tt>timerCount</tt>''', which increases as time passes.
    This private function calculates the center point of the shot and returns the enclosing rectangle of the shot. It uses the initial cannon force and angle in addition to '''<tt>timerCount</tt>''', which increases as time passes.


    <!--T:28-->
    The formula used is the standard Newtonian formula for frictionless movement in a gravity field. For simplicity, we've chosen to disregard any Einsteinian effects.
    The formula used is the standard Newtonian formula for frictionless movement in a gravity field. For simplicity, we've chosen to disregard any Einsteinian effects.


    <!--T:29-->
    We calculate the center point in a coordinate system where y coordinates increase upward. After we have calculated the center point, we construct a [http://doc.qt.nokia.com/latest/qrect.html Qt::Rect] with size 6 x 6 and move its center point to the point calculated above. In the same operation we convert the point into the widget's coordinate system (see [http://doc.qt.nokia.com/latest/coordsys.html The Coordinate System]).
    We calculate the center point in a coordinate system where y coordinates increase upward. After we have calculated the center point, we construct a [http://doc.qt.nokia.com/latest/qrect.html Qt::Rect] with size 6 x 6 and move its center point to the point calculated above. In the same operation we convert the point into the widget's coordinate system (see [http://doc.qt.nokia.com/latest/coordsys.html The Coordinate System]).
    </translate>


    '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/t11.rb t11.rb]'''
    '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/t11.rb t11.rb]'''


    <translate>
    <!--T:30-->
    The only addition is the <strong>Shoot</strong> button.
    The only addition is the <strong>Shoot</strong> button.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 155: Line 207:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:31-->
    In the constructor we create and set up the <strong>Shoot</strong> button exactly like we did with the <strong>Quit</strong> button.
    In the constructor we create and set up the <strong>Shoot</strong> button exactly like we did with the <strong>Quit</strong> button.
    </translate>


    <syntaxhighlight lang="ruby">
    <syntaxhighlight lang="ruby">
    Line 161: Line 216:
    </syntaxhighlight>
    </syntaxhighlight>


    <translate>
    <!--T:32-->
    Connects the '''<tt>clicked()</tt>''' signal of the <strong>Shoot</strong> button to the '''<tt>shoot()</tt>''' slot of the '''<tt>CannonField</tt>'''.
    Connects the '''<tt>clicked()</tt>''' signal of the <strong>Shoot</strong> button to the '''<tt>shoot()</tt>''' slot of the '''<tt>CannonField</tt>'''.
    </translate>


    === Running the Application ===
    <translate>
    === Running the Application === <!--T:33-->
     
    <!--T:34-->
    The cannon can shoot, but there's nothing to shoot at.
    The cannon can shoot, but there's nothing to shoot at.


    === Exercises ===
    === Exercises === <!--T:35-->
     
    <!--T:36-->
    Make the shot a filled circle. [Hint: [http://doc.qt.nokia.com/latest/qpainter.html#drawEllipse Qt::Painter::drawEllipse()] may help.]
    Make the shot a filled circle. [Hint: [http://doc.qt.nokia.com/latest/qpainter.html#drawEllipse Qt::Painter::drawEllipse()] may help.]


    <!--T:37-->
    Change the color of the cannon when a shot is in the air.
    Change the color of the cannon when a shot is in the air.


    <!--T:38-->
    [[Category:Ruby]]
    [[Category:Ruby]]
    </translate>

    Latest revision as of 14:22, 18 July 2012

    Other languages:


    Giving It a Shot
    Tutorial Series   Qt4 Ruby Tutorial
    Previous   Tutorial 10 - Smooth as Silk
    What's Next   Tutorial 12 - Hanging in the Air the Way Bricks Don't
    Further Reading   n/a

    Giving It a Shot

    Files:

    Overview

    In this example we introduce a timer to implement animated shooting.

    Line by Line Walkthrough

    cannon.rb

    The CannonField now has shooting capabilities.

    include Math
    

    We include Math because we need the sin() and cos() functions.

    @timerCount = 0
    
    @autoShootTimer = Qt::Timer.new(self)
    connect(@autoShootTimer, SIGNAL('timeout()'),
             self, SLOT('moveShot()'))
    
    @shootAngle = 0
    @shootForce = 0
    

    We initialize our new private variables and connect the Qt::Timer::timeout() signal to our moveShot() slot. We'll move the shot every time the timer times out.

    The timerCount keeps track of the time passed since the shot was fired. The shootAngle is the cannon angle and shootForce is the cannon force when the shot was fired.

    def shoot()
      if @autoShootTimer.isActive()
        return
      end;
    
      @timerCount = 0
      @shootAngle = @currentAngle
      @shootForce = @currentForce
      @autoShootTimer.start(5)
    end
    

    This function shoots a shot unless a shot is in the air. The timerCount is reset to zero. The shootAngle and shootForce variables are set to the current cannon angle and force. Finally, we start the timer.

    def moveShot()
      region = Qt::Region.new(shotRect())
      @timerCount += 1
    
      shotR = shotRect()
    
      if shotR.x() > width() || shotR.y() > height()
        @autoShootTimer.stop()
      else
        region = region.unite(Qt::Region.new(shotR))
      end
      update(region)
    end
    

    moveShot() is the slot that moves the shot, called every 5 milliseconds when the Qt::Timer fires.

    Its tasks are to compute the new position, update the screen with the shot in the new position, and if necessary, stop the timer.

    First we make a Qt::Region that holds the old shotRect(). A Qt::Region is capable of holding any sort of region, and we'll use it here to simplify the painting. shotRect() returns the rectangle where the shot is now. It is explained in detail later.

    Then we increment the timerCount, which has the effect of moving the shot one step along its trajectory.

    Next we fetch the new shot rectangle.

    If the shot has moved beyond the right or bottom edge of the widget we stop the timer, or we add the new shotRect() to the Qt::Region.

    Finally, we repaint the Qt::Region. This will send a single paint event for just the one or two rectangles that need updating.

    def paintEvent(event)
      painter = Qt::Painter.new(self)
    
      paintCannon(painter)
      if @autoShootTimer.isActive()
        paintShot(painter)
      end
    
      painter.end()
    end
    

    The paint event function has been simplified since the previous chapter. Most of the logic has been moved to the new paintShot() and paintCannon() functions.

    def paintShot(painter)
      painter.setPen(Qt::NoPen)
      painter.setBrush(Qt::Brush.new(Qt::black))
      painter.drawRect(shotRect())
    end
    

    This private function paints the shot by drawing a black filled rectangle.

    We leave out the implementation of paintCannon(); it is the same as the Qt::Widget::paintEvent() reimplementation from the previous chapter.

    def shotRect()
      gravity = 4.0
    
      time = @timerCount / 20.0
      velocity = @shootForce
      radians = @shootAngle * 3.14159265 / 180.0
    
      velx = velocity * cos(radians)
      vely = velocity * sin(radians)
      x0 = (@barrelRect.right() + 5.0) * cos(radians)
      y0 = (@barrelRect.right() + 5.0) * sin(radians)
      x = x0 + velx * time
      y = y0 + vely * time - 0.5 * gravity * time * time
    
      result = Qt::Rect.new(0, 0, 6, 6)
      result.moveCenter(Qt::Point.new(x.round, height() - 1 - y.round))
      return result
    end
    

    This private function calculates the center point of the shot and returns the enclosing rectangle of the shot. It uses the initial cannon force and angle in addition to timerCount, which increases as time passes.

    The formula used is the standard Newtonian formula for frictionless movement in a gravity field. For simplicity, we've chosen to disregard any Einsteinian effects.

    We calculate the center point in a coordinate system where y coordinates increase upward. After we have calculated the center point, we construct a Qt::Rect with size 6 x 6 and move its center point to the point calculated above. In the same operation we convert the point into the widget's coordinate system (see The Coordinate System).

    t11.rb

    The only addition is the Shoot button.

    shoot = Qt::PushButton.new(tr('&Shoot'))
    shoot.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))
    

    In the constructor we create and set up the Shoot button exactly like we did with the Quit button.

    connect(shoot, SIGNAL('clicked()'), cannonField, SLOT('shoot()'))
    

    Connects the clicked() signal of the Shoot button to the shoot() slot of the CannonField.

    Running the Application

    The cannon can shoot, but there's nothing to shoot at.

    Exercises

    Make the shot a filled circle. [Hint: Qt::Painter::drawEllipse() may help.]

    Change the color of the cannon when a shot is in the air.