henriques06

checkerslol

Dec 7th, 2024
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.20 KB | None | 0 0
  1. public class View {
  2.  
  3. Board board;
  4.  
  5. PositionTrace model;
  6.  
  7. int clickCounter=0;
  8.  
  9. Position primeiroClick = null;
  10.  
  11. int black=12;
  12.  
  13. int white=12;
  14.  
  15. int l=8;
  16.  
  17. int c=8;
  18.  
  19. boolean fj=false;
  20.  
  21. View(PositionTrace model) {
  22.  
  23. int x=0;
  24.  
  25. int y=0;
  26.  
  27.  
  28.  
  29. this.board = new Board("", 0, 0, 0);
  30.  
  31.  
  32. // Solicita dimensões e número de peças
  33.  
  34. x = board.promptInt("Qual é o nº de linhas/colunas do tabuleiro?");
  35.  
  36. y = board.promptInt("Qual é o nº de peças de cada cor no tabuleiro?");
  37.  
  38.  
  39.  
  40. if (y <= ((x * x) / 4)) {
  41.  
  42. l = x;
  43.  
  44. c = x;
  45.  
  46. black = y;
  47.  
  48. white = y;
  49.  
  50. }
  51.  
  52. if (y>(x*x)/4) {
  53.  
  54. l=8;
  55.  
  56. c=8;
  57.  
  58. black=12;
  59.  
  60. white=12;
  61.  
  62. }
  63.  
  64.  
  65. // Inicializa o modelo e o tabuleiro com as configurações obtidas
  66.  
  67. this.model = new PositionTrace(black, white, l, c);
  68.  
  69. this.board = new Board(quemJoga(), l, c, 60);
  70.  
  71.  
  72. board.setBackgroundProvider(this::background);
  73.  
  74. board.setIconProvider(this::icon);
  75.  
  76. board.addMouseListener(this::click);
  77.  
  78. board.addAction("Novo Jogo", this::action);
  79.  
  80. board.addAction("Aleatório", this::aleatorio);
  81.  
  82. board.addAction("Gravar", this::gravar);
  83.  
  84. board.addAction("Carregar", this::carregar);
  85.  
  86. board.setTitle(quemJoga());
  87.  
  88. }
  89.  
  90.  
  91. void gravar() {
  92.  
  93. String z = board.promptText("Qual é o nome do ficheiro a salvar?");
  94.  
  95. model.save(z);
  96.  
  97. }
  98.  
  99. void carregar(){
  100. String z = board.promptText("Qual é o nome do ficheiro a carregar?");
  101. if (z == null || z.isEmpty()) {
  102. return;
  103. }
  104. PositionTrace novoModel = new PositionTrace(model.blackCount, model.whiteCount, model.linha, model.coluna);
  105. Board novoTabuleiro = new Board(quemJoga(), novoModel.linha, novoModel.coluna, 60);
  106. novoTabuleiro.setBackgroundProvider(this::background);
  107. novoTabuleiro.setIconProvider(this::icon);
  108. novoTabuleiro.addMouseListener(this::click);
  109. novoTabuleiro.addAction("Novo Jogo", this::action);
  110. novoTabuleiro.addAction("Aleatório", this::aleatorio);
  111. novoTabuleiro.addAction("Gravar", this::gravar);
  112. novoTabuleiro.addAction("Carregar", this::carregar);
  113. novoModel.load(z);
  114. novoTabuleiro.setTitle(quemJoga());
  115. novoTabuleiro.open();
  116. board.refresh();
  117. }
  118.  
  119. void aleatorio() {
  120.  
  121. if(!fj) {
  122.  
  123. Position[] peçasAtuais = model.jogamBrancas ? model.positionWhities : model.positionBlackies;
  124.  
  125. Position[] origens = new Position[100];
  126.  
  127. Position[] destinos = new Position[100];
  128.  
  129. int contadorMovimentos = 0;
  130.  
  131. boolean peçaComDestinosValidos = false;
  132.  
  133. Position peçaEscolhida = null;
  134.  
  135. Position[] destinosValidos = new Position[100];
  136.  
  137. int numeroDestinosValidos = 0;
  138.  
  139. while (!peçaComDestinosValidos) {
  140.  
  141. // Escolher uma peça aleatória
  142.  
  143. int indicePeça = (int) (Math.random() * peçasAtuais.length);
  144.  
  145. peçaEscolhida = peçasAtuais[indicePeça];
  146.  
  147. numeroDestinosValidos = 0;
  148.  
  149. for (int i = 0; i < model.linha; i++) {
  150.  
  151. for (int j = 0; j < model.coluna; j++) {
  152.  
  153. Position destino = new Position(i, j);
  154.  
  155. if (model.éLegal(peçaEscolhida, destino) || model.tekirisse(peçaEscolhida, destino) != 0) {
  156.  
  157. // Se o movimento for válido, adiciona ao array de destinos válidos
  158.  
  159. destinosValidos[numeroDestinosValidos] = destino;
  160.  
  161. numeroDestinosValidos++;
  162.  
  163. }
  164.  
  165. }
  166.  
  167. }
  168.  
  169. if (numeroDestinosValidos > 0) {
  170.  
  171. peçaComDestinosValidos = true; // Há destinos válidos, podemos prosseguir com esse movimento
  172.  
  173. }
  174.  
  175. }
  176.  
  177. int indiceDestino = (int) (Math.random() * numeroDestinosValidos);
  178.  
  179. Position destinoAleatorio = destinosValidos[indiceDestino];
  180.  
  181. origens[contadorMovimentos] = new Position(peçaEscolhida.line(), peçaEscolhida.col());
  182.  
  183. destinos[contadorMovimentos] = destinoAleatorio;
  184.  
  185. contadorMovimentos++;
  186.  
  187. model.moveTopeça(peçaEscolhida, destinoAleatorio);
  188.  
  189. board.setTitle(quemJoga());
  190.  
  191. fimJogo();
  192.  
  193. }
  194.  
  195. }
  196.  
  197. String quemJoga() {
  198.  
  199. return model.jogamBrancas ? "Jogam as Brancas" : "Jogam as Pretas";
  200.  
  201. }
  202.  
  203. void start() {
  204.  
  205. fimJogo();
  206.  
  207. board.open();
  208.  
  209. }
  210.  
  211. void action() {
  212.  
  213. model = new PositionTrace(black, white, l, c);
  214.  
  215. board.setTitle(quemJoga());
  216.  
  217. fj=false;
  218.  
  219. fimJogo();
  220.  
  221. }
  222.  
  223.  
  224. String icon(int i, int j){
  225.  
  226. if (model.pretas(i, j))
  227.  
  228. return "black.png";
  229.  
  230. if (model.brancas(i,j))
  231.  
  232. return "white.png";
  233.  
  234. return null;
  235.  
  236. }
  237.  
  238. public static void main(String[] args) {
  239.  
  240. View gui = new View(new PositionTrace(12, 12, 8, 8)); // Valores padrão iniciais
  241.  
  242. gui.start();
  243.  
  244. }
  245.  
  246. Color background(int line, int col) {
  247.  
  248. Position currentPos = new Position(line, col);
  249.  
  250.  
  251. // Se a casa for a peça clicada, a cor será "LIME"
  252.  
  253. if (currentPos.equals(primeiroClick)) {
  254.  
  255. return StandardColor.LIME;
  256.  
  257. }
  258.  
  259. if (primeiroClick != null) {
  260.  
  261. if (model.tekirisse(primeiroClick, currentPos) != 0 || model.éLegal(primeiroClick, currentPos)) {
  262.  
  263. return StandardColor.YELLOW;
  264.  
  265. }
  266.  
  267. }
  268.  
  269. if ((line + col) % 2 == 0)
  270.  
  271. return StandardColor.WHITE;
  272.  
  273. return StandardColor.BLACK;
  274.  
  275. }
  276.  
  277. void click(int line, int col) {
  278.  
  279. Position clicked = new Position(line, col);
  280.  
  281.  
  282.  
  283. // Primeiro clique: Selecionar a peça
  284.  
  285. if (clickCounter == 0) {
  286.  
  287. if ((model.jogamBrancas && model.brancas(line, col)) || (!model.jogamBrancas && model.pretas(line, col))) {
  288.  
  289. primeiroClick = clicked;
  290.  
  291. clickCounter++;
  292.  
  293. }
  294.  
  295. }
  296.  
  297. // Segundo clique: Fazer o movimento
  298.  
  299. else if (clickCounter == 1) {
  300.  
  301. if (model.tekirisse(primeiroClick, clicked) != 0) {
  302.  
  303. model.capturamove(model.jogamBrancas ? model.positionWhities : model.positionBlackies, primeiroClick, clicked);
  304.  
  305. } else if (model.éLegal(primeiroClick, clicked)) {
  306.  
  307. model.moveTopeça(primeiroClick, clicked);
  308.  
  309. }
  310.  
  311.  
  312. // Resetar o clique
  313.  
  314. clickCounter = 0;
  315.  
  316. primeiroClick = null;
  317.  
  318.  
  319. // Atualizar título
  320.  
  321. board.setTitle(quemJoga());
  322.  
  323. fimJogo();
  324.  
  325. }
  326.  
  327. }
  328.  
  329. void fimJogo() {
  330.  
  331. Position[] peçasAtuais = model.jogamBrancas ? model.positionWhities : model.positionBlackies;
  332.  
  333. int jogadasPossiveis = 0;
  334.  
  335.  
  336. for (int i = 0; i < peçasAtuais.length; i++) {
  337.  
  338. Position peçaAtual = peçasAtuais[i];
  339.  
  340. if (model.posiçãoVálida(peçaAtual)) {
  341.  
  342. for (int li = -2; li <= 2; li++) {
  343.  
  344. for (int ci = -2; ci <= 2; ci++) {
  345.  
  346. Position destino = new Position(peçaAtual.line() + li, peçaAtual.col() + ci);
  347.  
  348. // Verifica se o movimento é válido ou há captura
  349.  
  350. if (model.éLegal(peçaAtual, destino) || model.tekirisse(peçaAtual, destino) != 0) {
  351.  
  352. jogadasPossiveis++;
  353.  
  354. }
  355.  
  356. }
  357.  
  358. }
  359.  
  360. }
  361.  
  362. }
  363.  
  364.  
  365. if (jogadasPossiveis == 0) { // Nenhuma jogada possível
  366.  
  367. if (model.whiteCount < model.blackCount) {
  368.  
  369. board.setTitle("Vitória das Pretas");
  370.  
  371. fj=true;
  372.  
  373. } else if (model.whiteCount > model.blackCount) {
  374.  
  375. board.setTitle("Vitória das Brancas");
  376.  
  377. fj=true;
  378.  
  379. } else if (model.whiteCount == model.blackCount){
  380.  
  381. board.setTitle("Empate");
  382.  
  383. fj=true;
  384.  
  385. }
  386.  
  387. }
  388.  
  389. }
  390.  
  391. }
  392. record Position(int line, int col) {
  393.  
  394. }
  395.  
  396. class PositionTrace {
  397.  
  398. boolean jogamBrancas = true;
  399.  
  400. Position[] positionBlackies;
  401.  
  402. Position[] positionWhities;
  403.  
  404. int blackCount = 12;
  405.  
  406. int whiteCount = 12;
  407.  
  408. int linha;
  409.  
  410. int coluna;
  411.  
  412. PositionTrace(int blackCount, int whiteCount, int linhas, int colunas) {
  413.  
  414. this.blackCount = blackCount;
  415.  
  416. this.whiteCount = whiteCount;
  417.  
  418. positionBlackies = new Position[blackCount];
  419.  
  420. positionWhities = new Position[whiteCount];
  421.  
  422. int peçablack = 0;
  423.  
  424. int peçawhite = 0;
  425.  
  426. linha=linhas;
  427.  
  428. coluna=colunas;
  429.  
  430.  
  431. // Colocar peças pretas no topo
  432.  
  433. for (int l = 0; l < linhas / 2 && peçablack < blackCount; l++) {
  434.  
  435. for (int c = 0; c < colunas && peçablack < blackCount; c++) {
  436.  
  437. if ((l + c) % 2 == 1) { // Casas escuras
  438.  
  439. positionBlackies[peçablack++] = new Position(l, c);
  440.  
  441. }
  442.  
  443. }
  444.  
  445. }
  446.  
  447.  
  448. // Colocar peças brancas na base
  449.  
  450. for (int l = linhas - 1; l >= linhas / 2 && peçawhite < whiteCount; l--) {
  451.  
  452. for (int c = colunas-1; c >=0 && peçawhite < whiteCount; c--) {
  453.  
  454. if ((l + c) % 2 == 1) { // Casas escuras
  455.  
  456. positionWhities[peçawhite++] = new Position(l, c);
  457.  
  458. }
  459.  
  460. }
  461.  
  462. }
  463.  
  464. }
  465.  
  466. boolean contém(Position[] positions, Position pos) {
  467.  
  468. for (int i = 0; i < positions.length; i++) {
  469.  
  470. Position p = positions[i];
  471.  
  472. if (p.equals(pos)) {
  473.  
  474. return true;
  475.  
  476. }
  477.  
  478. }
  479.  
  480. return false;
  481.  
  482. }
  483.  
  484. boolean pretas(int line, int col) {
  485.  
  486. return contém(positionBlackies, new Position(line, col));
  487.  
  488. }
  489.  
  490. boolean brancas(int line, int col) {
  491.  
  492. return contém(positionWhities, new Position(line, col));
  493.  
  494. }
  495.  
  496. void remover(Position[] positions, Position alvo) {
  497.  
  498. for (int i = 0; i < positions.length; i++) {
  499.  
  500. if (positions[i] != null && positions[i].equals(alvo)) {
  501.  
  502. positions[i] = new Position(-312,-123);
  503.  
  504. if (positions == positionBlackies) blackCount--;
  505.  
  506. if (positions == positionWhities) whiteCount--;
  507.  
  508. }
  509.  
  510. }
  511.  
  512. }
  513.  
  514. void capturamove(Position[] positions, Position inicial, Position alvo) {
  515.  
  516. int tekirisse = tekirisse(inicial, alvo);
  517.  
  518. Position meio = new Position((inicial.line() + alvo.line()) / 2, (inicial.col() + alvo.col()) / 2);
  519.  
  520.  
  521. if (tekirisse == 1 || tekirisse == 2) { // Captura pelas brancas
  522.  
  523. for (int i = 0; i < positionWhities.length; i++) {
  524.  
  525. if (positionWhities[i].equals(inicial)) {
  526.  
  527. positionWhities[i] = alvo;
  528.  
  529.  
  530. }
  531.  
  532. }
  533.  
  534. remover(positionBlackies, meio); // Remove a peça preta capturada
  535.  
  536. jogamBrancas = false;// mostra que é a vez das pretas
  537.  
  538. } else if (tekirisse == 3 || tekirisse == 4) { // Captura pelas pretas
  539.  
  540. for (int i = 0; i < positionBlackies.length; i++) {
  541.  
  542. if (positionBlackies[i].equals(inicial)) {
  543.  
  544. positionBlackies[i] = alvo;
  545.  
  546. }
  547.  
  548. }
  549.  
  550. remover(positionWhities, meio); // Remove a peça branca capturada
  551.  
  552. jogamBrancas = true;// mostra que é a vez das brancas
  553.  
  554. }
  555.  
  556. }
  557.  
  558. boolean estafora(Position a) {
  559.  
  560. return (a.line()>=linha||a.col()>=coluna||a.line()<0||a.col()<0);
  561.  
  562. }
  563.  
  564. boolean existeCapturaDisponivel() {
  565.  
  566. if (jogamBrancas) {
  567.  
  568. for (int i = 0; i < positionWhities.length; i++) { // Itera sobre as peças brancas
  569.  
  570. Position p = positionWhities[i];
  571.  
  572. Position destino1 = new Position(p.line() - 2, p.col() - 2);
  573.  
  574. Position destino2 = new Position(p.line() - 2, p.col() + 2);
  575.  
  576.  
  577. if (!estafora(destino1) && tekirisse(p, destino1) != 0) {
  578.  
  579. return true;
  580.  
  581. }
  582.  
  583. if (!estafora(destino2) && tekirisse(p, destino2) != 0) {
  584.  
  585. return true;
  586.  
  587. }
  588.  
  589. }
  590.  
  591. } else {
  592.  
  593. for (int i = 0; i < positionBlackies.length; i++) { // Itera sobre as peças pretas
  594.  
  595. Position p = positionBlackies[i];
  596.  
  597. Position destino1 = new Position(p.line() + 2, p.col() - 2);
  598.  
  599. Position destino2 = new Position(p.line() + 2, p.col() + 2);
  600.  
  601.  
  602. if (!estafora(destino1) && tekirisse(p, destino1) != 0) {
  603.  
  604. return true;
  605.  
  606. }
  607.  
  608. if (!estafora(destino2) && tekirisse(p, destino2) != 0) {
  609.  
  610. return true;
  611.  
  612. }
  613.  
  614. }
  615.  
  616. }
  617.  
  618. return false;
  619.  
  620. }
  621.  
  622. boolean éLegal(Position de, Position até) {
  623.  
  624. if(existeCapturaDisponivel()) {
  625.  
  626. return false;
  627.  
  628. }
  629.  
  630. int Linha = de.line() - até.line();
  631.  
  632. int Coluna = Math.abs(de.col() - até.col());
  633.  
  634. if (estafora(até))
  635.  
  636. return false;
  637.  
  638. if (jogamBrancas) { // Jogada das brancas
  639.  
  640. return Linha == 1 && Coluna == 1 && !pretas(até.line(), até.col()) && !brancas(até.line(), até.col());// Jogada simples das brancas
  641.  
  642. }
  643.  
  644. return Linha == -1 && Coluna == 1 && !pretas(até.line(), até.col()) && !brancas(até.line(), até.col());
  645.  
  646. }
  647.  
  648. int tekirisse(Position a, Position b) {
  649.  
  650. if(!estafora(b)) {
  651.  
  652. if(a.line()-2==b.line() && (a.col()-2==b.col()&& jogamBrancas)) {
  653.  
  654. if((!brancas(b.line(),b.col())&& (!pretas(b.line(),b.col())&& pretas((a.line()+b.line())/2,(a.col()+b.col())/2) )))
  655.  
  656. return 1;
  657.  
  658. }
  659.  
  660. if (a.line()-2==b.line() && (a.col()+2==b.col() && jogamBrancas)){
  661.  
  662. if((!brancas(b.line(),b.col())&& (!pretas(b.line(),b.col())&&pretas((a.line()+b.line())/2,(a.col()+b.col())/2))))
  663.  
  664. return 2;
  665.  
  666. }
  667.  
  668. if (a.line()+2==b.line() && (a.col()-2==b.col() && !jogamBrancas)) {
  669.  
  670. if((!brancas(b.line(),b.col())&& (!pretas(b.line(),b.col())&& brancas((a.line()+b.line())/2,(a.col()+b.col())/2))))
  671.  
  672. return 3;
  673.  
  674. }
  675.  
  676. if (a.line()+2==b.line() && (a.col()+2==b.col() && !jogamBrancas)){
  677.  
  678. if((!brancas(b.line(),b.col())&& (!pretas(b.line(),b.col())&& brancas((a.line()+b.line())/2,(a.col()+b.col())/2))))
  679.  
  680. return 4;
  681.  
  682. }
  683.  
  684. return 0;
  685.  
  686. }
  687.  
  688. return 0;
  689.  
  690. }
  691.  
  692.  
  693. void moveTopeça(Position de, Position até) {
  694.  
  695. if (éLegal(de, até)) { // Verifica se o movimento é legal
  696.  
  697. if(jogamBrancas) {
  698.  
  699. movevetor(positionWhities, de, até);
  700.  
  701. jogamBrancas = false;
  702.  
  703. }
  704.  
  705. else {
  706.  
  707. movevetor(positionBlackies, de, até);
  708.  
  709. jogamBrancas = true;
  710.  
  711. }
  712.  
  713. }
  714.  
  715. if(tekirisse(de, até)!=0) {
  716.  
  717. if(jogamBrancas) {
  718.  
  719. capturamove(positionWhities, de, até);
  720.  
  721. jogamBrancas = false;
  722.  
  723. }
  724.  
  725. else {
  726.  
  727. capturamove(positionBlackies, de, até);
  728.  
  729. jogamBrancas = true;
  730.  
  731. }
  732.  
  733. }
  734.  
  735. }
  736.  
  737. // Método auxiliar para mover a peça nas listas (positionBlackies ou positionWhities)
  738.  
  739. void movevetor(Position[] positions, Position from, Position to) {
  740.  
  741. for (int i = 0; i < positions.length; i++) {
  742.  
  743. if (positions[i] != null && positions[i].equals(from)) {
  744.  
  745. positions[i] = to; // Atualiza a posição da peça
  746.  
  747. }
  748.  
  749. }
  750.  
  751. }
  752.  
  753. boolean posiçãoVálida(Position pos) {
  754.  
  755. return !(pos.line() == -312 && pos.col() == -123);
  756.  
  757. }
  758.  
  759. void save(String fileName) {
  760.  
  761. try {
  762.  
  763. File file = new File(fileName);
  764.  
  765. PrintWriter writer = new PrintWriter(file);
  766.  
  767.  
  768. // Grava o estado atual do jogo
  769.  
  770. writer.println(jogamBrancas); // Quem joga
  771.  
  772. writer.println(linha); // Número de linhas do tabuleiro
  773.  
  774. writer.println(coluna); // Número de colunas do tabuleiro
  775.  
  776. writer.println(blackCount); // Quantidade de peças pretas
  777.  
  778. writer.println(whiteCount); // Quantidade de peças brancas
  779.  
  780.  
  781. // Grava as posições das peças brancas
  782.  
  783. for (int i = 0; i < whiteCount; i++) {
  784.  
  785. writer.println(positionWhities[i].line());
  786.  
  787. writer.println(positionWhities[i].col());
  788.  
  789. }
  790.  
  791.  
  792. // Grava as posições das peças pretas
  793.  
  794. for (int i = 0; i < blackCount; i++) {
  795.  
  796. writer.println(positionBlackies[i].line());
  797.  
  798. writer.println(positionBlackies[i].col());
  799.  
  800. }
  801.  
  802.  
  803. writer.close();
  804.  
  805. System.out.println("Jogo gravado com sucesso em " + fileName);
  806.  
  807. } catch (FileNotFoundException e) {
  808.  
  809. System.out.println("Erro ao gravar o arquivo: " + e.getMessage());
  810.  
  811. }
  812.  
  813. }
  814.  
  815. void load(String fileName) {
  816.  
  817. try {
  818. File file = new File(fileName);
  819. Scanner scanner = new Scanner(file);
  820. jogamBrancas = Boolean.parseBoolean(scanner.nextLine());
  821. linha = Integer.parseInt(scanner.nextLine());
  822. coluna = Integer.parseInt(scanner.nextLine());
  823. blackCount = Integer.parseInt(scanner.nextLine());
  824. whiteCount = Integer.parseInt(scanner.nextLine());
  825. positionWhities = new Position[whiteCount];
  826. positionBlackies = new Position[blackCount];
  827. for (int i = 0; i < whiteCount; i++) {
  828. int line = Integer.parseInt(scanner.nextLine());
  829. int col = Integer.parseInt(scanner.nextLine());
  830. positionWhities[i] = new Position(line, col);
  831. }
  832. for (int i = 0; i < blackCount; i++) {
  833. int line = Integer.parseInt(scanner.nextLine());
  834. int col = Integer.parseInt(scanner.nextLine());
  835. positionBlackies[i] = new Position(line, col);
  836. }
  837. scanner.close();
  838. System.out.println("Jogo carregado com sucesso de " + fileName);
  839. } catch (FileNotFoundException e) {
  840. System.out.println("Erro: Arquivo não encontrado.");
  841. } catch (Exception e) {
  842. System.out.println("Erro ao carregar o arquivo: " + e.getMessage());
  843. }
  844. }
  845.  
  846. }
Add Comment
Please, Sign In to add comment