Commit ecb7164f43280e3eeb609fff5f3d61020ec53aef

Merge commit 'danielmartins/master'

Commit diff

PortugueseBook/FirstApp/FirstApp.tex

 
2727 \sloppy
2828\fi
2929%=================================================================
30\chapter{A first application}
30\chapter{Uma primeira aplicação}
3131\label{cha:firstApp}
3232
33In this chapter, we will develop a simple game: \ind{Quinto}.
34Along the way we will demonstrate most of the tools that \squeak programmers use to construct and debug their programs, and show how programs are exchanged with other developers. We will see the system browser, the object inspector, the debugger and the \ind{Monticello} \ind{package} browser.
35Development in Smalltalk is efficient: you will find that you spend far more time actually writing code and far less managing the development process.
36This is partly because the Smalltalk language is very simple, and partly because the tools that make up the programming environment are very well integrated with the language.
33Neste capítulo, nós iremos desenvolver um jogo simples: \ind{Quinto}.
34Durante o desenvolvimento nós iremos demonstrar a maioria das ferramentas que programadores \squeak usam para construir e depurar seus programas, além de mostrar também como programas são distribuídos a outros desenvolvedores. Nós iremos ver o \foreign{system browser}, o \foreign{object inspector}, o \foreign{debugger} e o \foreign{\ind{Monticello} \ind{package} browser}.
35Desenvolver em Smalltalk é eficiente: você descobrirá que a maioria do tempo é usado para escrever código, e que pouco tempo é gasto gerenciando o processo de desenvolvimento.
36Isso acontece tanto pela simplicidade da linguagem Smalltalk quanto por causa que as ferramentas que compõe o ambiente de programação são muito bem integradas à linguagem.
3737
3838%=================================================================
39\section{The Quinto game}
39\section{Quinto, o jogo}
4040
4141% DON'T USE WRAPFIGURE CLOSE TOO A PAGE BREAK!!! (ON)
4242%\begin{wrapfigure}[13]{r}{0.35\linewidth}%
4949\begin{figure}[ht]
5050 \vskip -\baselineskip
5151 \centerline{\includegraphics[width=.3\linewidth]{GameBoard}}
52 \caption{The Quinto game board. The user has just clicked the mouse as shown by the cursor.
52 \caption{Tabuleiro do jogo Quinto. O usuário acabou de clicar com o mouse como mostrado pelo cursor.
5353 \label{fig:gameBoard}}
5454\end{figure}
5555
56To show you how to use \squeak's programming tools, we will build a simple game called \emph{Quinto}. The game board is shown in \figref{gameBoard}; it consists of rectangular array of light yellow \emph{cells}. When you click on one of the cells with the mouse, the four surrounding cells turn blue. Click again, and they toggle back to light yellow. The object of the game is to turn blue as many cells as possible.
56Para mostrar como usar as ferramentas de programação do \squeak, nós iremos construir um jogo simples chamado \emph{Quinto}. O tabuleiro do jogo é mostrado na \figref{gameBoard}; ele consiste num conjunto retangular de \emph{células} amarelo-claras. Quando você clica sobre uma das células com o mouse, as quatro células ao redor mudam para a cor azul. Clique novamente, e elas voltarão para a cor amarelo-clara. O objetivo do jogo é mudar para azul a maior quantidade possível de células.
5757
58The Quinto game shown in \figref{gameBoard} is made up of two kinds of objects: the game board itself, and 100 individual cell objects. The \squeak code to implement the game will contain two classes: one for the game and one for the cells.
59We will now show you how to define these classes using the \squeak programming tools.
58O jogo Quinto mostrado na \figref{gameBoard} é feito a partir de dois tipos de objetos: o tabuleiro em si, e 100 objetos que representam cada célula. O código \squeak para implementar o jogo irá conter duas classes: uma para o jogo e outra para as células.
59Nós iremos mostrar agora como definir essas classes usando as ferramentas de programação do \squeak.
6060
6161%=================================================================
62\section{Creating a new class Category}
62\section{Criando uma nova categoria de classe}
6363
64We have already seen the \ind{system browser} in \charef{quick}, where we learned how to navigate to classes and methods, and saw how to define new methods.
65Now we will see how to create system categories and classes.
66\seeindex{system category}{category}
67\seeindex{class category}{system category}
68\index{category!creating}
64Nós já vimos o \foreign{\ind{system browser}} em \charef{quick}, onde aprendemos como navegar pelas classes e métodos, e como definir novos métodos.
65Agora nós veremos como criar categorias e classes de sistema.
66\seeindex{categoria de sistema}{categoria}
67\seeindex{categoria de classe}{categoria de sistema}
68\index{categoria!criação}
6969
70\dothis{Open a system browser and yellow-click in the category pane.
71Select \menu{add item \ldots}.}
70\dothis{Abra um \foreign{system browser} e clique com o botão amarelo no painel de categorias.
71Selecione o menu \menu{add item \ldots}.}
7272
7373\begin{figure}[htb]
7474\begin{minipage}[b]{0.48\textwidth}
7575\ifluluelse
7676 {\centerline {\includegraphics[width=0.9\textwidth]{AddCategory}}}
7777 {\centerline {\includegraphics[scale=0.7]{AddCategory}}}
78 \caption{Adding a system category.
78 \caption{Adicionando uma categoria.
7979 \label{fig:addCategory}}
8080\end{minipage}
8181\hfill
8383\ifluluelse
8484 {\centerline {\includegraphics[width=0.9\textwidth]{ClassTemplate}}}
8585 {\centerline {\includegraphics[scale=0.7]{ClassTemplate}}}
86 \caption{The class-creation Template.
86 \caption{Modelo de criação de classe.
8787 \label{fig:classTemplate}}
8888\end{minipage}
8989\end{figure}
9090
91Type the name of the new category (we will use \scat{SBE-Quinto}) in the dialog box and click \menu{accept} (or just press the return key); the new category is created, and positioned at the end of the category list.
92If you selected an existing category first, then the new category will be positioned immediately ahead of the selected one.
91Digite o nome da nova categoria (nós usaremos \scat{SBE-Quinto}) na caixa de diálogo e selecione o menu \menu{accept} (ou apenas pressione ENTER); a nova categoria foi criada e posicionada no final da lista de categorias.
92Se você selecionou uma categoria existente primeiro, então a nova categoria será posicionada imediatamente acima da mesma.
9393
9494%=================================================================
95\section{Defining the class SBECell}
95\section{Definindo a classe SBECell}
9696
97As yet there are of course no classes in the new category. However, the main editing pane displays a template to make it easy to create a new class (see \figref{classTemplate}).
97Obviamente ainda não existem classes nesta nova categoria. No entanto, o painel principal de edição mostra um modelo para facilitar a criação de uma nova classe (veja \figref{classTemplate}).
9898
99This template shows us a \st expression that sends a message to a class called \ct{Object}, asking it to create a subclass called \ct{NameOfSubClass}. The new class has no variables, and should belong to the category \scat{SBE-Quinto}.
99Este modelo nos mostra uma expressão \st que envia uma mensagem para a classe chamada \ct{Object}, solicitando a criação de uma subclasse chamada \ct{NameOfSubClass}. A nova classe não possui variáveis, e pertence à categoria \scat{SBE-Quinto}.
100100
101We simply modify the template to create the class that we really want.
101Nós simplesmente modificamos o modelo para criar a classe que realmente queremos.
102102
103\dothis{Modify the class creation template as follows:}
103\dothis{Modifique o modelo de criação de classe como segue:}
104104\begin{itemize}
105 \item Replace \clsind{Object} by \clsind{SimpleSwitchMorph}.
106 \item Replace \ct{NameOfSubClass} by \clsind{SBECell}.
107 \item Add \ct{mouseAction} to the list of instance variables.
105 \item Substitua \clsind{Object} por \clsind{SimpleSwitchMorph}.
106 \item Substitua \ct{NameOfSubClass} por \clsind{SBECell}.
107 \item Adicione \ct{mouseAction} à lista de variáveis de instância.
108108\end{itemize}
109The result should look like \clsref{firstClassDef}.
109O resultado deve parecer com \clsref{firstClassDef}.
110110
111\begin{classdef}[firstClassDef]{Defining the class \ct| SBECell|}
111\begin{classdef}[firstClassDef]{Definindo a classe \ct| SBECell|}
112112SimpleSwitchMorph subclass: #SBECell
113113 instanceVariableNames: 'mouseAction'
114114 classVariableNames: ''
115115 poolDictionaries: ''
116116 category: 'SBE-Quinto'
117117\end{classdef}
118\index{system browser!defining a class}
119\index{class!creation}
118\index{system browser!definindo uma classe}
119\index{classe!criação}
120120\index{Morphic}
121121
122This new definition consists of a \st expression that sends a message to the existing class \ct{SimpleSwitchMorph}, asking it to create a subclass called \ct{SBECell}.
123(Actually, since \ct{SBECell} does not exist yet, we passed as an argument the \emphind{symbol} \ct{#SBECell} which stands for the name of the class to create.)
124We also tell it that instances of the new class should have a \ct{mouseAction} instance variable, which we will use to define what action the cell should take if the mouse should click over it.
125
126\emph{At this point you still have not created anything.}
127Note that the border of the class template pane has changed to red (\figref{acceptClassDef}).
128This means that there are \emph{unsaved changes}.
129To actually send this message, you must \menu{accept} it.
122Esta nova definição consiste numa expressão \st que envia uma mensagem para a classe já existente \ct{SimpleSwitchMorph}, solicitando que a mesma crie uma subclasse chamada \ct{SBECell}.
123(Na verdade, uma vez que \ct{SBECell} ainda não existe, nós passamos o \emphind{símbolo} \ct{#SBECell} que representa o nome da classe a ser criada.)
124Nós também informamos que as instâncias da nova classe devem ter uma variável de instância \ct{mouseAction}, que será usada para definir qual ação a célula deve tomar se esta for clicada pelo mouse.
130125
126\emph{Neste ponto você ainda não criou nada.}
127Note que a borda do painel do modelo de classe mudou para vermelho (\figref{acceptClassDef}).
128Isso significa que existem \emph{mudanças não salvas}.
129Para realmente enviar esta mensagem, você deve selecionar o menu \menu{accept}.
131130\begin{figure}[h!t]
132131\ifluluelse
133132 {\centerline {\includegraphics[width=\textwidth]{AcceptClassDef}}}
134133 {\centerline {\includegraphics[scale=0.7]{AcceptClassDef}}}
135\caption{The class-creation Template.
134\caption{Modelo de definição de classe.
136135\label{fig:acceptClassDef}}
137136\end{figure}
138137
139\dothis{Accept the new class definition.}
140Either yellow-click and select \menu{accept}, or use the shortcut \short{s} (for ``save'').
141The message will be sent to \ct{SimpleSwitchMorph}, which will cause the new class to be compiled.
142\index{yellow button}
143\index{keyboard shortcut!accept}
138\dothis{Salve a nova definição de classe.}
139Clique com o botão amarelo e selecione \menu{accept}, ou use o atalho \short{s} (de ``salvar'')
140A mensagem será enviada para \ct{SimpleSwitchMorph}, causando a compilação da nova classe.
141\index{botão amarelo}
142\index{atalho de teclado!accept}
143
144Uma vez que a nova definição de classe é salva, a classe será criada e aparecerá no painel de classes do \foreign{browser} (\figref{SBECell}).
145O painel de edição agora deve mostrar a definição da classe, e um pequeno painel abaixo que o lembrará de escrever algumas palavras que descrevem o propósito da classe. Isso é chamado de \emph{comentário de classe}, e é muito importante escrever algo que dê aos outros programadores uma visão geral do propósito da classe.
146Programadores \st consideram a legibilidade de código algo extremamente importante, e comentários detalhados em métodos não é muito comum de se ver: a filosofia é que o código deve falar por si só. (Se não falar, você deve refatorá-lo até que ele fale!) Um comentário de \subind{comentário}{classe} não precisa conter uma descrição detalhada da classe, mas poucas palavras descrevendo seu propósito são vitais para que outros programadores que vierem depois saibam como se organizar ao trabalhar com a classe.
144147
145Once the class definition is accepted, the class will be created and appear in the classes pane of the browser (\figref{SBECell}).
146The editing pane now shows the class definition, and a small pane below it will remind you to write a few words describing the purpose of the class. This is called a \emph{class comment}, and it is quite important to write one that will give other programmers a high-level overview of the purpose of this class.
147Smalltalkers put a very high value on the readability of their code, and detailed comments in methods are unusual: the philosophy is that the code should speak for itself. (If it doesn't, you should refactor it until it does!) A class \subind{class}{comment} need not contain a detailed description of the class, but a few words describing its overall purpose are vital if programmers who come after you are to know whether to spend time looking at this class.
148\index{refactoring}
148\index{refatoração}
149149
150\dothis{Type a class comment for \ct{SBECell} and accept it; you can always improve it later.}
150\dothis{Digite um comentário de classe para \ct{SBECell} e o salve; você sempre pode melhorá-lo com o passar do tempo.}
151151
152152\begin{figure}[h!t]
153153\ifluluelse
154154 {\centerline {\includegraphics[width=\textwidth]{SBECell}}}
155155 {\centerline {\includegraphics[scale=0.7]{SBECell}}}
156\caption{The newly-created class \ct{SBECell}\label{fig:SBECell}}
156\caption{A nova classe \ct{SBECell}.\label{fig:SBECell}}
157157\end{figure}
158158
159159%=================================================================
160\section{Adding methods to a class}
160\section{Adicionando métodos a classe}
161161
162Now let's add some methods to our class.
162Agora vamos adicionar alguns métodos à nossa classe.
163163
164\dothis{Select the protocol \prot{-{}-all-{}-} in the protocol pane.}
165You will see a template for method creation in the editing pane.
166Select it, and replace it by the text of \mthref{scbecellinitialize}.
167\protindex{all}
168\index{method!creation}
169\index{system browser!defining a method}
164\dothis{Selecione o protocolo \prot{-{}-all-{}-} no painel de protocolos.}
165Você verá um modelo para a criação do método no painel de edição.
166Selecione-o, e o substitua pelo texto do \mthref{scbecellinitialize}.
167\protindex{todos}
168\index{método!criação}
169\index{system browser!definindo um método}
170170
171171\needlines{10}
172\begin{numMethod}[scbecellinitialize]{Initializing instances of \ct{SBECell}}
172\begin{numMethod}[scbecellinitialize]{Inicializando instâncias de \ct{SBECell}}
173173initialize
174174 super initialize.
175175 self label: ''.
180180 self useSquareCorners.
181181 self turnOff
182182\end{numMethod}
183\index{initialization}
183\index{inicialização}
184184
185185\noindent
186Note that the characters \ct{''} on line 3 are two separate single quotes with nothing between them, not a double quote! \ct{''} denotes the empty string.
186Note que os caracteres \ct{''} na linha 3 são dois caracteres de aspas-simples sem nada entre eles, e não um caractere de aspas-duplas! \ct{''} indica uma string vazia.
187187
188\dothis{\menu{Accept} this method definition.}
188\dothis{Selecione o menu \menu{accept} para salvar esta nova definição de método.}
189189
190What does the above code do? We won't go into all of the details here (that's what the rest of the book is for!), but we will give you a quick preview. Let's take it line by line.
190O que o código acima faz? Nós não iremos entrar em todos os detalhes aqui (é para isso que serve o restante do livro!), mas nós lhe daremos uma rápida introdução. Vamos linha-a-linha.
191191
192Notice that the method is called \mthind{SBECell}{initialize}.
193The name is very significant!
194By convention, if a class defines a method named \ct{initialize}, it will be called right after the object is created.
195So, when we evaluate \ct{SBECell new}, the message \ct{initialize} will be sent automatically to this newly created object.
196Initialize methods are used to set up the state of objects, typically to set their instance variables; this is exactly what we are doing here.
197\seeindex{Object!initialization}{initialization}
198\index{initialization}
192Perceba que o método se chama \mthind{SBECell}{initialize}.
193O nome é muito importante!
194Por convenção, se a classe define um método chamado \ct{initialize}, ele será chamado logo após a criação do objeto.
195Então, quando executamos \ct{SBECell new}, a mensagem \ct{initialize} será automaticamente enviada ao objeto recém-criado.
196Métodos de inicialização são usados para definir o estado dos objetos, tipicamente para configurar suas variáveis de instância; isso é exatamente o que estamos fazendo aqui.
197\seeindex{Objeto!inicialização}{inicialização}
198\index{inicialização}
199199
200The first thing that this method does (line 2) is to execute the \ct{initialize} method of its superclass, \ct{SimpleSwitchMorph}.
201The idea here is that any inherited state will be properly initialized by the \ct{initialize} method of the superclass.
202It is always a good idea to initialize inherited state by sending \ct{super initialize} before doing anything else; we don't know exactly what \ct{SimpleSwitchMorph}'s \ct{initialize} method will do, and we don't care, but it's a fair bet that it will set up some instance variables to hold reasonable default values, so we had better call it, or we risk starting in an unclean state.
200A primeira coisa que este método faz (linha 2) é executar o método \ct{initialize} da sua superclasse, \ct{SimpleSwitchMorph}.
201A idéia aqui é que qualquer estado herdado seja devidamente inicializado pelo método \ct{initialize} da superclasse.
203202
204The rest of the method sets up the state of this object.
205Sending \ct{self label: ''}, for example, sets the label of this object to the empty string.
203É sempre uma boa idéia inicializar o estado herdado enviando a mensagem \ct{super initialize} antes de fazer qualquer outra coisa; nós não sabemos exatamente o que o método \ct{initialize} de \ct{SimpleSwitchMorph} fará, e também não queremos saber, mas é bem provável que ele atribuirá valores-padrão a algumas variáveis de instância, então é melhor chamarmos este método, ou nós corremos o risco de criar um objeto cujo estado foi apenas parcialmente inicializado.
204
205O resto do método define o estado deste objeto.
206Enviar \ct{self label:''}, por exemplo, define o rótulo deste objeto para uma string vazia.
206207\pvindex{self}
207208
208The expression \ct{0@0 corner: 16@16} probably needs some explanation.
209\lct{0@0} represents a \clsind{Point} object with $x$ and $y$ coordinates both set to 0.
210In fact, \ct{0@0} sends the message \ct{@}
209A expressão \ct{0@0 corner: 16@16} provavelmente precisa de mais explicações.
210\lct{0@0} representa um objeto \clsind{Point} com ambas as coordenadas $x$ and $y$ definidas como 0.
211Na verdade, \ct{0@0} envia a mensagem \ct{@}
211212% Yuck... the following should be \mthind{Number}{@}
212213%%% THIS IS BROKEN -- don't do it! (on)
213214%\def\atsign{\textsf{@}}%
218218% \protected@write\@indexfile{}%
219219% {\string\indexentry{Number!\string\atsign|hyperpage}{\thepage}}%
220220% \makeatother}
221to the number \ct{0} with argument \ct{0}.
222The effect will be that the number \ct{0} will ask the \ct{Point} class to create a new instance with coordinates (0,0).
223Now we send this newly created point the message \ct{corner: 16@16}, which causes it to create a \clsind{Rectangle} with corners \ct{0@0} and \ct{16@16}.
224This newly created rectangle will be assigned to the \ct{bounds} variable, inherited from the superclass.
221ao número \ct{0} com o argumento \ct{0}.
222O resultado disso é que o número \ct{0} irá solicitar à classe \ct{Point} a criação de uma nova instância com as coordenadas (0,0).
223Em seguida nós enviamos a este objeto \ct{Point} recém criado a mensagem \ct{corner: 16@16}, resultando na criação de um objeto \clsind{Rectangle} com cantos posicionados em \ct{0@0} e \ct{16@16}.
224Este retângulo recém criado será atribuído à variável \ct{bounds}, herdada da superclasse.
225225
226Note that the origin of the \sq screen is the \emph{top left}, and the $y$ coordinate increases \emph{downwards}.
226Note que o ponto de origem da tela do \sq se encontra na parte superior esquerda da tela, e a coordenada $y$ aumenta para baixo.
227227
228The rest of the method should be self-explanatory.
229Part of the art of writing good \st code is to pick good method names so that \st code can be read like a kind of pidgin English.
230You should be able to imagine the object talking to itself and saying ``\ct{Self use square corners!}'', ``\ct{Self turn off!}''.
228O restante do método deve ser auto-explicativo.
229Parte da arte de se escrever bom código \st é escolher bons nomes de métodos de modo que o código possa ser lido como se fosse um tipo de Inglês degenerado.
230Você deve ser capaz de imaginar o objeto conversando consigo mesmo e dizendo ``\ct{Self use square corners!}'', ``\ct{Self turn off!}''.
231231
232232%=================================================================
233\section{Inspecting an object}
233\section{Inspecionando um objeto}
234234
235You can test the effect of the code you have written by creating a new \ct{SBECell} object and inspecting it.
235Você pode testar o efeito do código que você escreveu criando um novo objeto \ct{SBECell} e o inspecionando.
236236
237\dothis{Open a workspace. Type the expression \ct{SBECell new} and \menu{inspect it}.}
237\dothis{Abra um \foreign{workspace}. Digite a expressão \ct{SBECell new} e selecione o menu \menu{inspect it}.}
238238
239239\begin{figure}[htbp]
240240 \centering
241241 \includegraphics[scale=0.7]{SBECellInspector}
242 \caption{The inspector used to examine a SBECell object.\label{fig:SBECellInspector}}
242 \caption{O \foreign{inspector} usado para examinar o objeto SBECell.\label{fig:SBECellInspector}}
243243\end{figure}
244244
245The left-hand pane of the \ind{inspector} shows a list of instance variables; if you select one (try \mbox{\ct{bounds}),} the value of the \ind{instance variable} is shown in the right pane. You can also use the inspector to change the value of an instance variable.
245O painel situado na parte esquerda da janela do \foreign{\ind{inspector}} mostra uma lista das variáveis de instância; se você selecionar uma (tente \mbox{\ct{bounds}}), o valor da \ind{variável de instância} é exibido no painel da direita. Você também pode usar o \foreign{inspector} para mudar o valor de uma variável de instância.
246246
247\dothis{Change the value of \ct{bounds} to \ct{0@0 corner: 50@50} and \menu{accept} it.}
247\dothis{Mude o valor de \ct{bounds} para \ct{0@0 corner: 50@50} e selecione o menu \menu{accept}.}
248248
249The bottom pane of the inspector is a mini-workspace. It's useful because in this workspace the pseudo-variable \self is bound to the object being inspected.
249O painel situado na parte inferior da janela é um \foreign{mini-workspace}. Ele é útil porque neste \foreign{workspace} a pseudo-variável \self está ligada ao objeto sendo inspecionado.
250250
251\dothis{Type the text \ct{self openInWorld} in the bottom pane and \menu{do it}.}
252The cell should appear at the top left-hand corner of the screen, indeed, exactly where its \ct{bounds} say that it should appear.
253Blue-click on the cell to bring up the morphic \subind{Morphic}{halo}.
254Move the cell with the brown (next to top-right) handle and resize it with the yellow (bottom-right) handle.
255Notice how the bounds reported by the inspector also change.
251\dothis{Digite o texto \ct{self openInWorld} no painel inferior e selecione o menu \menu{do it}.}
252A célula deve aparecer na parte superior esquerda da tela, de fato, exatamente no local indicado pela variável \ct{bounds}.
253Clique com o botão azul na célula para exibir o \foreign{\subind{Morphic}{halo}} da célula.
254Mova a célula usando o \foreign{handler} marrom (próximo ao canto superior direito) e a redimensione usando o \foreign{handler} amarelo (canto inferior direito).
255Perceba como as dimensões reportadas pelo inspector na variável \ct{bounds} também mudam.
256256
257257\begin{figure}[htbp]
258258\centering
259259\ifluluelse
260260 {\includegraphics[width=\textwidth]{SBECellResize} }
261261 {\includegraphics[scale=0.7]{SBECellResize} }
262\caption{Resizing the cell.\label{fig:cellresize}}
262\caption{Redimensionando a célula.\label{fig:cellresize}}
263263\end{figure}
264264
265\dothis{Delete the cell by clicking on the \ct{x} in the pink handle.}
265\dothis{Remova a célula clicando no \foreign{handler} \ct{x} rosa.}
266266
267267
268268%=================================================================
269\section{Defining the class SBEGame}
269\section{Definindo a classe SBEGame}
270270
271Now let's create the other class that we need for the game, which we will call \clsind{SBEGame}.
271Agora vamos criar a outra classe que precisamos para o nosso jogo, a qual chamaremos de \clsind{SBEGame}.
272272
273\dothis{Make the class definition template visible in the browser main window.}
274Do this by clicking twice on the name of the already-selected class category, or by displaying the definition of \ct{SBECell} again (by clicking the \button{instance} button.)
275Edit the code so that it reads as follows, and \menu{accept} it.
273\dothis{Torne visível o modelo de definição de classe na janela principal do \foreign{browser}.}
274Faça isso clicando duas vezes no nome de uma categoria de classe já selecionada, ou exibindo a definição de \ct{SBECell} novamente (clicando no botão \button{instance}.)
275Modifique o código de modo que ele fique igual ao que segue, e acione o menu \menu{accept}.
276276
277277\needlines{6}
278\begin{classdef}[sbegame]{Defining the \ct{SBEGame} class}
278\begin{classdef}[sbegame]{Definindo a classe \ct{SBEGame}}
279279BorderedMorph subclass: #SBEGame
280280 instanceVariableNames: ''
281281 classVariableNames: ''
283283 category: 'SBE-Quinto'
284284\end{classdef}
285285
286Here we subclass \clsind{BorderedMorph}; \clsind{Morph} is the superclass of all of the graphical shapes in \squeak, and (surprise!) a \ct{BorderedMorph} is a \ct{Morph} with a border.
287We could also insert the names of the instance variables between the quotes on the second line, but for now, let's just leave that list empty.
286Aqui nós criamos uma subclasse \clsind{BorderedMorph}; \clsind{Morph} é a superclasse de todas as formas gráficas no \squeak e (surpresa!) um \ct{BorderedMorph} é um \ct{Morph} com uma borda.
287Nós podemos também inserir os nomes das variáveis de instância entre os caracteres de aspas simples na segunda linha, mas por enquanto, vamos deixar esta lista vazia.
288288
289Now let's define an \mthind{SBEGame}{initialize} method for \ct{SBEGame}.
289Agora vamos definir um método \mthind{SBEGame}{initialize} para \ct{SBEGame}.
290290
291\dothis{Type the following into the browser as a method for \ct{SBEGame} and try to \menu{accept} it:}
291\dothis{Digite o texto a seguir no \foreign{browser} como um método para \ct{SBEGame} e tente clicar no menu \menu{accept}:}
292292
293\begin{numMethod}[sbegameinitialize]{Initializing the game}
293\begin{numMethod}[sbegameinitialize]{Inicializando o jogo}
294294initialize
295295 | sampleCell width height n |
296296 super initialize.
305305%\sd{it would be nicer if we would not have to create an instance of SBECell for nothing}
306306%\on{yes}
307307
308\squeak will complain that it doesn't know the meaning of some of the terms.
309\squeak tells you that it doesn't know of a message \ct{cellsPerSide}, and suggests a number of corrections, in case it was a spelling mistake.
310
308O \squeak irá dizer que não sabe o significado de alguns dos termos.
309O \squeak diz a você que ele não conhece a mensagem \ct{cellsPerSide}, e sugere algumas correções caso você tenha cometido um erro de digitação.
311310
312311\begin{figure}[htb]
313312\begin{minipage}{0.34\textwidth}
314314 \ifluluelse
315315 {\includegraphics[width=\textwidth]{UnknownSelector}}
316316 {\includegraphics[scale=0.7]{UnknownSelector}}
317 \caption{\squeak detecting an unknown selector.\label{fig:unknownSelector}}
317 \caption{\squeak detectando um seletor desconhecido.\label{fig:unknownSelector}}
318318\end{minipage}
319319\hfill
320320\begin{minipage}{0.64\textwidth}
322322 \ifluluelse
323323 {\includegraphics[width=\textwidth]{DeclareInstanceVar}}
324324 {\includegraphics[scale=0.7]{DeclareInstanceVar}}
325 \caption{Declaring a new instance variable.\label{fig:declareInstance}}
325 \caption{Declarando uma nova variável de instância.\label{fig:declareInstance}}
326326\end{minipage}
327327\end{figure}
328328
329But \ct{cellsPerSide} is not a mistake\,---\,it is just a method that we haven't yet defined\,---\,we will do so in a minute or two.
329Entretanto, \ct{cellsPerSide} não é um erro de digitação\,---\,é apenas um método que nós ainda não definimos\,---\,coisa que faremos dentro de alguns minutos.
330330
331\dothis{So just select the first item from the menu, which confirms that we really meant \ct{cellsPerSide}.}
331\dothis{Selecione o primeiro item do menu, indicando que nossa intenção foi realmente digitar \ct{cellsPerSide}.}
332332
333Next, \squeak will complain that it doesn't know the meaning of \ct{cells}. It offers you a number of ways of fixing this.
333Agora, o \squeak irá dizer que não sabe o significado de \ct{cells}. Ele exibe algumas formas de se resolver o problema.
334334
335\dothis{Choose \menu{declare instance} because we want \ct{cells} to be an instance variable.}
336Finally, \squeak will complain about the message \ct{newCellAt:at:} sent on the last line; this is also not a mistake, so confirm that message too.
337\index{on the fly variable definition}
338\index{instance variable definition}
335\dothis{Escolha o menu \menu{declare instance} porque nós queremos que \ct{cells} seja uma variável de instância.}
339336
340If you now look at the class definition once again (which you can do by clicking on the \button{instance} button), you will see that the browser has modified it to include the instance variable \ct{cells}.
337Finalmente, o \squeak irá reclamar da mensagem \ct{newCellAt:at:} enviada na última linha; este também não é um erro, portanto confirme tal mensagem.
338\index{definição dinâmica de variáveis}
339\index{definição de variáveis de instância}
341340
342Let's look at this \ct{initialize} method.
343The line \ct{| sampleCell width height n |} declares 4 temporary variables. They are called temporary variables because their scope and lifetime are limited to this method. Temporary variables with explanatory names are helpful in making code more readable. Smalltalk has no special syntax to distinguish constants and variables, and in fact all four of these ``variables'' are really constants.
344Lines 4--7 define these constants.
341Se você olhar novamente para a definição da classe (o que pode ser feito clicando no botão \button{instance}), você verá que o \foreign{browser} a modificou para incluir a variável de instância \ct{cells}.
345342
346How big should our game board be? Big enough to hold some integral number of cells, and big enough to draw a border around them.
347How many cells is the right number? 5? 10? 100? We don't know yet, and if we did, we would probably change our minds later. So we delegate the responsibility for knowing that number to another method, which we will call \ct{cellsPerSide}, and which we will write in a minute or two.
348It's because we are sending the \ct{cellsPerSide} message before we define a method with that name that \squeak asked us to ``confirm, correct, or cancel'' when we accepted the method body for \ct{initialize}.
349Don't be put off by this: it is actually good practice to write in terms of other methods that we haven't yet defined.
350Why? Well, it wasn't until we started writing the \ct{initialize} method that we realized that we needed it, and at that point, we can give it a meaningful name, and move on, without interrupting our flow.
343Vamos dar uma olhada neste método \ct{initialize}.
344A linha \ct{| sampleCell width height n |} declara quatro variáveis \emph{temporárias}. Elas são chamadas de variáveis temporárias porque seu escopo e tempo de vida é limitado a este método. Variáveis temporárias com nomes explicativos são úteis para tornar o código mais legível. \st não possui uma forma de diferenciar constantes de variáveis, e na verdade todas essas quatro ``variáveis'' são na verdade constantes.
345As linhas 4--7 definem essas constantes.
346
347Qual tamanho deve ter o tabuleiro do nosso jogo? Ele deve ser grande o bastante para conter um número integral de células e desenhar uma borda ao redor delas.
348Qual seria o número certo de células? 5? 10? 100? Nós ainda não sabemos, e mesmo se soubéssemos, nós provavelmente mudaríamos de idéia mais tarde. Portanto nós delegamos a responsabilidade de saber esse número a outro método, que chamamos de \ct{cellsPerSide}, que será escrito dentro de alguns momentos.
349
350Porque estamos enviando a mensagem \ct{cellsPerSide} antes de definirmos um método com este nome que o \squeak nos pediu para escolher entre opções ``confirm, correct, or cancel'', quando nós tentamos salvar o método \ct{initialize}.
351
352Não se preocupe com isso: na verdade é uma boa prática escrever código em termos de métodos que ainda não foram definidos.
353Por que? Bem, não foi antes de escrevermos o método \ct{initialize} que percebemos que precisaríamos de tal método, e neste ponto, nós podemos dar a ele um nome expressivo e seguir adiante, sem interromper o nosso fluxo.
351354
352The fourth line uses this method:
353the Smalltalk \ct{self cellsPerSide} sends the message \ct{cellsPerSide} to \pvind{self}, i.e., to this very object.
354The response, which will be the number of cells per side of the game board, is assigned to \ct{n}.
355A quarta linha usa este método:
356a instrução \st \ct{self cellsPerSide} envia a mensagem \ct{cellsPerSide} a \pvind{self}, \ie a este mesmo objeto.
357A resposta, que será o número de células por lado do tabuleiro, é atribuída a \ct{n}.
355358
356The next three lines create a new \ct{SBECell} object, and assign its width and height to the appropriate temporary variables.
359As três linhas seguintes criam um novo objeto \ct{SBECell}, e atribuem sua altura e comprimento às variáveis temporárias apropriadas.
357360
358361%The eighth line sends the message \ct{bounds:} to \self.
359362%\ct{bounds:} is a method that we inherit from our superclass; it is used to define the space on the screen that this Morph will occupy.
360363%The single colon (\ct{:}) at the end of the name says that \ct{bounds:} expects a single parameter, which should be a rectangle object.
361Line 8 sets the \ct{bounds} of the new object.
362Without worrying too much about the details just yet, just believe us that the expression in parentheses creates a square with its origin (\ie its top-left corner) at the point (5,5) and its bottom-right corner far enough away to allow space for the right number of cells.
364A linha 8 define o atributo \ct{bounds} do novo objeto.
365Não fique muito preocupado com relação aos detalhes por enquanto, apenas acredite que a expressão entre parênteses cria um quadrado com origem (\ie canto superior esquerdo) no ponto (5,5) e canto inferior direito longe o bastante para criar uma área capaz de abrigar o número correto de células.
363366
364The last line sets the \ct{SBEGame} object's instance variable \ct{cells} to a newly created \clsind{Matrix} with the right number of rows and columns. We do this by sending the message \ct{new:tabulate:} to the \ct{Matrix} class (classes are objects too, so we can send them messages). We know that \mthind{Matrix class}{new:tabulate:} takes two arguments because it has two colons (\ct{:}) in its name. The arguments go right after the colons.
365If you are used to languages that put all of the arguments together inside parentheses, this may seem weird at first. Don't panic, it's only syntax!
366It turns out to be a very good syntax because the name of the method can be used to explain the roles of the arguments. For example, it is pretty clear that \ct{Matrix rows: 5 columns: 2} has 5 rows and 2 columns, and not 2 rows and 5 columns.
367\cmindex{Matrix class}{rows:columns:}
367A última linha atribui à variável de instância \ct{cells} do objeto \ct{SBEGame} um novo objeto \clsind{Matrix} com o número correto de linhas e colunas. Isso é feito enviando a mensagem \ct{new:tabulate:} para a classe \ct{Matrix} (classes também são objetos, então nós podemos enviar mensagens a elas). Nós sabemos que \mthind{classe Matrix}{new:tabulate:} aceita dois argumentos por causa da existência de dois caracteres de \emph{dois pontos} em seu nome. Os argumentos vão logo após esses caracteres.
368Se você está acostumado a linguagens que agrupam todos os argumentos dentro de parênteses, isso pode parecer esquisito num primeiro momento. Não entre em pânico, isso é apenas sintaxe!
369Acontece que essa sintaxe é boa porque o nome do método pode ser usado para explicar o papel dos argumentos. Por exemplo, fica evidente que \ct{Matrix rows: 5 columns: 2} possui 5 linhas e 2 colunas, e não 2 linhas e 5 colunas.
370\cmindex{classe Matrix}{rows:columns:}
368371
369\ct{Matrix new: n tabulate: [ :i :j | self newCellAt: i at: j ]} creates a new \ct{n}{$\times$}\ct{n} matrix and initializes its elements. The initial value of each element will depend on its coordinates. The \ct{(i,j)}\textsuperscript{th} element will be initialized to the result of evaluating \ct{self newCellAt: i at: j}.
372\ct{Matrix new: n tabulate: [ :i :j | self newCellAt: i at: j ]} cria uma nova matriz \ct{n}{$\times$}\ct{n} e inicializa seus elementos. O valor inicial de cada elemento irá depender das suas coordenadas. O elemento \ct{(i,j)}\textsuperscript{th} será inicializado com o valor resultante da expressão \ct{self newCellAt: i at: j}.
370373
371That's \ct{initialize}. When you accept this message body, you might want to take the opportunity to pretty-up the formatting. You don't have to do this by hand: from the the yellow-button menu select \menu{more \ldots \go prettyprint}, and the browser will do it for you\damien{this didn't do anything to me}. You have to \menu{accept} again after you have \subind{method}{pretty-print}{}ed a method, or of course you can \subind{keyboard shortcut}{cancel}
372(\short{l}\,---\,that's a lower-case letter \emph{L}) if you don't like the result.
373Alternatively, you can set up the browser to use the pretty-printer automatically whenever it shows you code: use the the right-most button in the button bar to adjust the view.
374\seeindex{pretty-print}{method}
374Este é o \ct{initialize}. Quando você salva este método, você pode querer aproveitar a oportunidade para executar um \foreign{pretty-print} (endentar o código). Você não precisa fazer isso manualmente: através do menu do botão amarelo selecione o menu \menu{more \ldots \go prettyprint}, e o \foreign{browser} fará a endentação para você\damien{this didn't do anything to me}. Você deve selecionar o menu \menu{accept} novamente depois de executar o \foreign{\subind{método}{pretty-print}} no método, ou se for o caso você pode \subind{atalho de teclado}{cancelar} as modificações.
375(\short{l}\,---\,esta é a letra \emph{L} minúscula) se você não gostar do resultado.
376Por outro lado, você pode configurar o \foreign{browser} para endentar o código automaticamente antes de mostrá-lo: para isso use botão mais a direita da barra de botões.
377\seeindex{pretty-print}{método}
375378
376If you find yourself using \menu{more\,\ldots} a lot, it's useful to know that you can hold down the {\sc shift} key when you click to directly bring up the \menu{more \ldots} menu.
379Se você se pegar usando muito o menu \menu{more\,\ldots}, é bom saber que você pode mostrar o menu \menu{more \ldots} diretamente se você segurar a tecla {\sc shift} enquanto clica.
377380
378381%=================================================================
379\section{Organizing methods into protocols}
382\section{Organizando métodos em protocolos}
380383
381Before we define any more methods, let's take a quick look at the third pane at the top of the browser.
382In the same way that the first pane of the browser lets us categorize classes so we are not overwhelmed by a very long list of class names in the second pane, so the third pane lets us categorize methods so that we are not overwhelmed by a very long list of method names in the fourth pane.
383These categories of methods are called ``protocols''.
384\index{protocol}
384Antes de definirmos quaisquer outros métodos, vamos dar uma olhada rápida no terceiro painel situado na parte superior do \foreign{browser}.
385Da mesma forma que o primeiro painel do \foreign{browser} nos permite categorizar classes e evitar a exibição de uma lista enorme de nomes de classes no segundo painel, o terceiro painel serve para que possamos categorizar métodos e evitar a exibição de uma lista enorme de nomes de métodos no quarto painel.
386Estas categorias de métodos são chamadas de ``protocolos''.
387\index{protocolo}
385388
386If there are only a few methods in a class, the extra level of hierarchy provided by protocols is not really necessary.
387This is why the browser also offers us the \prot{-{}-all-{}-} virtual protocol, which, you will not be surprised to learn, contains all of the methods in the class.
389Se existem apenas alguns métodos numa classe, o nível extra de hierarquia fornecido pelos protocolos não é realmente necessário.
390É por isso que o \foreign{browser} também nos fornece um protocolo virtual \prot{-{}-all-{}-} que contém todos nos métodos da classe.
388391\protindex{all}
389392
390393\begin{figure}[htbp]
391394 \centering
392395 \includegraphics[scale=0.7]{Categorize}
393 \caption{Categorize all uncategorized methods.\label{fig:categorize}}
396 \caption{Categorize todos os métodos não categorizados.\label{fig:categorize}}
394397\end{figure}
395398
396If you have followed along with this example, the third pane may well contain the protocol \protind{as yet unclassified}.
399Se você está acompanhando este exemplo, o terceiro painel pode conter o protocolo \protind{as yet unclassified}.
397400
398\dothis{Select the \ind{yellow button} menu item \menu{categorize all uncategorized} to fix this, and move the \ct{initialize} methods to a new protocol called \protind{initialization}.}
399How does \squeak{} know that this is the right protocol? Well, in general \squeak{} can't know, but in this case there is also an \ct{initialize} method in a superclass, and \squeak assumes that our \ct{initialize} method should go in the same category as the one that it overrides.
400\index{method!categorize}
401\dothis{Selecione o menu \menu{categorize all uncategorized} situado no menu do \ind{botão amarelo} para corrigir isso, e mova o método \ct{initialize} para um novo protocolo chamado \protind{initialization}.}
402Como o \squeak sabe que este é o protocolo correto? Bem, de um modo geral o \squeak não sabe, mas neste caso também existe um método \ct{initialize} na superclasse, e \squeak assume que o nosso método \ct{initialize} deve ser colocado na mesma categoria que o método da superclasse.
403\index{método!categorizar}
401404
402You may find that \squeak has already put your \ct{initialize} method into the \protind{initialization} protocol.
403If so, it's probably because you have loaded a package called \ct{AutomaticMethodCategorizer} into your image.
405Pode ser que o \squeak tenha colocado o nosso método \ct{initialize} no protocolo \protind{initialization}.
406Se isso ocorreu, provavelmente foi porque você deve ter carregado na sua imagem um pacote chamado \ct{AutomaticMethodCategorizer}.
404407
405\paragraph{A typographic convention.} Smalltalkers frequently use the notation ``\verb|>>|'' to identify the class to which a method belongs, so, for example, the \ct{cellsPerSide} method in class \ct{SBEGame} would be referred to as \ct{SBEGame>>cellsPerSide}.
406To indicate that this is \emph{not} \st syntax, we will use the special symbol \ct{>>>} instead, so this method will appear in the text as \ct{SBEGame>>>cellsPerSide}
408\paragraph{Uma convenção tipográfica.} Programadores \st frequentemente usam a notação ``\verb|>>|'' para identificar a classe na qual um método está inserido, portanto, por exemplo, o método \ct{cellsPerSide} na classe \ct{SBEGame} seria referenciado como \ct{SBEGame>>cellsPerSide}.
409Para indicar que essa \emph{não} é uma sintaxe \st, nós usaremos o símbolo especial \ct{>>>} em seu lugar, portanto este método aparecerá no texto como \ct{SBEGame>>>cellsPerSide}
407410\cmindex{Behavior}{>>}
408411
409From now on, when we show a method in this book, we will write the name of the method in this form. Of course, when you actually type the code into the browser, you don't have to type the class name or the \ct{>>>}; instead, you just make sure that the appropriate class is selected in the class pane.
412De agora em diante, quando nós mostrarmos um método neste livro, nós iremos escrever seu nome nesta forma. É claro, quando você de fato digita o código no \foreign{browser}, você não precisa digitar o nome da classe ou o \ct{>>>}; em vez disso, apenas tenha certeza de que a classe apropriada esteja selecionada no painel de classes do \foreign{browser}.
410413
411Now let's define the other two methods that are used by the \ct{SBEGame>>>initialize} method. Both of them can go in the \prot{initialization} protocol.
414Agora vamos definir os outros dois métodos que serão usados pelo método \ct{SBEGame>>>initialize}. Ambos os métodos podem ser colocados dentro do protocolo \prot{initialization}.
412415
413\begin{method}[sbegamecellsperside]{A constant method.}
416\begin{method}[sbegamecellsperside]{Um método constante.}
414417SBEGame>>>cellsPerSide
415 "The number of cells along each side of the game"
418 "Numero de celulas em cada um dos lados do tabuleiro"
416419 ^ 10
417420\end{method}
418421\cmindex{SBEGame}{cellsPerSide}
419\index{constant methods}
422\index{métodos constantes}
420423
421This method could hardly be simpler: it answers the constant 10. One advantage of representing constants as methods is that if the program evolves so that the constant then depends on some other features, the method can be changed to calculate this value.
424Este método dificilmente poderia ser mais simples: ele responde com a constante 10. Uma vantagem de representar constantes como métodos é que se o programa evoluir de modo que as contantes dependam de outras partes, o método pode ser modificado para calcular o novo valor.
422425
423426\needlines{10}
424\begin{method}[newCellAt:at:]{An initialization helper method}
427\begin{method}[newCellAt:at:]{Um método auxiliar de inicialização}
425428SBEGame>>>newCellAt: i at: j
426 "Create a cell for position (i,j) and add it to my on-screen
427 representation at the appropriate screen position. Answer the new cell"
429 "Cria uma celula para a posicao (i,j) e a insere na minha representacao
430 em tela na posicao apropriada da tela. Responde com a nova celula"
428431 | c origin |
429432 c := SBECell new.
430433 origin := self innerBounds origin.
438438\cmindex{SBEGame}{newCellAt:at:}
439439% ^ c "omit this final line to create a bug"
440440
441\dothis{Add the methods \ct{SBEGame>>>cellsPerSide} and \ct{SBEGame>>>newCellAt:at:}.}
442Confirm the spelling of the new selectors \ct{toggleNeighboursOfCellAt:at:} and \ct{mouseAction:}.
441\dothis{Adicione os métodos \ct{SBEGame>>>cellsPerSide} e \ct{SBEGame>>>newCellAt:at:}.}
442Verifique a digitação dos novos seletores \ct{toggleNeighboursOfCellAt:at:} e \ct{mouseAction:}.
443443
444\Mthref{newCellAt:at:} answers a new SBECell, specialized to position \ct{(i, j)} in the \clsind{Matrix} of cells.
445The last line defines the new cell's \ct{mouseAction} to be the \emph{block}
444O \Mthref{newCellAt:at:} responde com um novo objeto \ct{SBECell}, situado na posição \ct{(i, j)} do objeto \clsind{Matrix} que representa as células.
445A última linha define o \ct{mouseAction} da célula para ser o \emph{bloco}
446446\mbox{\lct{[self toggleNeighboursOfCellAt: i at: j ]}.}
447 In effect, this defines the callback behaviour to perform when the mouse is clicked.
448The corresponding method also needs to be defined.
447 Isso define o comportamento a ser executado quando o mouse é clicado (método de \foreign{callback}).
448O método correspondente também precisa ser definido.
449449
450\begin{method}[toggleNeighboursOfCellAt:at:]{The callback method}
450\begin{method}[toggleNeighboursOfCellAt:at:]{O método de \foreign{callback}}
451451SBEGame>>>toggleNeighboursOfCellAt: i at: j
452452 (i > 1) ifTrue: [ (cells at: i - 1 at: j ) toggleState].
453453 (i < self cellsPerSide) ifTrue: [ (cells at: i + 1 at: j) toggleState].
456456\end{method}
457457\cmindex{SBEGame}{toggleNeighboursOfCellAt:at:}
458458
459\Mthref{toggleNeighboursOfCellAt:at:} toggles the state of the four cells to the north, south, west and east of cell (\ct{i}, \ct{j}). The only complication is that the board is finite, so we have to make sure that a neighboring cell exists before we toggle its state.
459O \Mthref{toggleNeighboursOfCellAt:at:} alterna o estado das quatro células norte, sul, leste e oeste da célula (\ct{i}, \ct{j}). A única complicação é que o tabuleiro é finito, portanto nós precisamos nos certificar que as células vizinhas existem antes de alternarmos seus estados.
460460
461\dothis{Place this method in a new protocol called \prot{game logic}.\damien{this has to be explained. There were no explications before on how to create a new protocol.}}
462To move the method, you can simply click on its name and drag it to the newly-created protocol (\figref{dragMethod}).
461\dothis{Coloque este método em um novo protocolo chamado \prot{game logic}.\damien{this has to be explained. There were no explications before on how to create a new protocol.}}
462