Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Home
Help
Recent changes
Contributor Help Pages
Tasks and Tools
Modify a page
Add new content
Page elements
Typographical guidelines
More markup help
Translator Help Pages
Get a Translator Account
Languages represented
Translation Workflow
Translate a Page
Off-line Translation
Translation Statistics
More Help pages
Search
Search
English
Log in
Personal tools
Log in
Export translations
Translate
English
Language statistics
Message group statistics
Export
Tools
Tools
move to sidebar
hide
Actions
Language statistics
Message group statistics
Export
General
Special pages
Printable version
Settings
Group
Category:Phonon
Contribute/List of KDE Modules
Development
Development/FAQs/General FAQ
Development/FAQs/Technical FAQ
Development/KDevelop-PG-Qt Introduction
Development/Tools
Development/Tutorials
Development/Tutorials/CommandLineArguments
Development/Tutorials/Common Programming Mistakes
Development/Tutorials/First program
Development/Tutorials/First program/KDE4
Development/Tutorials/First program/KF5
Development/Tutorials/KDE3/Qt Designer and KDevelop 3.0 for Beginners
Development/Tutorials/Metadata/Nepomuk/TipsAndTricks
Development/Tutorials/Physical Simulation
Development/Tutorials/Qt4 Ruby Tutorial
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 01
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 04
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 06
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 07
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 08
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 09
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 10
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 12
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 13
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3
Development/Tutorials/Saving and loading
Development/Tutorials/Setting Up
Development/Tutorials/Using Actions
Development/Tutorials/Using KXmlGuiWindow
Documentation Primer
Edit Markup
Getting Started
Help:Contents
Help:Contribute
How To Convert a UserBase Manual to Docbook
KDE Frameworks
KDE Frameworks/Getting Started
KDE TechBase:About
KDE TechBase:Contributors
KDE TechBase:General disclaimer
KDE TechBase:Privacy policy
Off-line Translation
Projects/Calligra/Plugin Tutorials
Toolbox
Translate a Page
Translation Workflow
Typographical Guidelines
User:Neverendingo
Welcome to KDE TechBase
Language
aa - Afar
ab - Abkhazian
abs - Ambonese Malay
ace - Achinese
acm - Iraqi Arabic
ady - Adyghe
ady-cyrl - Adyghe (Cyrillic script)
aeb - Tunisian Arabic
aeb-arab - Tunisian Arabic (Arabic script)
aeb-latn - Tunisian Arabic (Latin script)
af - Afrikaans
aln - Gheg Albanian
alt - Southern Altai
am - Amharic
ami - Amis
an - Aragonese
ang - Old English
ann - Obolo
anp - Angika
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
atj - Atikamekw
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - South Azerbaijani
ba - Bashkir
ban - Balinese
ban-bali - Balinese (Balinese script)
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba (Latin script)
bcc - Southern Balochi
bci - Baoulé
bcl - Central Bikol
bdr - West Coast Bajau
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bew - Betawi
bg - Bulgarian
bgn - Western Balochi
bh - Bhojpuri
bho - Bhojpuri
bi - Bislama
bjn - Banjar
blk - Pa'O
bm - Bambara
bn - Bangla
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
btm - Batak Mandailing
bto - Iriga Bicolano
bug - Buginese
bxr - Russia Buriat
ca - Catalan
cbk-zam - Chavacano
cdo - Min Dong Chinese
ce - Chechen
ceb - Cebuano
ch - Chamorro
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cps - Capiznon
cpx - Pu-Xian Min
cpx-hans - Pu-Xian Min (Simplified Han script)
cpx-hant - Pu-Xian Min (Traditional Han script)
cpx-latn - Pu-Xian Min (Latin script)
cr - Cree
crh - Crimean Tatar
crh-cyrl - Crimean Tatar (Cyrillic script)
crh-latn - Crimean Tatar (Latin script)
crh-ro - Crimean Tatar (Romania)
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
dag - Dagbani
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
dga - Dagaare
din - Dinka
diq - Zazaki
dsb - Lower Sorbian
dtp - Central Dusun
dty - Doteli
dv - Divehi
dz - Dzongkha
ee - Ewe
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
es-419 - Latin American Spanish
es-formal - Spanish (formal address)
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
fat - Fanti
ff - Fula
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fon - Fon
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fy - Western Frisian
ga - Irish
gaa - Ga
gag - Gagauz
gan - Gan Chinese
gan-hans - Gan (Simplified)
gan-hant - Gan (Traditional)
gcr - Guianan Creole
gd - Scottish Gaelic
gl - Galician
gld - Nanai
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
gor - Gorontalo
got - Gothic
gpe - Ghanaian Pidgin
grc - Ancient Greek
gsw - Alemannic
gu - Gujarati
guc - Wayuu
gur - Frafra
guw - Gun
gv - Manx
ha - Hausa
hak - Hakka Chinese
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
hno - Northern Hindko
ho - Hiri Motu
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
hsn - Xiang Chinese
ht - Haitian Creole
hu - Hungarian
hu-formal - Hungarian (formal address)
hy - Armenian
hyw - Western Armenian
hz - Herero
ia - Interlingua
id - Indonesian
ie - Interlingue
ig - Igbo
igl - Igala
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kai - Karekare
kbd - Kabardian
kbd-cyrl - Kabardian (Cyrillic script)
kbp - Kabiye
kcg - Tyap
kea - Kabuverdianu
kg - Kongo
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kjh - Khakas
kjp - Eastern Pwo
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
ko - Korean
ko-kp - Korean (North Korea)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
krl - Karelian
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ksw - S'gaw Karen
ku - Kurdish
ku-arab - Kurdish (Arabic script)
ku-latn - Kurdish (Latin script)
kum - Kumyk
kus - Kʋsaal
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - Lak
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
lki - Laki
lld - Ladin
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mad - Madurese
mag - Magahi
mai - Maithili
map-bms - Basa Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Māori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mnc - Manchu
mnc-latn - Manchu (Latin script)
mnc-mong - Manchu (Mongolian script)
mni - Manipuri
mnw - Mon
mo - Moldovan
mos - Mossi
mr - Marathi
mrh - Mara
mrj - Western Mari
ms - Malay
ms-arab - Malay (Jawi script)
mt - Maltese
mus - Muscogee
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nāhuatl
nan - Min Nan Chinese
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
nia - Nias
niu - Niuean
nl - Dutch
nl-informal - Dutch (informal address)
nmz - Nawdm
nn - Norwegian Nynorsk
no - Norwegian
nod - Northern Thai
nog - Nogai
nov - Novial
nqo - N’Ko
nrm - Norman
nso - Northern Sotho
nv - Navajo
ny - Nyanja
nyn - Nyankole
nys - Nyungar
oc - Occitan
ojb - Northwestern Ojibwa
olo - Livvi-Karelian
om - Oromo
or - Odia
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pcd - Picard
pcm - Nigerian Pidgin
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Norfuk / Pitkern
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
pwn - Paiwan
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rki - Arakanese
rm - Romansh
rmc - Carpathian Romani
rmy - Vlax Romani
rn - Rundi
ro - Romanian
roa-tara - Tarantino
rsk - Pannonian Rusyn
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rw - Kinyarwanda
ryu - Okinawan
sa - Sanskrit
sah - Yakut
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
se-fi - Northern Sami (Finland)
se-no - Northern Sami (Norway)
se-se - Northern Sami (Sweden)
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
sh-cyrl - Serbo-Croatian (Cyrillic script)
sh-latn - Serbo-Croatian (Latin script)
shi - Tachelhit
shi-latn - Tachelhit (Latin script)
shi-tfng - Tachelhit (Tifinagh script)
shn - Shan
shy - Shawiya
shy-latn - Shawiya (Latin script)
si - Sinhala
simple - Simple English
sjd - Kildin Sami
sje - Pite Sami
sk - Slovak
skr - Saraiki
skr-arab - Saraiki (Arabic script)
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
smn - Inari Sami
sms - Skolt Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - српски (ћирилица)
sr-el - srpski (latinica)
srn - Sranan Tongo
sro - Campidanese Sardinian
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
sty - Siberian Tatar
su - Sundanese
sv - Swedish
sw - Swahili
syl - Sylheti
szl - Silesian
szy - Sakizaya
ta - Tamil
tay - Tayal
tcy - Tulu
tdd - Tai Nuea
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tk - Turkmen
tl - Tagalog
tly - Talysh
tly-cyrl - Talysh (Cyrillic script)
tn - Tswana
to - Tongan
tok - Toki Pona
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
trv - Taroko
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - Uzbek (Cyrillic script)
uz-latn - Uzbek (Latin script)
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vmw - Makhuwa
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
wal - Wolaytta
war - Waray
wls - Wallisian
wo - Wolof
wuu - Wu Chinese
wuu-hans - Wu Chinese (Simplified)
wuu-hant - Wu Chinese (Traditional)
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
xsy - Saisiyat
yi - Yiddish
yo - Yoruba
yrl - Nheengatu
yue - Cantonese
yue-hans - Cantonese (Simplified)
yue-hant - Cantonese (Traditional)
za - Zhuang
zea - Zeelandic
zgh - Standard Moroccan Tamazight
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - Chinese (Macau)
zh-my - Chinese (Malaysia)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
qqq - Message documentation
Format
Export for off-line translation
Export in native format
Export in CSV format
Fetch
{{DISPLAYTITLE:Разработка/Руководства/Введение в Qt4 на Ruby/Глава 13}}<languages /> {{TutorialBrowser/ru| series=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial|Введение в программирование на Qt<sup>®</sup>4 на языке Ruby]]| name=Игра окончена| pre=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_12|Пример 12: Висящий в воздухе]]| next=[[Special:myLanguage/Development/Tutorials/Qt4_Ruby_Tutorial/Chapter_14|Пример 14: Стена]] }} <span id="Game_Over"></span> == Игра окончена == [[Image:Qt4_Ruby_Tutorial_Screenshot_13.png|center]] Файлы: * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/lcdrange.rb lcdrange.rb] * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/gamebrd.rb gamebrd.rb] * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/t13.rb t13.rb] * [http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/cannon.rb cannon.rb] <span id="Overview"></span> === Обзор === In this example we start to approach a real playable game with a score. We give '''<tt>MyWidget</tt>''' a new name ('''<tt>GameBoard</tt>'''), add some slots, and move it to '''<tt>gamebrd.rb</tt>''' The '''<tt>CannonField</tt>''' now has a game over state. The layout problems in '''<tt>LCDRange</tt>''' are fixed. <span id="Line_by_Line_Walkthrough"></span> === Построчный обзор программы === '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/lcdrange.rb lcdrange.rb]''' <syntaxhighlight lang="ruby"> @label.setSizePolicy(Qt::SizePolicy::Preferred, Qt::SizePolicy::Fixed) </syntaxhighlight> We set the size policy of the [http://doc.qt.nokia.com/latest/qlabel.html Qt::Label] to ([http://doc.qt.nokia.com/latest/qsizepolicy.html#Policy-enum Qt::SizePolicy::Preferred], [http://doc.qt.nokia.com/latest/qsizepolicy.html#Policy-enum Qt::SizePolicy::Fixed]). The vertical component ensures that the label won't stretch or shrink vertically; it will stay at its optimal size (its [http://doc.qt.nokia.com/latest/qwidget.html#sizeHint-prop QWidget::sizeHint()]). This solves the layout problems observed in Chapter 12. '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/cannon.rb cannon.rb]''' The '''<tt>CannonField</tt>''' now has a game over state and a few new functions. <syntaxhighlight lang="ruby"> signals 'canShoot(bool)' </syntaxhighlight> This new signal indicates that the '''<tt>CannonField</tt>''' is in a state where the '''<tt>shoot()</tt>''' slot makes sense. We'll use it below to enable or disable the <strong>Shoot</strong> button. <syntaxhighlight lang="ruby"> @gameEnded = false </syntaxhighlight> This variable contains the game state; '''<tt>true</tt>''' means that the game is over, and '''<tt>false</tt>''' means that a game is going on. Initially, the game is not over (luckily for the player :-). <syntaxhighlight lang="ruby"> def shoot() if isShooting() return end @timerCount = 0 @shootAngle = @currentAngle @shootForce = @currentForce @autoShootTimer.start(5) emit canShoot(false) end </syntaxhighlight> We added a new '''<tt>isShooting()</tt>''' function, so '''<tt>shoot()</tt>''' uses it instead of testing directly. Also, shoot tells the world that the '''<tt>CannonField</tt>''' cannot shoot now. <syntaxhighlight lang="ruby"> def setGameOver() if @gameEnded return end if isShooting() @autoShootTimer.stop() end @gameEnded = true update() end </syntaxhighlight> This slot ends the game. It must be called from outside '''<tt>CannonField</tt>''', because this widget does not know when to end the game. This is an important design principle in component programming. We choose to make the component as flexible as possible to make it usable with different rules (for example, a multi-player version of this in which the first player to hit ten times wins could use the '''<tt>CannonField</tt>''' unchanged). If the game has already been ended we return immediately. If a game is going on we stop the shot, set the game over flag, and repaint the entire widget. <syntaxhighlight lang="ruby"> def restartGame() if isShooting() @autoShootTimer.stop() end @gameEnded = false update() emit canShoot(true) end </syntaxhighlight> This slot starts a new game. If a shot is in the air, we stop shooting. We then reset the '''<tt>gameEnded</tt>''' variable and repaint the widget. '''<tt>moveShot()</tt>''' too emits the new '''<tt>canShoot(true)</tt>''' signal at the same time as either '''<tt>hit()</tt>''' or '''<tt>miss()</tt>'''. Modifications in CannonField::paintEvent(): <syntaxhighlight lang="ruby"> def paintEvent(event) painter = Qt::Painter.new(self) if @gameEnded painter.setPen(Qt::black) painter.setFont(Qt::Font.new( "Courier", 48, Qt::Font::Bold)) painter.drawText(rect(), Qt::AlignCenter, tr("Game Over")) end </syntaxhighlight> The paint event has been enhanced to display the text "Game Over" if the game is over, i.e., '''<tt>gameEnded</tt>''' is '''<tt>true</tt>'''. We don't bother to check the update rectangle here because speed is not critical when the game is over. To draw the text we first set a black pen; the pen color is used when drawing text. Next we choose a 48 point bold font from the Courier family. Finally we draw the text centered in the widget's rectangle. Unfortunately, on some systems (especially X servers with Unicode fonts) it can take a while to load such a large font. Because Qt caches fonts, you will notice this only the first time the font is used. <syntaxhighlight lang="ruby"> paintCannon(painter) if isShooting() paintShot(painter) end unless @gameEnded paintTarget(painter) end painter.end() end </syntaxhighlight> We draw the shot only when shooting and the target only when playing (that is, when the game is not ended). '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/gamebrd.rb gamebrd.rb]''' This file is new. It contains the '''<tt>GameBoard</tt>''' class, which was last seen as '''<tt>MyWidget</tt>'''. <syntaxhighlight lang="ruby"> slots 'fire()', 'hit()', 'missed()', 'newGame()' </syntaxhighlight> We have now added four slots. We have also made some changes in the '''<tt>GameBoard</tt>''' constructor. <syntaxhighlight lang="ruby"> @cannonField = CannonField.new() </syntaxhighlight> '''<tt>@cannonField</tt>''' is now a member variable, so we carefully change the constructor to use it. <syntaxhighlight lang="ruby"> connect(@cannonField, SIGNAL('hit()'), self, SLOT('hit()')) connect(@cannonField, SIGNAL('missed()'), self, SLOT('missed()')) </syntaxhighlight> This time we want to do something when the shot has hit or missed the target. Thus we connect the '''<tt>hit()</tt>''' and '''<tt>missed()</tt>''' signals of the '''<tt>CannonField</tt>''' to two protected slots with the same names in this class. <syntaxhighlight lang="ruby"> connect(shoot, SIGNAL('clicked()'), self, SLOT('fire()') ) </syntaxhighlight> Previously we connected the <strong>Shoot</strong> button's '''<tt>clicked()</tt>''' signal directly to the '''<tt>CannonField</tt>''''s '''<tt>shoot()</tt>''' slot. This time we want to keep track of the number of shots fired, so we connect it to a slot in this class instead. Notice how easy it is to change the behavior of a program when you are working with self-contained components. <syntaxhighlight lang="ruby"> connect(@cannonField, SIGNAL('canShoot(bool)'), shoot, SLOT('setEnabled(bool)')) </syntaxhighlight> We also use the '''<tt>CannonField</tt>''''s '''<tt>canShoot()</tt>''' signal to enable or disable the <strong>Shoot</strong> button appropriately. <syntaxhighlight lang="ruby"> restart = Qt::PushButton.new(tr('&New Game')) restart.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold)) connect(restart, SIGNAL('clicked()'), self, SLOT('newGame()')) </syntaxhighlight> We create, set up, and connect the <strong>New Game</strong> button as we have done with the other buttons. Clicking this button will activate the '''<tt>newGame()</tt>''' slot in this widget. <syntaxhighlight lang="ruby"> @hits = Qt::LCDNumber.new(2) @shotsLeft = Qt::LCDNumber.new(2) hitsLabel = Qt::Label.new(tr('HITS')) shotsLeftLabel = Qt::Label.new(tr('SHOTS LEFT')) </syntaxhighlight> We create four new widgets, to display the number of hits and shots left. <syntaxhighlight lang="ruby"> topLayout = Qt::HBoxLayout.new() topLayout.addWidget(shoot) topLayout.addWidget(@hits) topLayout.addWidget(hitsLabel) topLayout.addWidget(@shotsLeft) topLayout.addWidget(shotsLeftLabel) topLayout.addStretch(1) topLayout.addWidget(restart) </syntaxhighlight> The top-right cell of the [http://doc.qt.nokia.com/latest/qgridlayout.html Qt::GridLayout] is starting to get crowded. We put a stretch just to the left of the <strong>New Game</strong> button to ensure that this button will always appear on the right side of the window. <syntaxhighlight lang="ruby"> newGame() </syntaxhighlight> We're all done constructing the '''<tt>GameBoard</tt>''', so we start it all using '''<tt>newGame()</tt>'''. Although '''<tt>newGame()</tt>''' is a slot, it can also be used as an ordinary function. <syntaxhighlight lang="ruby"> def fire() if @cannonField.gameOver() || @cannonField.isShooting() return end @shotsLeft.display(@shotsLeft.intValue() - 1) @cannonField.shoot() end </syntaxhighlight> This function fires a shot. If the game is over or if there is a shot in the air, we return immediately. We decrement the number of shots left and tell the cannon to shoot. <syntaxhighlight lang="ruby"> def hit() @hits.display(@hits.intValue() + 1) if @shotsLeft.intValue() == 0 @cannonField.setGameOver() else @cannonField.newTarget() end end </syntaxhighlight> This slot is activated when a shot has hit the target. We increment the number of hits. If there are no shots left, the game is over. Otherwise, we make the '''<tt>CannonField</tt>''' generate a new target. <syntaxhighlight lang="ruby"> def missed() if @shotsLeft.intValue() == 0 @cannonField.setGameOver() end end </syntaxhighlight> This slot is activated when a shot has missed the target. If there are no shots left, the game is over. <syntaxhighlight lang="ruby"> def newGame() @shotsLeft.display(15) @hits.display(0) @cannonField.restartGame() @cannonField.newTarget() end </syntaxhighlight> This slot is activated when the user clicks the <strong>New Game</strong> button. It is also called from the constructor. First it sets the number of shots to 15. Note that this is the only place in the program where we set the number of shots. Change it to whatever you like to change the game rules. Next we reset the number of hits, restart the game, and generate a new target. '''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t13/t13.rb t13.rb]''' This file has just been on a diet. '''<tt>MyWidget</tt>''' is gone, and the only thing left is the '''<tt>main()</tt>''' function, unchanged except for the name change. <span id="Running_the_Application"></span> === Запуск приложения === The cannon can shoot at a target; a new target is automatically created when one has been hit. Hits and shots left are displayed and the program keeps track of them. The game can end, and there's a button to start a new game. <span id="Exercises"></span> === Упражнения === Add a random wind factor and show it to the user. Make some splatter effects when the shot hits the target. Implement multiple targets. [[Category:Ruby/ru]]
Toggle limited content width