Enunciado_2223_PPM_1aEp_v2.pdf
Document Details
Uploaded by StrongerCantor
2023
Tags
Related
Full Transcript
Projeto de Programação Multiparadigma 2º semestre – 2022/2023 Prova Escrita - 1ª Época Duração: 1 hora...
Projeto de Programação Multiparadigma 2º semestre – 2022/2023 Prova Escrita - 1ª Época Duração: 1 hora e 30 minutos Cotação: 8 valores Observações e Regras: Deve indicar o seu número, nome e curso nas páginas 3 e 5; As questões devem ser respondidas nas respetivas folhas; É permitido entregar o teste escrito a lápis; Só é permitido entregar ou desistir após a primeira hora; É estritamente proibido manipular quaisquer aparelhos eletrónicos (telemóveis, tablets, etc). A violação desta regra implica a anulação da frequência; Podem ser utilizados métodos desenvolvidos em questões anteriores; Não é necessário escrever quaisquer instruções de import; Os métodos desenvolvidos não podem conter ciclos nem variáveis mutáveis. Class List API (partial) apply(n: Int): A - Get the element at the specified index. contains[A1 >: A](elem: A1): Boolean - Tests whether this list contains a given value as an element. count(p: (A) => Boolean): Int - Counts the number of elements in the collection which satisfy a predicate. dropWhile(p: (A) => Boolean): List[A] - Drops longest prefix of elements that satisfy a predicate. exists(p: (A) => Boolean): Boolean - Tests whether a predicate holds for at least one element of this list. filter(p: (A) => Boolean): List[A] - Selects all elements of this list which satisfy a predicate. find(p: (A) => Boolean): Option[A] - Finds the first element of the list satisfying a predicate, if any. foldLeft[B](z: B)(op: (B, A) => B): B - Applies a binary operator to a start value and all elements of this sequence, going left to right. foldRight[B](z: B)(op: (A, B) => B): B - Applies a binary operator to all elements of this list and a start value, going right to left. 1/6 head: A - Selects the first element of this iterable collection. indexOf[B >: A](elem: B): Int - Finds index of first occurrence of some value in this sequence. indexWhere(p: (A) => Boolean, from: Int): Int - Finds index of the first element satisfying some predicate after or at some start index. init: List[A] - The initial part of the collection without its last element. isEmpty: Boolean - Tests whether the list is empty. last: A - Selects the last element. length: Int - The length (number of elements) of the list. map[B](f: (A) => B): List[B] - Builds a new list by applying a function to all elements of this list. reverse: List[A] - Returns new list with elements in reversed order. takeWhile(p: (A) => Boolean): List[A] - Takes longest prefix of elements that satisfy a predicate. transpose[B](implicit asIterable: (A) => collection.Iterable[B]): List[List[B]] - Transposes this iterable collection of iterable collections into a iterable collection of iterable collections. updated[B >: A](index: Int, elem: B): List[B] - A copy of this list with one single replaced element. Enunciado Considere que pretende desenvolver o jogo Quatro em Linha (humano vs computador) num tabuleiro 6x7 utilizando os seguintes tipos de Dados: type Board = List[List[Cells.cell]] object Cells extends Enumeration { type Cell = Value val Red, Blue, Empty = Value } O tabuleiro é vertical o que significa que o jogador só pode jogar na posição livre da linha de maior índice de uma dada coluna (assumindo que a posição (0,0) do tabuleiro está no canto superior esquerdo). O objetivo é criar uma sequência contínua horizontal, vertical ou diagonal1 de 4 unidades. O primeiro a criar essa sequência ganha o jogo. 1 Não considerado neste enunciado. 2/6 Número: Curso: _________________________________ Nome: _______________________________________________________________ Questão 1 (2,0 valores) Implemente o método com recursividade na cauda (i.e., tailRec) responsável por determinar se existe uma sequência consecutiva de n células (i.e., Cells.cell) iguais numa linha de células fornecida. def nInLine(col:List[Cells.Cell], c:Cells.Cell, n:Int): Boolean = { } Questão 2 (2,0 valores) Implemente o método winner responsável por verificar se, o computador ou o jogador, ganhou o jogo (i.e., se existe uma sequência contínua horizontal ou vertical de quatro unidades). Sugestão: utilize o método transpose que aplicado a uma matriz devolve a sua transposta (i.e., as linhas passam a colunas e a colunas a linhas). def winner(b:Board, player:Cells.Cell):Boolean = { 3/6 } Questão 3 (2,0 valores) Implemente, utilizando foldRight ou foldLeft, o método que recebe o board e devolve uma lista de índices correspondente às colunas com posições livres (não necessita de verificar se as posições estão no topo da coluna). Sugestão: utilize o método transpose. def columnsWithEmptyCells(b:Board):List[Int] = { } (Não responder às perguntas 4 ou 5 nesta folha!) 4/6 Número: Curso: _________________ Nome: _______________________________________________________________ Questão 4 (1,0 valor) Complete o código dado que corresponde ao método responsável por alterar o texto da label1 para “You won!” no caso de o jogador (que joga com a cor azul) ter ganho o jogo. Pode assumir a existência da instância game da case classe Game no object App contendo o método winner(player:Cells.Cell):Boolean class Controller { @FXML var label1: Label = _ def onMouseClicked(): Unit = { } } Questão 5 (1,0 valor) Comente, sucintamente, a seguinte frase: “É adequado incluir o User Interface Pattern Fat Menu na interface gráfica do jogo Quatro em Linha”. 5/6 (Não responder às perguntas 1, 2 ou 3 nesta folha!) 6/6