• Olá Visitante, se gosta do forum e pretende contribuir com um donativo para auxiliar nos encargos financeiros inerentes ao alojamento desta plataforma, pode encontrar mais informações sobre os várias formas disponíveis para o fazer no seguinte tópico: leia mais... O seu contributo é importante! Obrigado.

Programa Jogo_Rand

helldanger1

GForum VIP
Entrou
Ago 1, 2007
Mensagens
29,631
Gostos Recebidos
1
Agora vamos desenvolver um programa que simula um jogo. O programa conterá cinco componentes Label que permanecerão visíveis e terão seus valores (caracteres da tabela ASCII) alterados aleatoriamente, sempre que clicarmos o botão Apostar ou pressionarmos a tecla Enter com o foco em Apostar. Também teremos cinco componentes Edit que trabalharão da mesma forma, porém permanecerão invisíveis. Todas as vezes que um caracter de um componente Label coincidir com o caracter de um Edit qualquer, esse Edit tornar-se-á visível. Também, haverá uma alteração da imagem apresentada com a emissão de um Beep sonoro.



Inicie uma nova aplicação.



Coloque dois Button, cinco Label, cinco Edit, e dois Image no formulários, conforme a figura abaixo:


Cassino_html_ma55e8e7.gif



 

helldanger1

GForum VIP
Entrou
Ago 1, 2007
Mensagens
29,631
Gostos Recebidos
1
Vamos às propriedades:





Form1

BorderStyle = bsNone // retira a barra de títulos

Color = clOlive // cor do formulário



Button1

Caption = Apostar



Button2

Caption = Sair



Label (todos):

Alignment = taCenter // centraliza o conteúdo de Label

AutoSize = false // Label terá tamanho fixo

Caption = // deletar o que estiver em Caption

Color = chYellow // cor de Label

Obs. Em Font Escolha a fonte, seu tamanho e sua respectiva cor.



Edit (todos):

AutoSize = false

Visible = false

Obs. Em Font Escolha a fonte, seu tamanho e sua respectiva cor.



Image1:

Center = true // centraliza a imagem

Visible = false // inicialment Image1 não será visível

Obs. Escolha uma imagem.



Image2:

Center = true // centraliza a imagem

Visible = false // inicialmente Image2 não será visível

Obs. Escolha uma imagem.



Vamos aos códigos. O dois primeiros problemas a ser resolvidos são decorrentes de do fato de termos alterado a propriedade BorderStyle de Form1 para bsNone. Com isso retiramos a barra de títulos, o que impossibilita a uso da propriedade de arrastarmos o Form1, bem como a capacidade de encerrar o aplicativo diretamente nessa barra.
 

helldanger1

GForum VIP
Entrou
Ago 1, 2007
Mensagens
29,631
Gostos Recebidos
1
Encerrar o aplicativo não é difícil, basta implementarmos o método Close() no botão escolhido, no caso o Button2.





void __fastcall TForm1::Button2Click(TObject *Sender)

{

Close(); // encerra o programa

}



Agora, para podermos arrastar o formulário de um lado para o outro, só mesmo na base do código. Em Unit1.cpp, digite:



//--------------------------------------------------------------------------------

void __fastcall TForm1::WMNCHitTest(TMessage &Msg)

{

TForm::Dispatch(&Msg);

if (Msg.Result == HTCLIENT) Msg.Result = HTCAPTION;

}

//--------------------------------------------------------------------------------



Dê um clique em Unit1.cpp e pressiones as teclas Ctrl mais F6. Assim abriremos o Editor do arquivo de cabeçalho Unit1.h. Uma outra forma de abrir Unit1.h é darmos um clique com o botão direito do mouse sobre onde está escrito Unit1.cpp, na paleta do Editor, e escolhermos a primeira opção do menu PopUp que se abre (Open Sourse/Hearder File).



Com isso, nós acessamos a classe criadora de Form1. Quase no final do código escrito automaticamente pelo compilador na classe Unit1.h, temos as partes privada (private) e pública (public) da classe:



private: // User declarations

public: // User declarations



Nós vamos digitar algumas linhas de código na parte pública.



Então, abaixo de:



"public: // User declarations"



digite:



void __fastcall WMNCHitTest(TMessage &Msg);

BEGIN_MESSAGE_MAP

MESSAGE_HANDLER(WM_NCHITTEST, TMessage, WMNCHitTest)

END_MESSAGE_MAP(TForm)



Pois bem, se executarmos o programa, já podemos arrastar o formulário para todos os lados, bem como encerrar o aplicativo.



Agora vamos digitar o código do botão Apostar. Não se assuste com o tamanho do código, pois na verdade tratam-se se conceitos básicos que, por certo, você entenderá com relativa facilidade, simplesmente prestando atenção no código e nos comentários:



//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)

{

Image1 -> Visible = true; // Image1 será visível quando clicarmos Button1

Image2 -> Visible = false; // Image2 não será visível quando clicarmos Button1



// Edit(s) (1, 2, 3, 4 e 5), em princípio, não serão visíveis

Edit1 -> Visible = false;

Edit2 -> Visible = false;

Edit3 -> Visible = false;

Edit4 -> Visible = false;

Edit5 -> Visible = false;



randomize(); /* melhora o método rand() dos Label(s) e Edit(s). Evita repetição dos valores cada vez que o programa é iniciado*/



/* Label(s) e Edit(s) terão seus valores (caracteres da tabela ASCII) alterados aleatoriamente pela função rand()*/

Label1 -> Caption = char (rand());

Label2 -> Caption = char (rand());

Label3 -> Caption = char (rand());

Label4 -> Caption = char (rand());

Label5 -> Caption = char (rand());

Edit1 -> Text = char (rand());

Edit2 -> Text = char (rand());

Edit3 -> Text = char (rand());

Edit4 -> Text = char (rand());

Edit5 -> Text = char (rand());



/* se a propriedade Caption de um Label qualquer for igual à propriedade Text de um Edit qualquer ... (continua no próximo comentário) ...*/

if ((Label1 -> Caption == Edit1 -> Text)||(Label1 -> Caption == Edit2 -> Text) ||

(Label1 -> Caption == Edit3 -> Text)||(Label1 -> Caption == Edit4 -> Text) ||

(Label1 -> Caption == Edit5 -> Text)||

(Label2 -> Caption == Edit1 -> Text)||(Label2 -> Caption == Edit2 -> Text) ||

(Label2 -> Caption == Edit3 -> Text)||(Label2 -> Caption == Edit4 -> Text) ||

(Label2 -> Caption == Edit5 -> Text)||

(Label3 -> Caption == Edit1 -> Text)||(Label3 -> Caption == Edit2 -> Text) ||

(Label3 -> Caption == Edit3 -> Text)||(Label3 -> Caption == Edit4 -> Text) ||

(Label3 -> Caption == Edit5 -> Text)||

(Label4 -> Caption == Edit1 -> Text)||(Label4 -> Caption == Edit2 -> Text) ||

(Label4 -> Caption == Edit3 -> Text)||(Label4 -> Caption == Edit4 -> Text) ||

(Label4 -> Caption == Edit5 -> Text)||

(Label5 -> Caption == Edit1 -> Text)||(Label5 -> Caption == Edit2 -> Text) ||

(Label5 -> Caption == Edit3 -> Text)||(Label5 -> Caption == Edit4 -> Text) ||

(Label5 -> Caption == Edit5 -> Text))

/* ... (continuação do comentário anterior) ... então, o programa ...*/

{

MessageBeep(0); /* ... imitirá um bip ... */

Image1 -> Visible = false; /* ... esconderá Image1 ... */

Image2 -> Visible = true; /* ... mostrará Image2.*/

} /* fim do primeiro if e do primeiro comentário fracionado*/



/* se a propriedade Caption de algum Label for igual a propriedade Text de Edit1, ... */

if ((Label1 -> Caption == Edit1 -> Text)||(Label2 -> Caption == Edit1 -> Text) ||

(Label3 -> Caption == Edit1 -> Text)||(Label4 -> Caption == Edit1 -> Text) ||

(Label5 -> Caption == Edit1 -> Text))

Edit1 -> Visible = true; /* ... então Edit1 será visível*/



/* se a propriedade Caption de algum Label for igual a propriedade Text de Edit2, ... */

if ((Label1 -> Caption == Edit2 -> Text)||(Label2 -> Caption == Edit2 -> Text) ||

(Label3 -> Caption == Edit2 -> Text)||(Label4 -> Caption == Edit2 -> Text) ||

(Label5 -> Caption == Edit2 -> Text))

Edit2 -> Visible = true; /* ... então Edit2 será visível*/





/* se a propriedade Caption de algum Label for igual a propriedade Text de Edit3, ... */

if ((Label1 -> Caption == Edit3 -> Text)||(Label2 -> Caption == Edit3 -> Text) ||

(Label3 -> Caption == Edit3 -> Text)||(Label4 -> Caption == Edit3 -> Text) ||

(Label5 -> Caption == Edit3 -> Text))

Edit3 -> Visible = true; /* ... então Edit3 será visível*/





/* se a propriedade Caption de algum Label for igual a propriedade Text de Edit4, ... */

if ((Label1 -> Caption == Edit4 -> Text)||(Label2 -> Caption == Edit4 -> Text) ||

(Label3 -> Caption == Edit4 -> Text)||(Label4 -> Caption == Edit4 -> Text) ||

(Label5 -> Caption == Edit4 -> Text))

Edit4 -> Visible = true; /* ... então Edit4 será visível*/





/* se a propriedade Caption de algum Label for igual a propriedade Text de Edit5, ... */

if ((Label1 -> Caption == Edit5 -> Text)||(Label2 -> Caption == Edit5 -> Text) ||

(Label3 -> Caption == Edit5 -> Text)||(Label4 -> Caption == Edit5 -> Text) ||

(Label5 -> Caption == Edit5 -> Text))

Edit5 -> Visible = true; /* ... então Edit5 será visível*/



}

//---------------------------------------------------------------------------



Pode rodar o programa.
 
Topo