id
stringlengths
36
36
text
stringlengths
1
1.25M
927f4e93-2221-4453-8eea-eb0df5584d1f
private Node buildSubTree(int from, int to){ final int interval = to-from; Node node = null; if(interval <= 0){ // leaf from == to node = new Node(from); }else if (interval == 1){ // we have only two numbers in interval node = new Node(to); node.setLeftLeaf(new Node(from)); return node; }else{ // split interval into two int pivot = (interval)/2 + from; node = new Node(pivot); node.setLeftLeaf(buildSubTree(from, pivot - 1)); node.setRightLeaf(buildSubTree(pivot + 1, to)); } return node; }
3698c8f3-74c6-4391-b267-e791c586ffc6
public static int maxDepth(Node root){ return depth(root,0); }
e4ce1a9f-1a4f-43ee-b2d4-9b6e468dae34
private static int depth(Node leaf, int actualDepth){ int leftDepth = actualDepth; int rightDepth = actualDepth; if(leaf.getLeftLeaf() != null){ leftDepth = depth(leaf.getLeftLeaf(),actualDepth+1); } if(leaf.getRightLeaf() != null){ rightDepth = depth(leaf.getRightLeaf(),actualDepth+1); } return rightDepth > leftDepth ? rightDepth : leftDepth; }
59c1fe07-cec5-4df9-a790-8334710ac93d
public static int deeperNode(Node root, int aValue, int bValue){ if(root == null){ throw new NullPointerException("Root node is null!"); } return deeperNodeStep(aValue, root, bValue, root); }
b76ef82b-3bf3-4213-97a0-0e1a5817a541
private static int deeperNodeStep(int aValue, Node aNode, int bValue, Node bNode){ if(aNode.getValue() == aValue && bNode.getValue() == bValue){ // they are on same level return 0; }else if(aNode.getValue() == aValue){ // the bValue is deeper return -1; }else if(bNode.getValue() == bValue){ // the aValue is deeper return 1; }else{ // we have to go one level deeper return deeperNodeStep(aValue, findNextNode(aValue,aNode), bValue, findNextNode(bValue,bNode)); } }
ea8e7c69-8ee7-4556-8d35-eaf5ae6eb3df
private static Node findNextNode(int value, Node node){ if(node.getValue() > value && node.getLeftLeaf() != null){ // value is smaller then node, then go left if possible return node.getLeftLeaf(); }else if(node.getValue() < value && node.getRightLeaf() != null){ // value is higher then node, then go right if possible return node.getRightLeaf(); }else{ // can't go anywhere throw new NullPointerException("There is no route from "+node+" for: "+value); } }
3504cb94-4407-4bd2-9e1d-778cc9cd4175
public static Node lowestCommonAncestor(Node node, int aValue, int bValue){ if(node == null){ return null; } if(node.getValue() == aValue || node.getValue() == bValue){ // If the value of node is aValue or bValue then we found LCA return node; } final Node aNext = findNextNode(aValue,node); final Node bNext = findNextNode(bValue,node); if(aNext.equals(bNext)){ // next level node is same for both values thus we need to go deeper return lowestCommonAncestor(aNext,aValue,bValue); }else{ // we found the LCA return node; } }
94a062f5-1a3c-41b3-826a-54453436dda4
public Node(int value){ this.value = value; }
82b8444c-c582-40b0-816d-be9869283072
public int getValue() { return value; }
9802b55f-67e7-433a-b00d-9a16a8119819
public void setLeftLeaf(Node leftLeaf) { this.leftLeaf = leftLeaf; }
ee610c18-6f82-4665-9a53-761f5c522e13
public Node getLeftLeaf() { return leftLeaf; }
32cb1a44-b705-4433-a129-4f9dde5244b3
public void setRightLeaf(Node rightLeaf) { this.rightLeaf = rightLeaf; }
7ef6d454-0a52-4693-a4a6-031299807fb2
public Node getRightLeaf() { return rightLeaf; }
6eaad940-6ee5-4edc-991e-0559a1784a87
@Override public String toString() { return String.format("Node[%s]",value); }
9582492a-7c49-4c45-b65a-e748c87f52db
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; if (value != node.value) return false; return true; }
e04da335-6e48-467c-848a-44c4a2064609
@Override public int hashCode() { return value; }
f1398b51-e3ec-4347-83d1-39fc69ff1bea
@Test public void maxDepthTest(){ TreeBuilder tb = new TreeBuilder(10); Node root = tb.buildTree(); assertEquals(3,TreeOperations.maxDepth(root)); }
cfb128ac-478f-4772-bf8f-7680919e0b4b
@Test public void deeperNodeTest(){ TreeBuilder tb = new TreeBuilder(10); Node root = tb.buildTree(); // same deep assertEquals(0,TreeOperations.deeperNode(root,1,7)); // same deep assertEquals(0,TreeOperations.deeperNode(root,0,9)); // same deep assertEquals(0,TreeOperations.deeperNode(root,8,2)); // 0 is deeper assertEquals(1,TreeOperations.deeperNode(root,0,7)); // 0 is deeper assertEquals(1,TreeOperations.deeperNode(root,0,1)); // 0 is deeper assertEquals(1,TreeOperations.deeperNode(root,0,4)); // 3 is deeper assertEquals(-1,TreeOperations.deeperNode(root,1,3)); }
aaa07e0c-c36f-417d-b5b0-ed5f2bc7f78e
@Test public void lcaTest(){ TreeBuilder tb = new TreeBuilder(10); Node root = tb.buildTree(); assertEquals(5,TreeOperations.lowestCommonAncestor(root,1,8).getValue()); assertEquals(2,TreeOperations.lowestCommonAncestor(root,3,1).getValue()); assertEquals(2,TreeOperations.lowestCommonAncestor(root,1,2).getValue()); assertEquals(7,TreeOperations.lowestCommonAncestor(root,7,6).getValue()); }
b2242441-b278-435f-8781-772c5330efc2
@Test public void buildTree1Test(){ TreeBuilder t = new TreeBuilder(10); Node root = t.buildTree(); assertEquals(5,root.getValue()); assertEquals(2,root.getLeftLeaf().getValue()); assertEquals(4,root.getLeftLeaf().getRightLeaf().getValue()); assertEquals(3,root.getLeftLeaf().getRightLeaf().getLeftLeaf().getValue()); assertEquals(1,root.getLeftLeaf().getLeftLeaf().getValue()); assertEquals(0,root.getLeftLeaf().getLeftLeaf().getLeftLeaf().getValue()); assertEquals(null,root.getLeftLeaf().getLeftLeaf().getRightLeaf()); assertEquals(8,root.getRightLeaf().getValue()); assertEquals(10,root.getRightLeaf().getRightLeaf().getValue()); assertEquals(9,root.getRightLeaf().getRightLeaf().getLeftLeaf().getValue()); assertEquals(7,root.getRightLeaf().getLeftLeaf().getValue()); assertEquals(6,root.getRightLeaf().getLeftLeaf().getLeftLeaf().getValue()); assertEquals(null,root.getRightLeaf().getLeftLeaf().getRightLeaf()); }
6afa3517-79bd-4e1c-893d-d0c30bd7a3dc
@Test public void buildTree2Test(){ TreeBuilder t = new TreeBuilder(9); Node root = t.buildTree(); assertEquals(4,root.getValue()); // left subtree assertEquals(1,root.getLeftLeaf().getValue()); assertEquals(0,root.getLeftLeaf().getLeftLeaf().getValue()); assertEquals(null,root.getLeftLeaf().getLeftLeaf().getLeftLeaf()); assertEquals(null,root.getLeftLeaf().getLeftLeaf().getRightLeaf()); assertEquals(3,root.getLeftLeaf().getRightLeaf().getValue()); assertEquals(2,root.getLeftLeaf().getRightLeaf().getLeftLeaf().getValue()); assertEquals(null,root.getLeftLeaf().getRightLeaf().getRightLeaf()); // right subtree assertEquals(7,root.getRightLeaf().getValue()); assertEquals(9,root.getRightLeaf().getRightLeaf().getValue()); assertEquals(8,root.getRightLeaf().getRightLeaf().getLeftLeaf().getValue()); assertEquals(null,root.getRightLeaf().getRightLeaf().getRightLeaf()); assertEquals(6,root.getRightLeaf().getLeftLeaf().getValue()); assertEquals(5,root.getRightLeaf().getLeftLeaf().getLeftLeaf().getValue()); assertEquals(null,root.getRightLeaf().getLeftLeaf().getRightLeaf()); }
2fe0d834-fa98-41ed-8bf3-c8768c9b2b1a
public Algoritmo calculaAlgoritmoGenetico(Integer numeroGenes, Integer tamanhoDaPopulacao, RestricoesLaterais restricoesLaterais, Integer comprimento);
cd6b8462-c9fc-410e-96b9-4658bfcd35a3
public Integer obtemTotalBits(Integer tamanhoPopulacao, Integer numeroGenes, Integer comprimento){ return tamanhoPopulacao * numeroGenes * comprimento; }
13ca3b0d-e6fe-4f1f-890d-a46c2a49483f
public BigDecimal[] obtemValorDeMelhorResultado(BigDecimal resultadoAdaptacao, BigDecimal[] resultPopInicial) { BigDecimal[] resultado = new BigDecimal[resultPopInicial.length]; BigDecimal valor = BigDecimal.ZERO; for(int i = 0; i < resultPopInicial.length; i++){ valor = valor.add(resultPopInicial[i].divide(resultadoAdaptacao, RoundingMode.HALF_EVEN)); resultado[i] = valor; } return resultado; }
a1f6c5ef-aedf-48a1-a1ea-352ca95bea07
public BigDecimal calcularCodigoGenetico(RestricoesLaterais restricoesLaterais, Integer comprimento, Double valor) { return BigDecimal.valueOf(valor).multiply(restricoesLaterais.getXu().subtract(restricoesLaterais.getXl())) .divide(((new BigDecimal(2).pow(comprimento)).subtract(BigDecimal.ONE)), 3, RoundingMode.CEILING) .add(restricoesLaterais.getXl()); }
deb84f01-42d4-409f-a25d-a51f223b3656
public BigDecimal funcaoObjetiva(BigDecimal x, BigDecimal y){ //max g(x, y) = - [x sen (4x) + 1,1 y sen (2y)] x = x.setScale(2, RoundingMode.HALF_EVEN); y = y.setScale(2, RoundingMode.HALF_EVEN); BigDecimal total = x.multiply( BigDecimal.valueOf(Math.sin(4 * x.doubleValue()) )) .add(new BigDecimal(1.1) .multiply(y.multiply( BigDecimal.valueOf(Math.sin(2 * y.doubleValue())) )) ).negate(); return total; }
f738e238-d0e3-4a2e-acac-7b5387005e4e
public Integer indiceDaMutacao(Integer indice, Integer tamanhoIndividuo) { int validador = 0; int index = new BigDecimal(indice - tamanhoIndividuo).abs().intValue(); while(indice / tamanhoIndividuo != validador){ if(indice / tamanhoIndividuo == 0){ index = indice; break; } else if(indice / tamanhoIndividuo == 1){ index = indice - tamanhoIndividuo; break; } else { return indiceDaMutacao(indice - tamanhoIndividuo, tamanhoIndividuo); } } return index; }
b46d4b70-cdbd-40d6-9306-ae4eccd0fd2b
public CalculadoraGenetica(){ this.calculos = new Calculos(); }
c72f2986-12f5-4d27-a089-250d3a6abfc7
public String reproducao(Genes[] genes, RestricoesLaterais restricoesLaterais, Integer comprimento, BigDecimal[] genesAdaptacao) { String gene = ""; System.out.println("Iniciando reprodução . . . "); for(int i = 0; i < genes.length; i++){ Double valor = AlgoritmoUtils.converteBinarioEmDecimal(genes[i].getGene()); BigDecimal resultado = calculos.calcularCodigoGenetico(restricoesLaterais, comprimento, valor); genesAdaptacao[i] = resultado; gene += valor; gene += " "; } System.out.println("Reprodução calculada!"); return gene; }
29a36f34-05a7-4aeb-9b61-f96c546ab184
public BigDecimal adaptacao(BigDecimal[] genesAdaptacao){ System.out.println("Iniciando Adaptação . . ."); BigDecimal x = genesAdaptacao[0]; BigDecimal y = genesAdaptacao[1]; BigDecimal resultado = calculos.funcaoObjetiva(x, y); System.out.println("Adaptação Concluída!"); return resultado.setScale(2, RoundingMode.HALF_EVEN); }
7317b9f2-3f9f-45ff-865c-c64b8c81d7fa
public Populacao mutacao(Populacao populacao, Integer numeroGenes, Integer comprimento){ String caracteres = AlgoritmoUtils.CODIGO_BINARIO; System.out.println("Iniciando processo de mutação . . ."); Integer contador = 0; Integer qtdBitsLidos = 0; int i = 0; int somaBits = 0; Integer totalDeBits = calculos.obtemTotalBits(populacao.getTamanhoDaPopulacao(), numeroGenes, comprimento); SortedMap<Integer, Double> indicesMutaveis = GeradorRandomico.obterCaracterMutacao(totalDeBits); Object[] indices = indicesMutaveis.keySet().toArray(); Integer comprimentoIndividuo = populacao.getIndividuo()[contador].getIndividuo().length(); while(indices.length > i) { int indice = new Integer(indices[i].toString()); System.out.println("Indice a ser alterado na mutação: " + indice); //qtdBitsLidos += comprimentoIndividuo * 2; if(indice / comprimentoIndividuo > 1 && indice - somaBits > comprimentoIndividuo){ contador = indice / comprimentoIndividuo; qtdBitsLidos = comprimentoIndividuo * (contador + 1); somaBits += comprimentoIndividuo * (contador + 1); } else if(indice / comprimentoIndividuo == 1){ somaBits += comprimentoIndividuo; contador++; } else { somaBits += comprimentoIndividuo; } if(indice > somaBits) continue; if(somaBits >= indice){ int index = calculos.indiceDaMutacao(indice, populacao.getIndividuo()[contador].getIndividuo().length()); if(index == 0){ contador--; index = populacao.getIndividuo()[contador].getIndividuo().length(); } populacao.getIndividuo()[contador] = mutar(populacao.getIndividuo()[contador], caracteres, comprimento, index); } if(indice <= somaBits){ i++; somaBits = 0; } contador++; } if(indices.length == 0){ System.out.println("Não houve Mutação!"); } System.out.println("Mutação concluída!"); return populacao; }
c51a0c85-1408-48eb-9ae7-6b9b441d4e3c
private Cromossomo mutar(Cromossomo cromossomo, String caracteres, Integer comprimento, int index) { System.out.println("mutar no indice " + (index - 1) + " do cromossomo " + cromossomo.getIndividuo()); char[] mutacao = cromossomo.getIndividuo().toCharArray(); System.out.println("antes de mutar: " + mutacao[index-1]); mutacao[index-1] = (mutacao[index-1] == caracteres.charAt(0) ? caracteres.charAt(1) : caracteres.charAt(0)); System.out.println("depois de mutado: " + mutacao[index-1]); cromossomo.setIndividuo(new String(mutacao)); return cromossomo; }
84609e77-f8dc-4ed7-ae1c-22d5227e2d23
public Populacao criaCrossoverMutado(Populacao populacao, Integer comprimento, Integer numeroGenes){ System.out.println("Iniciando processo de Crossover . . ."); List<Integer> index = obterPopulacaoParaCrossOver(GeradorRandomico.geraVetorRandomico(populacao.getTamanhoDaPopulacao()), populacao); System.out.println("Tamanho da populacao a ser feita crossover: " + index.size()); for(int i = 0; i < populacao.getIndividuo().length; i++){ int contador = i + 1; System.out.println("C antes do crossover" + contador + ":" + populacao.getIndividuo()[i].getIndividuo()); } populacao = this.criaCrossover(populacao, GeradorRandomico.numeroRandomicoParaRetornoDeK(comprimento, numeroGenes).intValue(), index); for(int i = 0; i < populacao.getIndividuo().length; i++){ int contador = i + 1; System.out.println("C depois do crossover" + contador + ":" + populacao.getIndividuo()[i].getIndividuo()); } populacao = this.mutacao(populacao, numeroGenes, comprimento); for(int i = 0; i < populacao.getIndividuo().length; i++){ int contador = i + 1; System.out.println("C depois da mutacao" + contador + ":" + populacao.getIndividuo()[i].getIndividuo()); } System.out.println("Finalizando Mutação e Crossover"); return populacao; }
364359bc-5fa7-4509-8db8-20be962332ab
private List<Integer> obterPopulacaoParaCrossOver(BigDecimal[] rand, Populacao populacao) { List<Integer> index = new ArrayList<Integer>(); boolean paresNaoDefinidos = true; int tamanho = populacao.getTamanhoDaPopulacao() % 2 != 0 ? populacao.getTamanhoDaPopulacao() : populacao.getTamanhoDaPopulacao() - 1; int i = 0; int contadorEmergencial = 0; while(i < tamanho - 1 || index.size() % 2 == 1){ if(i > tamanho) return index; double numero; if(i == tamanho && index.size() % 2 == 1){ i--; numero = rand[contadorEmergencial].doubleValue(); contadorEmergencial++; } else { numero = rand[i].doubleValue(); } if(numero < populacao.getIndividuo()[i].getCromossomoDouble()){ index.add(i); } i++; } return index; }
67be0472-f5ce-41ae-af8f-3b2c8289672a
private Populacao criaCrossover(Populacao populacao, Integer randomK, List<Integer> index) { for(int i = 0; i < index.size(); i = i + 2){ Cromossomo cromossomo = populacao.getIndividuo()[index.get(i)]; if(index.size() % 2 == 0){ populacao = geraCrossover(populacao, index.get(i), randomK); } } return populacao; }
e6fa9699-43bf-4e67-b27b-8fc4749eda0c
private Populacao geraCrossover(Populacao populacao, int i, Integer randomK){ System.out.println("Iniciando crossover do par " + i + " e " + (i+1) + " com equivalente k = " + randomK); String c1 = populacao.getIndividuo()[i].getIndividuo().substring(randomK); String c2 = populacao.getIndividuo()[i+1].getIndividuo().substring(randomK); populacao.getIndividuo()[i].setIndividuo(populacao.getIndividuo()[i].getIndividuo().substring(0, randomK) + c2); populacao.getIndividuo()[i+1].setIndividuo(populacao.getIndividuo()[i+1].getIndividuo().substring(0, randomK) + c1); System.out.println("Crossover do par concluído!"); return populacao; }
3fd169c5-94a3-46dd-a6ea-53438bfb284e
public Populacao separaMelhores(BigDecimal[] vetorRand, BigDecimal resultadoAdaptacao, BigDecimal[] resultPopInicial, Map<Integer, Cromossomo> individuo) { System.out.println("Obtendo os Melhores cromossomos . . ."); int contador = 0; Cromossomo[] cromossomos = new Cromossomo[individuo.size()]; BigDecimal[] probabilidade = calculos.obtemValorDeMelhorResultado(resultadoAdaptacao, resultPopInicial); while(vetorRand.length > contador){ cromossomos[contador] = compareEObtenhaOMelhor(vetorRand[contador], probabilidade, individuo); contador++; } System.out.println("Retornando melhores cromossomos como uma nova população"); return new Populacao(cromossomos); }
634a06b2-aa82-4383-8ba4-ba30fe0368a6
private Cromossomo compareEObtenhaOMelhor(BigDecimal vetorRand, BigDecimal[] probabilidade, Map<Integer, Cromossomo> individuo) { int i = 0; boolean encontrou = false; while(!encontrou){ if(vetorRand.compareTo(probabilidade[i]) == -1){ encontrou = true; break; } else if(vetorRand.compareTo(probabilidade[i]) == 1){ encontrou = false; i++; continue; } } individuo.get(i).setCromossomoDouble(probabilidade[i].doubleValue()); return populaCromossomo(individuo.get(i)); }
b8b751ef-d19a-4bf6-81c8-0b7861594ec7
private Cromossomo populaCromossomo(Cromossomo cromossomo) { Integer numeroGenes = cromossomo.getGenes().length; Integer comprimento = cromossomo.getGenes()[0].getGene().length(); Cromossomo cromossomoNovo = new Cromossomo(cromossomo.getIndividuo(), comprimento, numeroGenes); cromossomoNovo.setCromossomoDouble(cromossomo.getCromossomoDouble()); return cromossomoNovo; }
4840f514-1e8d-4073-ac90-4e2c8354d63f
@Override public Algoritmo calculaAlgoritmoGenetico(Integer numeroGenes, Integer tamanhoPopulacao, RestricoesLaterais restricoesLaterais, Integer comprimento) { CalculadoraGenetica calculadoraGenetica = new CalculadoraGenetica(); //Criar Populacao inicial Populacao populacaoInicial = new Populacao(numeroGenes, tamanhoPopulacao, comprimento); StringBuilder builder = new StringBuilder(); for(int i = 0; i < populacaoInicial.getIndividuo().length; i++){ int contador = i + 1; System.out.println("Cinicial" + contador + ":" + populacaoInicial.getIndividuo()[i].getIndividuo()); builder.append("Cinicial" + contador + ":" + populacaoInicial.getIndividuo()[i].getIndividuo() + " \n"); } JOptionPane.showMessageDialog(null, builder.toString(), "Populacao Inicial", JOptionPane.INFORMATION_MESSAGE); //Criar populacao das gerações /*Populacao populacao = new Populacao(numeroGenes,CalculadoraGenetica.getTotalCromossomos()); for(int i = 0; i < populacaoInicial.getIndividuo().length; i++){ int contador = i + 1; System.out.println("pFi" + contador + ":" + populacaoInicial.getIndividuo()[i].getIndividuo()); }*/ BigDecimal resultadoAdaptacao = BigDecimal.ZERO; BigDecimal[] resultPopInicial = new BigDecimal[populacaoInicial.getIndividuo().length]; Map<Integer, Cromossomo> mapPopulacao = new HashMap<Integer,Cromossomo>(); resultadoAdaptacao = reproduzirEAdaptar(restricoesLaterais, comprimento, calculadoraGenetica, populacaoInicial, resultadoAdaptacao, resultPopInicial, mapPopulacao); JOptionPane.showMessageDialog(null, resultadoAdaptacao, "Resultado antes de algumas etapas (fx objetiva)", JOptionPane.INFORMATION_MESSAGE); //Melhores Resultados Populacao populacaoNova = calculadoraGenetica.separaMelhores(GeradorRandomico.geraVetorRandomico(tamanhoPopulacao),resultadoAdaptacao, resultPopInicial, mapPopulacao); //Cruzamento e mutação populacaoNova = calculadoraGenetica.criaCrossoverMutado(populacaoNova, comprimento, numeroGenes); //Teste de convergencia resultadoAdaptacao = reproduzirEAdaptar(restricoesLaterais, comprimento, calculadoraGenetica, populacaoNova, resultadoAdaptacao, resultPopInicial, mapPopulacao); JOptionPane.showMessageDialog(null, resultadoAdaptacao, "Resultado após todas as etapas (fx objetiva)", JOptionPane.INFORMATION_MESSAGE); return this; }
4471cb6e-a2c6-4bb2-b5ca-1394aad41a7f
private BigDecimal reproduzirEAdaptar(RestricoesLaterais restricoesLaterais, Integer comprimento, CalculadoraGenetica calculadoraGenetica, Populacao populacaoInicial, BigDecimal resultadoAdaptacao, BigDecimal[] resultPopInicial, Map<Integer, Cromossomo> mapPopulacao) { for(int i = 0; i < populacaoInicial.getIndividuo().length; i++){ //Reprodução e adaptação BigDecimal[] genesAdaptacao = new BigDecimal[populacaoInicial.getIndividuo()[i].getGenes().length]; String gene = calculadoraGenetica.reproducao(populacaoInicial.getIndividuo()[i].getGenes(), restricoesLaterais, comprimento, genesAdaptacao); resultPopInicial[i] = calculadoraGenetica.adaptacao(genesAdaptacao); populacaoInicial.getIndividuo()[i].setCromossomoDouble(resultPopInicial[i].doubleValue()); mapPopulacao.put(i, populacaoInicial.getIndividuo()[i]); resultadoAdaptacao = resultadoAdaptacao.add(resultPopInicial[i]); } return resultadoAdaptacao; }
2cc2e9b7-6f30-4b15-b9c5-80ca7a1aa8be
public static void main(String[] args){ AlgoritmoGenetico algoritmoGenetico = new Algoritmo(); /// Inputs String nGene = JOptionPane.showInputDialog("Digite o numero de genes que deve ter (Default 2): "); String nPop = JOptionPane.showInputDialog("Digite o numero do tamanho da população (Default 6): "); String nComprimento = JOptionPane.showInputDialog("Digite o comprimento do gene (Default 8): "); String nXu = JOptionPane.showInputDialog("Digite a restrição lateral maior (Default 10): "); String nXl = JOptionPane.showInputDialog("Digite a restrição lateral menor (Default 8): "); //calculaAlgoritmoGenetico(numeroGenes,tamanhoDaPopulacao,xu,xl) RestricoesLaterais restricoesLaterais = new RestricoesLaterais(nXu.isEmpty() ? new BigDecimal(10) : new BigDecimal(nXu), nXl.isEmpty() ? new BigDecimal(8): new BigDecimal(nXl)); Integer numeroGenes = nGene.isEmpty() ? 2 : new Integer(nGene);//2; Integer tamanhoDaPopulacao = nPop.isEmpty() ? 6 : new Integer(nPop);//6; Integer comprimentoGene = nComprimento.isEmpty() ? 8 : new Integer(nComprimento);//8; algoritmoGenetico.calculaAlgoritmoGenetico(numeroGenes, tamanhoDaPopulacao, restricoesLaterais, comprimentoGene); }
ae2506c4-c82c-4b47-a4ad-3f8e90e7dfe6
public Populacao(Integer numeroGenes, Integer tamanhoDaPopulacao, Integer comprimento) { this.tamanhoDaPopulacao = tamanhoDaPopulacao; this.individuo = new Cromossomo[tamanhoDaPopulacao]; /*individuo[0] = new Cromossomo("1000010100100111", comprimento, numeroGenes); individuo[1] = new Cromossomo("0000111000001001", comprimento, numeroGenes); individuo[2] = new Cromossomo("1001000100000001", comprimento, numeroGenes); individuo[3] = new Cromossomo("1100010100101001", comprimento, numeroGenes); individuo[4] = new Cromossomo("0111110010101100", comprimento, numeroGenes); individuo[5] = new Cromossomo("1110001001001010", comprimento, numeroGenes);*/ for(int i = 0; i < individuo.length; i++){ individuo[i] = new Cromossomo(numeroGenes, comprimento); } }
3a6ad19e-0391-4570-8a31-ff9709e2ea3b
public Populacao(Cromossomo[] cromossomos){ this.individuo = cromossomos; this.tamanhoDaPopulacao = cromossomos.length; }
68f99fce-893e-453b-a241-49dc54c07895
public Cromossomo[] getIndividuo() { return individuo; }
517a53b3-7ad6-484f-b2d2-78708a5d8636
public void setIndividuo(Cromossomo[] individuo) { this.individuo = individuo; }
8b630533-736c-451e-8636-f8a687a4d139
public Integer getTamanhoDaPopulacao() { return tamanhoDaPopulacao; }
cc9643e0-629e-49aa-a1a9-8d65900f484d
public void setTamanhoDaPopulacao(Integer tamanhoDaPopulacao) { this.tamanhoDaPopulacao = tamanhoDaPopulacao; }
b4b474b9-39b3-4373-8b09-dea81baccac4
public Genes(Integer comprimento, String gene) { this.comprimento = comprimento; this.gene = gene; alelos = new Character[gene.length()]; for(int i = 0; i < gene.length(); i++){ alelos[i] = gene.charAt(i); } }
080d4522-b5fc-44c6-8864-e3ad57b65923
public String getGene() { return gene; }
227b43ab-6766-4bc2-a3cf-df58bb671fa8
public RestricoesLaterais(BigDecimal xu, BigDecimal xl) { this.xl = xl; this.xu = xu; }
876d53cd-b692-480e-b254-df3604d7ba84
public BigDecimal getXu() { return xu; }
dd7e5bd2-e062-4809-95d2-c5d3283594e5
public void setXu(BigDecimal xu) { this.xu = xu; }
2ce44fce-b5b1-4fdb-8f13-58e0e04ce9f4
public BigDecimal getXl() { return xl; }
b4a63d80-7722-4d63-a1f4-031169051c9c
public void setXl(BigDecimal xl) { this.xl = xl; }
bf9c89d6-bf41-4dfb-bd88-1b58f49b4e77
public Cromossomo(Integer numeroGenes, Integer comprimento) { this.numeroGenes = numeroGenes; genes = new Genes[numeroGenes]; StringBuilder geneString = new StringBuilder(); for(int i =0; i < numeroGenes; i++) { genes[i] = new Genes(comprimento, criarGene(comprimento, AlgoritmoUtils.CODIGO_BINARIO)); } }
4d836737-7682-4cf7-8c66-f21506602b14
public Cromossomo(String individuo, Integer comprimento, Integer numeroGenes){ genes = new Genes[numeroGenes]; this.numeroGenes = numeroGenes; int posicaoInicial = 0; int posicaoFinal = comprimento; for(int i = 0; i < numeroGenes; i++){ genes[i] = new Genes(comprimento, individuo.substring(posicaoInicial, posicaoFinal)); posicaoInicial += comprimento; posicaoFinal += comprimento; } }
8a96fc5b-0bbb-439b-8300-d640b9fb08a9
private String criarGene(Integer tamanho, String caracteres){ String gene = ""; for(int i = 0; i < tamanho; i++){ gene += caracteres.charAt(GeradorRandomico.obtemIndiceDeCaracterRandomico()); } return gene; }
913862e2-5aa1-44fd-a6f8-62ad9278d61d
public Genes[] getGenes() { return genes; }
ee741fc0-f417-4b7f-8d77-d504e8a0ffde
public String getIndividuo() { this.individuo = ""; for(int i = 0; i < this.genes.length; i++){ this.individuo += this.genes[i].getGene(); } return individuo; }
45799258-5867-42a4-a95c-758c5e3a671a
public void setIndividuo(String individuo) { this.individuo = individuo; int inicio = 0; int fim = individuo.length()/numeroGenes; for (int i = 0; i < this.numeroGenes; i++){ this.getGenes()[i] = new Genes(individuo.length()/numeroGenes, individuo.substring(inicio, fim)); inicio = fim; fim += individuo.length()/numeroGenes; } }
f2474a38-31b9-4768-a1e9-25024dd9d5ca
public Double getCromossomoDouble() { return cromossomoDouble; }
c9271020-72a2-47a4-98ba-a7fcd8b3040e
public void setCromossomoDouble(Double cromossomoDouble) { this.cromossomoDouble = cromossomoDouble; }
5d9e949f-d8b4-45bf-a689-c94156655d4e
public static Double converteBinarioEmDecimal(String binario){ Double valor = new Double(0); // soma ao valor final o d�gito bin�rio da posi��o * 2 elevado ao contador da posi��o (come�a em 0) for (int i = binario.length() - 1; i >= 0; i--) { valor += Integer.parseInt( binario.charAt(i) + "" ) * Math.pow( 2, ((binario.length() -1) - i ) ); } return valor; }
9075d358-c9f5-49eb-b570-64a284b7aa52
public static String converteDecimalEmBinario(BigDecimal decimal) { int resto = -1; StringBuilder sb = new StringBuilder(); int valor = decimal.intValue(); if (valor == 0) { return "0"; } // enquanto o resultado da divis�o por 2 for maior que 0 adiciona o resto ao in�cio da String de retorno while (valor > 0) { resto = valor % 2; valor = valor / 2; sb.insert(0, resto); } return sb.toString(); }
9e9f31ac-f968-432a-b8ab-64941e874649
public static BigDecimal numeroRandomicoParaRetornoDeK(Integer comprimento, Integer numeroGenes){ return new BigDecimal(1 + random.nextDouble() * ( (comprimento * numeroGenes - 1) - 1) ).setScale(1,RoundingMode.UP); }
8ad29fa2-a796-4d13-a975-552cf363eeca
public static BigDecimal[] geraVetorRandomico(Integer tamanhoPopulacao){ BigDecimal[] vetor = new BigDecimal[tamanhoPopulacao]; for(int i = 0; i < tamanhoPopulacao; i++){ vetor[i] = new BigDecimal(random.nextDouble()); } return vetor; }
fcef47b8-2cbd-4bd3-9fe8-7f02990a32d7
public static SortedMap<Integer, Double> obterCaracterMutacao(Integer totalDeBits) { SortedMap<Integer, Double> listaIndicesMutaveis = new TreeMap<Integer, Double>(); for(int i = 0; i < totalDeBits; i++){ Double gerado = random.nextDouble(); if(gerado < AlgoritmoUtils.PORCENTAGEM_MUTACAO){ listaIndicesMutaveis.put(i, gerado); } } return listaIndicesMutaveis; }
af4b3f66-8546-4666-b3b0-dcc86476a8c9
public static Integer obtemIndiceDeCaracterRandomico(){ return random.nextInt(2); }
145645f6-631d-42a9-a195-9d6cb9947b95
YahtzeeScore(JButton[] buttons, JLabel[][] labels, JLabel status, Die[] dice, String[] cButtonsText, int numGridRows, int player) { this.cButtons = buttons; this.cLabels = labels; this.statusLabel = status; this.dice = dice; this.cButtonsText = cButtonsText; this.numGridRows = numGridRows; this.player = player; }
2dce7096-8b2c-4450-aebd-8efcac3a1389
private boolean inArray(int n, int[] array, String find) {// if find = "exact", 'n' needs to be exact number in array int seqCounter = 0; for (int arr : array) { if ((find.equals("exact") && arr == n) || (find.equals("min") && arr >= n)) return true; } if (find.equals("sequence")) {//sequence of 'n', limited possibilities if ( n == 4 && ( (array[0]>0 && array[1]>0 && array[2]>0 && array[3]>0) || (array[1]>0 && array[2]>0 && array[3]>0 && array[4]>0) || (array[2]>0 && array[3]>0 && array[4]>0 && array[5]>0) )) return true; else if ( n == 5 && ( (array[0]>0 && array[1]>0 && array[2]>0 && array[3]>0 && array[4]>0) || (array[1]>0 && array[2]>0 && array[3]>0 && array[4]>0 && array[5]>0) )) return true; } return false; }
1431e982-b598-4bc2-ac62-0b4f125b45fd
private boolean cButtonEnable(int bIndex, String bText) { cButtons[bIndex].setEnabled(true); if (bText != null) cButtons[bIndex].setText(bText); return true; }
d35e9f6e-2391-4823-be62-ffc02e947422
public boolean checkDice(int numRollsLeft) { boolean canScore = false; faceValues = new int[6]; /* ////TESTING FOR YAHTZEE EVERY TIME if (numRollsLeft == 2) { dice[0].faceValue = 5; dice[1].faceValue = 5; dice[2].faceValue = 5; dice[3].faceValue = 5; dice[4].faceValue = 5; } if (numRollsLeft == 1) { dice[0].faceValue = 6; dice[1].faceValue = 6; dice[2].faceValue = 6; dice[3].faceValue = 6; dice[4].faceValue = 6; } if (numRollsLeft == 0) { dice[0].faceValue = 4; dice[1].faceValue = 4; dice[2].faceValue = 4; dice[3].faceValue = 4; dice[4].faceValue = 4; }*/ ////**************************//// //stores/counts how many of each die faces there are. for (int i=0; i<5; i++) { faceValues[dice[i].getFaceValue()-1]++; } //total value of all 5 dice int total5 = (faceValues[0])+(faceValues[1]*2)+(faceValues[2]*3)+(faceValues[3]*4)+(faceValues[4]*5)+(faceValues[5]*6); //set all scoring buttons to initial disabled for (int i=2; i<=numGridRows-3; i++) { cButtons[i].setEnabled(false); cButtons[i].setText(cButtonsText[i]); //reset button to initial text } //check upper section if (faceValues[0] > 0 && scores[1] == -1) canScore = cButtonEnable(2, "Aces (+"+faceValues[0]+")"); if (faceValues[1] > 0 && scores[2] == -1) canScore = cButtonEnable(3, "Twos (+"+faceValues[1]*2+")"); if (faceValues[2] > 0 && scores[3] == -1) canScore = cButtonEnable(4, "Threes (+"+faceValues[2]*3+")"); if (faceValues[3] > 0 && scores[4] == -1) canScore = cButtonEnable(5, "Fours (+"+faceValues[3]*4+")"); if (faceValues[4] > 0 && scores[5] == -1) canScore = cButtonEnable(6, "Fives (+"+faceValues[4]*5+")"); if (faceValues[5] > 0 && scores[6] == -1) canScore = cButtonEnable(7, "Sixes (+"+faceValues[5]*6+")"); //check 3 of a kind if (inArray(3, faceValues, "min") && scores[7] == -1) canScore = cButtonEnable(10, "3 of a kind (+"+total5+")"); //check 4 of a kind if (inArray(4, faceValues, "min") && scores[8] == -1) canScore = cButtonEnable(11, "4 of a kind (+"+total5+")"); //check full house if (inArray(3, faceValues, "exact") && inArray(2, faceValues, "exact") && scores[9] == -1) canScore = cButtonEnable(12, "Full House (+25)"); //check small straight if (inArray(4, faceValues, "sequence") && scores[10] == -1) canScore = cButtonEnable(13, "Sm. Straight (+30)"); //check large straight if (inArray(5, faceValues, "sequence") && scores[11] == -1) canScore = cButtonEnable(14, "Lg. Straight (+40)"); //check Yahtzee (5 of a kind) and bonus if (inArray(5, faceValues, "exact")) { //if main yahtzee not scored if (scores[12] == -1) canScore = cButtonEnable(15, "YAHTZEE! (+50)"); else if (scores[12] != 0) {//no bonus if yahtzee has 0 points //if score of the facevalue of yahtzee dice is already set, then can select to score as a filler to any lower section if (scores[dice[0].getFaceValue()] != -1) { for (int i=9; i<12; i++) { if (scores[i] == -1) { canScore = cButtonEnable(i+3, null); } } } } } //check chance if (scores[0] == -1) canScore = cButtonEnable(16, "Chance (+"+total5+")"); //if you cant score and number of rolls left is 0, enable buttons to choose a score to fill in as 0 if (!canScore && numRollsLeft == 0) { for (int i=1; i<13; i++) //skipping 0, because chance would automatically have to be set to be in this situation { if (scores[i] == -1) { if (i <=6)//checking upper section cButtons[i+1].setEnabled(true); else//lower cButtons[i+3].setEnabled(true); } } } return canScore; }//end of checkDice method
fc2f3b72-1501-491d-93dd-d4e857e61bbc
private void updateScore(int[] points, boolean canScore, int bIndex, int scoreIndex, int pointsToScore) { //upper section scored, multiply score by facevalue of scored section if (bIndex == scoreIndex+1 && pointsToScore == -1) scores[scoreIndex] = (canScore) ? (faceValues[scoreIndex-1]*scoreIndex) : 0; else scores[scoreIndex] = (canScore) ? pointsToScore : 0; points[0] += scores[scoreIndex]; cLabels[player][bIndex].setText("Score: "+scores[scoreIndex]); }
8737dd2f-9b11-4e25-bf4e-c5de1e7a6d42
public int[] score(Object buttonO, boolean canScore) { JButton button = (JButton)buttonO; int[] points = new int[3]; // int[] that will be returned containing amount of points scored [0]->points [1]->upper bonus [2]->yahtzeebonus int bIndex = -1; // index of button clicked, also respective label //total of all 5 dice int total5 = (faceValues[0])+(faceValues[1]*2)+(faceValues[2]*3)+(faceValues[3]*4)+(faceValues[4]*5)+(faceValues[5]*6); //check Yahtzee (5 of a kind) and award bonus if 2nd+ yahtzee if (inArray(5, faceValues, "exact")) { if ((!yahtzeeBonus[0] || !yahtzeeBonus[1]) && scores[12] > 0) { if (!yahtzeeBonus[0]) yahtzeeBonus[0] = true; else yahtzeeBonus[1] = true; points[2] += 100; } } //check for button/label index for (int i=0; i<cButtons.length; i++) { if (cButtons[i] == button) { bIndex = i; break; } } //update scores and labels switch(bIndex) { case 2: //aces case 3: //twos case 4: //threes case 5: //fours case 6: //fives case 7: //sixes updateScore(points, canScore, bIndex, bIndex-1, -1); break; case 10: //3 of a kind case 11: //4 of a kind updateScore(points, canScore, bIndex, bIndex-3, total5); break; case 12: //full house updateScore(points, canScore, bIndex, bIndex-3, 25); break; case 13: //small straight updateScore(points, canScore, bIndex, bIndex-3, 30); break; case 14: //large straight updateScore(points, canScore, bIndex, bIndex-3, 40); break; case 15: //yahtzee updateScore(points, canScore, bIndex, bIndex-3, 50); break; case 16: //chance updateScore(points, canScore, bIndex, 0, total5); break; } //add up totals scores[13] = 0; //scores[1]+scores[2]+scores[3]+scores[4]+scores[5]+scores[6]; for (int i=1; i<=6; i++) { if (scores[i] != -1) scores[13] += scores[i]; } //check for bonus in upper section if (scores[13] >= 63) { upperBonus = true; cLabels[player][8].setText("BONUS: +35"); scores[13] += 35; if (!printedBonus) { printedBonus = true; points[1] += 35; } } scores[14] = 0; if (scores[0] != -1) scores[14] += scores[0]; //scores[7]+scores[8]+scores[9]+scores[10]+scores[11]+scores[12]+scores[0]; for (int i=7; i<=12; i++) { if (scores[i] != -1) scores[14] += scores[i]; } //add in any yahtzee bonuses int yahBonus = 0; if (yahtzeeBonus[0]) yahBonus+=100; if (yahtzeeBonus[1]) yahBonus+=100; scores[14] += yahBonus; scores[15] = scores[13]+scores[14]; //update total labels cLabels[player][9].setText("UPPER TOTAL: "+scores[13]); cLabels[player][17].setText("Yahtzee BONUS: +"+yahBonus); cLabels[player][18].setText("LOWER TOTAL: "+scores[14]); cLabels[player][19].setText("GRAND TOTAL: "+scores[15]); return points; }//end of score method
63a39010-4859-467e-afb4-2d2300e5fd72
public void reset() { for (int i=0; i<13; i++) scores[i] = -1; scores[13] = 0; scores[14] = 0; scores[15] = 0; yahtzeeBonus[0] = false; yahtzeeBonus[1] = false; upperBonus = false; printedBonus = false; for (int i=2; i<numGridRows; i++) { switch(i) { case 8: cLabels[player][i].setText("BONUS: +0"); break; case 9: cLabels[player][i].setText("UPPER TOTAL: 0"); break; case 17: cLabels[player][i].setText("Yahtzee BONUS: +0"); break; case 18: cLabels[player][i].setText("LOWER TOTAL: 0"); break; case 19: cLabels[player][i].setText("GRAND TOTAL: 0"); break; default: cLabels[player][i].setText("Score: "); break; } } }
a0951f8f-30b5-4c71-96a7-02477df67140
public int getGrandTotal() { return scores[15]; }
01026f44-e884-4296-b5fa-79b1da4c38a7
public static void main(String[] args) { Object[] options = {"1","2","3","4","5"}; String s = (String)JOptionPane.showInputDialog( null, "How many players will be playing this game?\n", "Customized Dialog", JOptionPane.PLAIN_MESSAGE, null, options, "1"); //If a string was returned, say so. int numPlayers = 0; if (s != null && s.length() == 1) numPlayers = Integer.parseInt(s); if (numPlayers < 1 || numPlayers > 5) System.exit(0); //int numPlayers = Integer.parseInt(JOptionPane.showInputDialog("How many players will be playing this game?")); JFrame frame = new ExFrame(numPlayers); frame.setSize(150+150*numPlayers,700); frame.setTitle("YAHTZEE!"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }
5e14f49f-2308-421b-a68b-baba94d11c30
public Die(int x, int y, boolean highlight, int faceValue) { this.x = x; this.y = y; this.highlighted = highlight; this.highlightedHover = false; this.faceValue = faceValue; }
25e7fe0e-a8d1-49f0-ad5b-04c4ec82d0e2
public void highlight() { this.highlighted = !this.highlighted; }
d97cd9e1-ed5a-409b-8b16-a9a177f68dc4
public void highlightHover(boolean h) { this.highlightedHover = h; }
67160a60-9cdc-4e5e-9adb-2e8e448cf90d
public int getFaceValue() { return faceValue; }
7763220b-6cea-48f5-ae59-46c8c00cd267
public void draw(Graphics2D g2) {}
bcb684b3-bb2c-4b2f-b336-2b98aad26efb
MousePressListener(DiceComponent component, JButton[] cButtons, JLabel[][] cLabels, JLabel statusLabel, int numGridRows, YahtzeeScore[] score, JLabel highscoreLabel, int numPlayers) { this.component = component; this.cButtons = cButtons; this.cLabels = cLabels; this.statusLabel = statusLabel; this.numGridRows = numGridRows; this.score = score; this.highscoreLabel = highscoreLabel; this.player = 0; this.numPlayers = numPlayers; round = 1; numRollsLeft = 2; canScore = score[player].checkDice(numRollsLeft); }
cb6c8313-ad55-4688-b55a-b67022d403a2
private void newGame() { Object[] options = {"Create new game","Cancel"}; int answer = JOptionPane.showOptionDialog(null, "Are you sure you want to start a new game? All your current data will be deleted.", "New Game?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (answer == JOptionPane.YES_OPTION) { cButtons[0].setEnabled(true); numRollsLeft = 2; round = 1; cLabels[player][0].setText(""); cLabels[0][0].setText("Rolls Left: "+numRollsLeft); player = 0; component.rollDice(true); for(YahtzeeScore sco : score) sco.reset(); statusLabel.setText("<html>New game has been started!<br>Please select the dice that you wish to hold or click on a scoring button</html>"); } }
3f5edd7d-d788-4651-8fbf-c2ab26da9c44
private void nextPlayer() { cLabels[player][0].setText(""); // remove label above player if (player+1 < numPlayers) player++; //next player else { player = 0; //back to first player round++; // increment round } }
c321e6e8-fa29-4580-ba7c-197e7d5f32ec
public void mousePressed(MouseEvent e) { // highlight die and keep highlighted int x = e.getX(); int y = e.getY(); component.highlightDie(x,y, false); }
ad198ace-ddb0-4bc2-bc24-064335f5dee4
public void mouseReleased(MouseEvent e){}
63cb1989-42f4-4dae-95b0-fe021f3694df
public void mouseClicked(MouseEvent e){}
f2d9392d-cfbf-486b-a397-9d3e91f0813e
public void mouseEntered(MouseEvent e){}
4428294f-fdf3-4957-a7f4-61c3e976b5c5
public void mouseExited(MouseEvent e){}
d6896b55-585c-4af8-b40f-2f7091f913c8
public void mouseDragged(MouseEvent e) {}
9a01f2e4-57b2-477b-8b3e-e961d5dcf986
public void mouseMoved(MouseEvent e) { //highlight die when mouse hovered on int x = e.getX(); int y = e.getY(); if ( !(hoverCoords != null && //array does NOT exists x >= hoverCoords[0] && x <= hoverCoords[0]+component.DIE_SIZE && //NOT inside x coords y >= hoverCoords[1] && y <= hoverCoords[1]+component.DIE_SIZE )) //NOT inside y coords { component.diceHighlightHoverOff(); //method to set all highlightHover properties to false b/c not hovering on a die or went off from a die hoverCoords = component.highlightDie(x,y, true); //check if die is hovered on } }
baccad7c-47ef-40e1-a5b3-614be8ecd1d1
public void actionPerformed(ActionEvent e) { statusLabel.setForeground(Color.black); //reroll button clicked if (e.getSource() == cButtons[0]) { component.rollDice(false); cLabels[player][0].setText("Rolls Left: "+ --numRollsLeft); if (numRollsLeft <= 0) { cButtons[0].setEnabled(false); statusLabel.setText("<html>No more rolls left.<br>Choose how you wish to score.</html>"); } } //new game button clicked else if (e.getSource() == cButtons[numGridRows-1]) { newGame(); // reset everything for new game } //one of the scoring buttons was clicked else { int[] points = score[player].score(e.getSource(), canScore); numRollsLeft = 2; component.rollDice(true); // rolls new 5 dice cButtons[0].setEnabled(true); // sets roll dice button to enable statusLabel.setText("<html>Scored "+points[0]+" points!"+ (points[0] == 50 ? " YAHTZEE!<br>" : "<br>") + (points[1]==35 ?"You have also received a bonus of +35 points for having 63+ points in the Upper Section!<br>":"") + (points[2]==100 ?"You have also received a Yahtzee bonus of +100 points!<br>":"") + "<br>Please select the dice that you wish to reroll or click on a scoring button</html>"); if (round == 13 && player+1 == numPlayers) { cButtons[0].setEnabled(false); if (numPlayers == 1) statusLabel.setText("<html>End of game. You have scored a Grand Total of "+score[player].getGrandTotal()+" points!<br><br>To play again, click on NEW GAME!</html>"); else { //more than one players, compare scores int winnerScore = 0; int winner = 0; for(int k = 0; k < numPlayers; k++) { if (score[k].getGrandTotal() > winnerScore) { winnerScore = score[k].getGrandTotal(); winner = k+1; } } statusLabel.setText("<html>End of game. Player "+winner+" is the winner with a Grand Total of "+winnerScore+" points!<br><br>To play again, click on NEW GAME!</html>"); } /*try { checkHighscore(score.getGrandTotal()); } catch (IOException t) { System.err.println("FileNotFoundException: " + t.getMessage()); }*/ } nextPlayer(); cLabels[player][0].setText("Rolls Left: "+ numRollsLeft); } canScore = score[player].checkDice(numRollsLeft); if (!canScore && numRollsLeft == 0) { statusLabel.setText("<html>You can not score, select which scoring catagory to fill a 0 in</html>"); statusLabel.setForeground(Color.red); } }
0cc3eaa2-0901-4f9c-a586-c494c1480f97
ExFrame(int numPlayers) { this.numPlayers = numPlayers; this.numGridRows = 20; this.buttonWidth = 140; this.numCreateButLabCalls = 0; this.component = new DiceComponent(buttonWidth*2); this.cButtons = new JButton[numGridRows]; this.cButtonsText = new String[numGridRows]; this.cLabels = new JLabel[numPlayers][numGridRows]; this.statusLabel = new JLabel("<html>New game has been started!<br>Please select the dice that you wish to hold or click on a scoring button</html>"); this.highscoreLabel = new JLabel("Highscores"); this.score = new YahtzeeScore[numPlayers]; //populate score array for(int k = 0; k < numPlayers; k++) { score[k] = new YahtzeeScore(cButtons,cLabels, statusLabel, component.getDieArray(), cButtonsText, numGridRows, k); } statusLabel.setPreferredSize(new Dimension(buttonWidth*2, 100)); centerPanel = new JPanel(new GridLayout(numGridRows,numPlayers+1)); //columns based on numPlayers component.rollDice(true); popCenterPanel(); for(int k = 0; k < numPlayers; k++) score[k].reset(); addListeners(); this.add(centerPanel, BorderLayout.CENTER); this.add(component, BorderLayout.PAGE_START); this.add(statusLabel, BorderLayout.SOUTH); //this.add(highscoreLabel, BorderLayout.EAST); this.pack(); }
aa12e6ea-b102-4437-8c24-342ddaea13ce
private void addListeners() { listener = new MousePressListener(component, cButtons, cLabels, statusLabel, numGridRows, score, highscoreLabel, numPlayers); component.addMouseListener(listener); component.addMouseMotionListener(listener); /* try { listener.popHighscores(); } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: "+ e.getMessage()); }*/ for(JButton b:cButtons) { if (b.isVisible()) b.addActionListener(listener); } }
7ecfaba7-82b6-4d90-a31c-8086f4efc574
private void popCenterPanel() { //create buttons and labels for centerPanel createButLab("Roll Dice", "Rolls Left: 2",true); createButLab("","",false); createButLab("Aces", "Score: ",true); createButLab("Twos", "Score: ",true); createButLab("Threes", "Score: ",true); createButLab("Fours", "Score: ",true); createButLab("Fives", "Score: ",true); createButLab("Sixes", "Score: ",true); createButLab("", "BONUS: +0",false); createButLab("", "UPPER TOTAL: 0",false); //LOWER SECTION createButLab("3 of a kind", "Score: ",true); createButLab("4 of a kind", "Score: ",true); createButLab("Full House", "Score: ",true); createButLab("Sm. Straight", "Score: ",true); createButLab("Lg. Straight", "Score: ",true); createButLab("YAHTZEE!", "Score: ",true); createButLab("Chance", "Score: ",true); createButLab("", "Yahtzee BONUS: +0",false); createButLab("", "LOWER TOTAL: 0",false); createButLab("NEW GAME!", "GRAND TOTAL: 0",true); for (int i = 1; i < numPlayers; i++) cLabels[i][0] = new JLabel(""); //add all center buttons/labels into centerPanel boolean allButtonsAdded = false; for(int i = 0; i < cButtons.length; i++) { centerPanel.add(cButtons[i]); for(int p = 0; p < numPlayers; p++) centerPanel.add(cLabels[p][i]); } }
85d95f1b-7a7f-45b0-b504-e588919e98ab
private void createButLab(String butText, String labText, boolean visible) { cButtonsText[numCreateButLabCalls] = butText; cButtons[numCreateButLabCalls] = new JButton(butText); cButtons[numCreateButLabCalls].setPreferredSize(new Dimension(buttonWidth,25)); for (int i = 0; i < numPlayers; i++) cLabels[i][numCreateButLabCalls] = new JLabel(labText); if (numCreateButLabCalls > 0 && numCreateButLabCalls != numGridRows-1)//if not first button and not new game button, proceed cButtons[numCreateButLabCalls].setEnabled(false); if (!visible) cButtons[numCreateButLabCalls].setVisible(false); numCreateButLabCalls++; }
5b62f332-d1b3-47d0-a903-c61cd0e062b2
DiceComponent(int x) { this.dimX = x; this.setPreferredSize(new Dimension(dimX,dimY)); }
1d2f2b88-994c-488a-8f8c-9852c1b6dfc8
public void paintComponent(Graphics g) { g2 = (Graphics2D) g; for(int i = 0; i < 5; i++) { dice[i].draw(g2); } }