Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
LSinzker committed Jun 8, 2017
0 parents commit 6c696cd
Show file tree
Hide file tree
Showing 36 changed files with 1,707 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
*.class
*.log

# sbt specific
.cache
.history
.lib/
dist/*
target/
target/*
lib_managed/
src_managed/
project/boot/
project/plugins/project/

# Scala-IDE specific
.scala_dependencies
.worksheet

# Scala Intellij
.idea
*.idea
.idea/*
98 changes: 98 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
GameOfLife
==========
Projeto 1 da Disciplina de Técnicas de Programação I no semestre 2017/1 (Turmas C) na Universidade de Brasília.

##### Especificação do projeto:
Baseado nos códigos disponibilizados no ambiente moodle da disciplina as seguintes melhorias devem ser implementadas no algoritmo do GameOfLife:


* Questão 01 do projeto

•conforme mencionado, diferentes alternativas podem ser usadas para flexibilizar a implementação do cálculo das próximas gerações.
Entre elas:

•Template Method
•Strategy

•Usando o padrão Template Method, tornamos a classe GameEngine abstrata. Classes abstratas geralmente possuem pelo menos um método abstrato, não podem ser instanciadas e servem para estabelecer um tipo particular de contrato: as classes concretas que herdam de uma classe abstrata devem prover uma implementação para os métodos abstratos declarados na super classe. Os métodos shouldRevive e shouldKeepAlive
Devem ser declarados como abstratos e serem chamados pelo método concreto nextGeneration da classe GameEngine (caracterizando o padrão Template Método).

•No caso do TemplateMethod, a implementação dos métodos shouldRevive e shouldKeepAlive ́e concretizada em classes que herdam de GameEngine. Note que, para mudar a regra de derivação durante uma partida, precisamos instanciar uma GameEngine.

•Usando o padrão Strategy, deve ocorrer uma extração da definição dos métodos shouldRevive e shouldKeepAlive para um trait (EstrategiaDeDerivacao) e fazer com que a classe GameEngine referencie uma instancia desse trait. O método que computa próxima geração faz as chamadas aos métodos shouldRevive e shouldKeepAlive extraídos para o trait.

•A implementação dos métodos shouldRevive e shouldKeepAlive e concretizada em classes que implementam o trait EstrategiaDeDerivacao . Note que, para mudar a regra de derivação durante uma partida, precisamos apenas atualizar a referência a uma estratégia de derivação na classe GameEngine não sendo necessário instanciar novamente essa classe



* Questão 02 do Projeto

•Implemente uma interface gráfica para o GameOfLife reusando as classes existentes. A interface gráfica pose ser baseada na biblioteca libgdx.

•Torne a implementação mais flexível com o uso do padrão injeção de dependência (ID), de tal forma que os objetos que implementam os diferentes algoritmos para calcular as regras de derivação sejam injetados no programa (em vez de diretamente instanciados).




* Questão 03 do Projeto

•Implemente uma nova opção de menu que faz com que próximas gerações sejam computadas automaticamente.

•Observe que a implementação atual não suporta a noção de ambiente infinito (as células próximas aos limites do tabuleiro não possuem oito células vizinhas). Corrija essa falha de implementação.



* Questão 04 do Trabalho

•Estude o padrão de projeto memento e implemente um mecanismo de Undo, de tal forma que seja possível retornar (desfazer) n gerações. Assuma n = 10.


Instruções de execução (Utilizando a IDE *IntelliJ IDEA*)
=========================================================


#Software necessário

O seguinte software é necessário para construir o ScalaFX:
* Instalar o ScalaFX no projeto:

O seguinte software é necessário para construir o ScalaFX:


1. [SBT](http://www.scala-sbt.org/) v.0.13.5 ou melhor
- Descompacte o conteúdo em alguma pasta de sua preferência no projeto.
2. [Scala](http://www.scala.org/)
- ScalaFX 8.0 é construído com o Scala 2.10.2 ou mais recente.
- ScalaFX 2.2 é construído com a versão Scala 2.9.3 +, 2.10. + Ou 2.11. +



* No projeto

• Em buid.sbt adicione o seguinte código:

name := "GoL_Strategy"

version := "1.0"

scalaVersion := "2.12.2"

libraryDependencies += "org.scalafx" %% "scalafx" % "8.0.102-R11"


* Utilize a *JRE System Library [JavaSE-1.8]*.

------------------------------------------------------------------------------------------------------------------------
O JOGO

Comece a jogar: File>New (Isso criará uma matriz de celulas mortas)
Clique nos quadrados para tornar as células vivas.
O botão "Next Generation" criará a nova geração.
O botão "Play" criará novas gerações indefinidamente até o botão "Stop" ser acionado.
Os botões "UNDO" e "REDO" desfazem e refazem as ações do usuário.
Para mudar as regras do jogo vá no menu "Rules" e selecione a de preferência.

O usuário pode mudar a cor das cálulas vivas com os botões de cores no canto superoir esquerdo.
Existem configurações de células vivas pré setadas no jogo "Pulsar" e "Glider".

[Jonatas Gomes P. Júnior][14/0146407] [Juliana Hosoume][17/0003078] [Luisa Sinzker][14/0151893]
10 changes: 10 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name := "GoL"

version := "1.0"

scalaVersion := "2.12.2"

libraryDependencies += "org.scalafx" %% "scalafx" % "8.0.102-R11"

libraryDependencies += "net.codingwell" %% "scala-guice" % "4.1.0"

1 change: 1 addition & 0 deletions project/build.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sbt.version = 0.13.15
1 change: 1 addition & 0 deletions project/plugins.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
logLevel := Level.Warn
14 changes: 14 additions & 0 deletions src/main/scala/GoL/Caretaker.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package GoL
import scala.collection.mutable.ListBuffer

/**
* Contract for implementation of a Keeper of Mementos
*/
trait Caretaker[Memento] {
val mementosRepository: ListBuffer[Memento]
protected var current: Int = -1
def persist: Unit
def undo: Unit
def redo: Unit
def clear: Unit
}
22 changes: 22 additions & 0 deletions src/main/scala/GoL/Cell.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package GoL

/**
* @author Jonatas, Juliana and Luisa
* Adapted from code from Breno Xavier
*/
class Cell {

private var alive = false

/**
* Getter for att .alive
* @return (Boolean) alive
*/
def isAlive = alive

/**
* Setters for Cell attribute alive
*/
def kill = alive = false
def revive = alive = true
}
53 changes: 53 additions & 0 deletions src/main/scala/GoL/CellsCaretaker.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package GoL

import scala.collection.mutable.ListBuffer

/** Deals with Mementos*/
object CellsCaretaker extends Caretaker[CellsMemento] {
/** cellsMementos keeps all mementos created. Tests shows that a modern notebook can store
* a lot of Mementos without overloading*/
val mementosRepository = new ListBuffer[CellsMemento]
/** current works as an index to provide information of the current state of the program
* accordingly to the mementos stored */

/**
* Save a state of the CellsRepository
*/
def persist: Unit = {
mementosRepository += CellsRepository.save
current += 1
}

/**
* Restore CellsRepository to previous saved State
*/
def undo: Unit = {
if (validMemento(current - 1)) {
current -= 1
CellsRepository.restore(mementosRepository(current))
} else {
CellsRepository.restore(mementosRepository(0))
}
}

/**
* Restore CellsRepository to previous saved State
*/
def redo: Unit = {
if (validMemento(current + 1)) {
current += 1
CellsRepository.restore(mementosRepository(current))
} else {
CellsRepository.restore(mementosRepository.last)
}
}

private def validMemento(position: Int): Boolean = {
position >= 0 && position < mementosRepository.size
}

def clear: Unit = {
current = -1
mementosRepository.clear
}
}
13 changes: 13 additions & 0 deletions src/main/scala/GoL/CellsMemento.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package GoL

class CellsMemento(height: Int, width: Int, cells: Array[Array[Cell]]) {
val collection = Array.ofDim[Cell](height, width)

for(line <- (0 until height)) {
for(column <- (0 until width)) {
collection(line)(column) = new Cell
if (cells(line)(column).isAlive ) { collection(line)(column).revive }
}
}

}
51 changes: 51 additions & 0 deletions src/main/scala/GoL/CellsRepository.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package GoL

object CellsRepository {

val max_height = Main.height
val max_width = Main.width
val collection = Array.ofDim[Cell](max_height, max_width)

for(line <- (0 until max_height)) {
for(column <- (0 until max_width)) {
collection(line)(column) = new Cell
}
}

def apply(height: Int, width: Int): Cell = {
val line = positiveModulo(height, max_height)
val column = positiveModulo(width, max_width)
collection(line)(column)
}

private def positiveModulo(num: Int, den: Int): Int = {
val result = num % den
if (result >= 0) { result } else { result + den }
}

def clear: Unit ={
for(i <- 0 until max_height) {
for (j <- 0 until max_width) {
CellsRepository(i, j).kill
}
}
}

def save: CellsMemento = {
new CellsMemento(max_height, max_width, collection)
}

def restore(memento: CellsMemento) = {
for (line <- (0 until max_height)) {
for (column <- (0 until max_width)) {
if(memento.collection(line)(column).isAlive) {
collection(line)(column).revive
}else {
collection(line)(column).kill
}
}
}
}


}
12 changes: 12 additions & 0 deletions src/main/scala/GoL/DerivationStrategy.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package GoL

/**
*/
trait DerivationStrategy {
/* verifica se uma celula deve ser mantida viva */
def shouldKeepAlive(line: Int, column: Int): Boolean

/* verifica se uma celula deve (re)nascer */
def shouldRevive(line: Int, column: Int): Boolean

}
Loading

0 comments on commit 6c696cd

Please sign in to comment.