Ir ao conteúdo
  • Cadastre-se

Ajuda em Pascal - Jogo da Velha


Posts recomendados

Pessoal sou novo em programação e estou tentando fazer um jogo da velha com que o usuário jogue contra a máquina mas ainda não consegui implementar certas funções. Não consegui com que a máquina receba o simbolo diferente do que o usuário escolheu como por exemplo o usuario escolheu 'o' e a máquina deve receber 'x' e vice versa. Ai no código acabei colocando como se o jogador sempre escolhesse x... Em relação a escolha dos níveis (fácil, médio e difícil) por enquanto só implementei o fácil com um random(9). Não consegui fazer com que a jogada da máquina apareça no tabuleiro com um random(9). E também a verificação de quando houver um ganhador. A procedure que será a que a máquina irá utilizar para fazer sua jogada será a base_f. Se alguém puder me ajudar ou puder me mostrar o caminho de como fazer isso eu agradeço! Obrigado!
 

Program JogodaVelha; Uses crt;  var  i,j,k,l,mov,aux,aux_1: integer; simb,simb_2: char; tabuleiro : array[1..3, 1..3] of char; ok : boolean; jog : array[1..9] of integer;  procedure jogada_ok; begin if tabuleiro[j,k] = '' then  ok:= true else ok:= false;  if ok = false then  random(9);  jogada_ok();end;	   procedure base_f(); begin  simb_2 := 'o';  aux:= random(9);            if (aux = 1) or (aux_1 = 1) then				 begin				   if tabuleiro[1,1] = '' then					  begin 				    tabuleiro[1,1] := simb_2;				    end				   else begin 					          repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = ''); 								end;							      	 end;				 		if (aux = 2) or (aux_1 = 2) then				 begin				   if tabuleiro[1,2] = '' then					  begin 				    tabuleiro[1,2] := simb_2;				    end				 else begin 					            repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;							      				      	 end;				 		if (aux = 3) or (aux_1 = 3) then				 begin				   if tabuleiro[1,3] = '' then					  begin 				    tabuleiro[1,3] := simb_2;				    				 end				 else begin repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;							      				      	end;				 		if (aux = 4) or (aux_1 = 4) then				 begin				   if tabuleiro[2,1] = '' then					  begin 				    tabuleiro[2,1] := simb_2;				    				 end				 else  begin repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;							     				      	end;				 				 		if (aux = 5) or (aux_1 = 5) then				 begin				   if tabuleiro[2,2] = '' then					  begin 				    tabuleiro[2,2] := simb_2;				    				 end				 else begin repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;							      	end;				 				 		if (aux = 6) or (aux_1 = 6) then				 begin				   if tabuleiro[2,3] = '' then					  begin 				    tabuleiro[2,3] := simb_2;				    				 end				 else begin repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;				end;				 	if (aux = 7) or (aux_1 = 7) then				 begin				   if tabuleiro[3,1] = '' then					  begin 				    tabuleiro[3,1] := simb_2;				    				 end				 else begin repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;							      	end;				 	if (aux = 8) or (aux_1 = 8) then				 begin				   if tabuleiro[3,2] = '' then					  begin 				    tabuleiro[3,2] := simb_2;				    ok:= true				 end				 else begin repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;							      	end;				 		if (aux = 9) or (aux_1 = 9) then				 begin				   if tabuleiro[3,3] = '' then					  begin 				    tabuleiro[3,3] := simb_2;				   				 end				 else  begin repeat 										 aux_1:= random(9);				             until (tabuleiro[j,k] = '');								end;							       				      	end;    end;  procedure vencer; begin  if tabuleiro[j,k] <> ' ' then begin    if (tabuleiro[1,1] = tabuleiro[1,2]) and (tabuleiro[1,2] = tabuleiro[1,3]) then begin  writeln('Vencedor');     end;     if (tabuleiro[2,1] = tabuleiro[1,2]) and (tabuleiro[2,2] = tabuleiro[2,3]) then begin  writeln('Vencedor');    end;  if (tabuleiro[3,1] = tabuleiro[3,2]) and (tabuleiro[3,2] = tabuleiro[3,3]) then begin  writeln('Vencedor');  readkey;   end;  if (tabuleiro[1,1] = tabuleiro[2,1]) and (tabuleiro[2,1] = tabuleiro[3,1]) then begin  writeln('Vencedor');    end;   if (tabuleiro[1,2] = tabuleiro[2,2]) and (tabuleiro[2,2] = tabuleiro[3,2]) then  begin   writeln('Vencedor');       end;   if (tabuleiro[1,3] = tabuleiro[2,3]) and (tabuleiro[2,3] = tabuleiro[3,3]) then  begin   writeln('Vencedor');       end;   if (tabuleiro[1,1] = tabuleiro[2,2]) and (tabuleiro[2,2] = tabuleiro[3,3]) then  begin   writeln('Vencedor');       end;   if (tabuleiro[1,3] = tabuleiro[2,2]) and (tabuleiro[2,2] = tabuleiro[3,1]) then  begin   writeln('Vencedor');      end; end;  end;  procedure jogada(); begin     		for l:= 1 to 1 do 		begin				   		 writeln('Jogador escolha um campo para jogar');      readln(jog[l]);            if simb  = 'x' then      begin			   if jog[l] = 1 then 			   begin				    tabuleiro[1,1] := 'x';						ok:= true					end					 else ok:= false;					 	 				 if jog[l] = 2 then				 begin 				    tabuleiro[1,2] := 'x';				    ok:= true				 end				 else ok:= false;				    				 if jog[l] = 3 then				 begin 				    tabuleiro[1,3] := 'x';				    ok:= true				 end				 else ok:= false;				 				 if jog[l] = 4 then				 begin 				    tabuleiro[2,1] := 'x';				    ok:= true				 end				 else ok:= false;				 				 if jog[l] = 5 then				 begin 				    tabuleiro[2,2] := 'x';				    ok:= true				 end				 else ok:= false;				 				 if jog[l] = 6 then				 begin 				    tabuleiro[2,3] := 'x';				    ok:= true				 end				 else ok:= false;				 				 if jog[l] = 7 then				 begin 				    tabuleiro[3,1] := 'x';				    ok:= true				 end				 else ok:= false;				 				 if jog[l] = 8 then				 begin 				    tabuleiro[3,2] := 'x';				    ok:= true				 end				 else ok:= false;				 				 if jog[l] = 9 then				 begin 				    tabuleiro[3,3] := 'x';				    ok:= true				 end				 else ok:= false;		end;		 			 						  if simb  = 'o' then      begin				 if jog[l] = 1 then				 begin 				    tabuleiro[1,1] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 2 then				 begin 				    tabuleiro[1,2] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 3 then				 begin 				    tabuleiro[1,3] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 4 then				 begin 				    tabuleiro[2,1] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 5 then				 begin 				    tabuleiro[2,2] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 6 then				 begin 				    tabuleiro[2,3] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 7 then				 begin 				    tabuleiro[3,1] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 8 then				 begin 				    tabuleiro[3,2] := 'o';						ok:= true				 end				 else ok:= false;				 				 if jog[l] = 9 then				 begin 				    tabuleiro[3,3] := 'o';						ok:= true				 end				 else ok:= false;			end;					end;		 	  end;				procedure des_tab();begin      writeln(tabuleiro[1, 1], ' | ', tabuleiro[1, 2], ' | ', tabuleiro[1, 3]);      writeln('-------------');      writeln(tabuleiro[2, 1], ' | ', tabuleiro[2, 2], ' | ', tabuleiro[2, 3]);      writeln('-------------');      writeln(tabuleiro[3, 1], ' | ', tabuleiro[3, 2], ' | ', tabuleiro[3, 3]);      			end;		          Begin writeln('Escolha o nível de dificuldade: 1- Fácil, 2- Médio, 3- Díficil');   readln(i);      if i=1 then   writeln('Nível fácil selecionado');      if i=2 then   writeln('Nível media selecionado');      if i=3 then   writeln('Nível difícil selecionado');      writeln('Selecione o símbolo para começar: x ou o');   readln(simb);        if simb = 'x' then       writeln('Você escolheu x');        if simb = 'o' then       writeln('Você escolheu o');       readkey;       for j := 1 to 3 do   begin      for k := 1 to 3 do      begin         tabuleiro[j, k] := ' ';      end;   end;              clrscr;      writeln;      writeln('ATENCAO!!!');      writeln('Numeração de cada campo:                1|2|3                -----                4|5|6                -----                7|8|9 ');                                 jogada();      base_f();			des_tab();						jogada();			base_f();			writeln;			des_tab();									readkey;  				   		 				   			          End.
Link para o comentário
Compartilhar em outros sites

  • Membro VIP

Olá.

 

Creio que seu código não esteja tão simples... e de certo modo, a ideia em si do jogo da velha não é tão trivial... Mas vamos lá..

 

 

Tem vários pequenos detalhes que precisam ser verificados, por exemplo nessa procedure:

procedure jogada_ok;  begin  if tabuleiro[j,k] = '' then    ok:= true  else    ok:= false;  if ok = false then    random(9);  jogada_ok();  end;	

Na linha 9, você está chamando a própria procedure, ou seja, "uma recursividade". E essa recursividade está sem controle interno, logo, vai ficar chamando a si mesmo até "estourar a pilha".

 

Na linha 8, você está chamando um Random(), mas não está "aproveitado" o valor gerado. (não tem sentido sortear algo e não armazenar/utilizar).

 

 

 

Outro exemplo:

      repeat         aux_1:= random(9);      until (tabuleiro[j,k] = '');

Aqui, tem um laço de repetição,  e a condição para sair é fixa!!! ou seja, o valor que está em tabuleiro[j,k] não é alterado, logo, se o valor que estiver lá for diferente de '', vai ficar num loop infinito.

1) gera um número de 0 a 8, joga o valor em aux_1
2) verifica a sentença (tabuleiro[j,k] = ''), vai dar false, logo vai repetir, voltando pro passo 1...

 

E isso vai rolar INFINITAMENTE.

 

Por ai vai..

 

 

RESUMINDO

 

Tente fazer um código mais simples, e vá "melhorando aos poucos", em vez de tentar fazer algo "já pronto".

 

Minha sugestão:

 

"Fazer um programa que escreve as jogadas na tela entre dois jogadores humanos", ou seja, que simplesmente desenhe os "X" ou "O" nas suas respectivas posições... Nessa etapa NÃO precisa se preocupar com mais nada!!! (como verificar se já está preenchida, ou se é uma valor válido. Faça testes colocando valores válidos e pronto). Ai depois vai inserindo outras funcionalidades...

 

 

No aguardo.

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...