From 5a005ddf02ef33bc317347b996620f01605fa63d Mon Sep 17 00:00:00 2001 From: HFossdal <122976119+HFossdal@users.noreply.github.com> Date: Tue, 19 Mar 2024 20:14:18 +0100 Subject: [PATCH] feat: :sparkles: merged all the files for the game merged all the files for the game --- src/game/TetrisGameManager.py | 125 +++++++++++++++++--------- src/game/block.py | 52 +++++------ src/game/board.py | 162 ++++++++++++++++------------------ 3 files changed, 184 insertions(+), 155 deletions(-) diff --git a/src/game/TetrisGameManager.py b/src/game/TetrisGameManager.py index 8588a34..12a479e 100644 --- a/src/game/TetrisGameManager.py +++ b/src/game/TetrisGameManager.py @@ -1,5 +1,8 @@ from pynput.keyboard import Key, Listener import time as t +from Board import Board +import sys + baseScore = 100 DOWN = (0, 1) @@ -14,7 +17,6 @@ soft drop and hard drop implementation """ - class TetrisGameManager: currentPiece = None @@ -23,6 +25,7 @@ class TetrisGameManager: updateTimer = 1 streak = 1 currentTime = None + board = None def __init__(self, board): self.board = board @@ -35,65 +38,99 @@ def __init__(self, board): def onPress(self, key): + switcher = { - + Key.down: self.movePiece("DOWN"), + Key.left: self.movePiece("LEFT"), + Key.right: self.movePiece("RIGHT"), + Key.space: "HardDrop", + Key.esc: self.stopGame(), + Key.up: self.rotatePiece("UP"), } - + + # Default action if key not found + default_action = lambda: "Key not recognized" + + # Get the function to execute based on the key, or default action + switcher.get(key, default_action) + print("_____________________________________________________") + self.board.printBoard() + #print(action) + # Execute the function + #return action + def onRelease(self, key): pass - def rotatePiece(self, direction): - self.currentPiece.rotate(direction) - + pass + # self.currentPiece.rotate(direction) def movePiece(self, direction): + if self.legalMove(): + if direction == "DOWN": + self.board.moveBlockDown() + elif direction == "LEFT": + self.board.moveBlockLeft() + elif direction == "RIGHT": + self.board.moveBlockRight() - if self.legalMove(direction): - self.currentPiece.move(direction) + # if self.legalMove(): + # self.board.moveBlockDown(direction) def dropPiece(self, newPiece): - self.movePiece(DOWN) + self.movePiece("DOWN") def isGameOver(self): - return self.board.isGameOver() + return self.board.validMove() + #return self.board.isGameOver() def startGame(self): self.currentPiece = self.newPiece() self.nextPiece = self.newPiece() - - while not self.isGameOver(): - action = input("Enter action: ") ## valid commands: [moveLeft, moveRight, moveDown, softDrop, hardDrop, quitGame, rotateLeft, rotateRight, rotate180] - if action == "moveLeft" and self.legalMove(LEFT): - self.movePiece(LEFT) - elif action == "moveRight" and self.legalMove(RIGHT): - self.movePiece(RIGHT) - elif action == "moveDown" and self.legalMove(DOWN): - self.dropPiece(DOWN) - elif action == "softDrop": - self.softDrop() - elif action == "h": - self.hardDrop() - elif action == "rotateLeft": - self.rotatePiece(-1) - elif action == "rotateRight": - self.rotatePiece(1) - elif action == "rotate180": - self.rotatePiece(2) - elif action == "q": - self.stopGame() - break - else: - self.moveDown() - + self.board.printBoard() + + with Listener( + on_press=self.onPress, + on_release=self.onRelease) as listener: + listener.join() + while not self.isGameOver(): + #action = input("Enter action: ") ## valid commands: [moveLeft, moveRight, moveDown, softDrop, hardDrop, quitGame, rotateLeft, rotateRight, rotate180] + if action == "moveLeft" and self.legalMove(): + self.movePiece(LEFT) + elif action == "moveRight" and self.legalMove(): + self.movePiece(RIGHT) + elif action == "moveDown" and self.legalMove(): + self.dropPiece(DOWN) + elif action == "softDrop": + self.softDrop() + elif action == "h": + self.hardDrop() + elif action == "rotateLeft": + self.rotatePiece(-1) + elif action == "rotateRight": + self.rotatePiece(1) + elif action == "rotate180": + self.rotatePiece(2) + elif action == "q": + self.stopGame() + break + else: + self.checkTimer() + + t.sleep(0.1) # Add a small delay to reduce CPU usage + + # Stop the listener when the game is over + listener.stop() def newPiece(self): - return self.pieces.getNewPiece() + pass + #return self.pieces.getNewPiece() - def legalMove(self, x, y): - return self.board.legalMove(x, y) + def legalMove(self): + return self.board.validMove() # def clearLines(self): # linesCleared = self.board.checkGameState() @@ -141,15 +178,19 @@ def checkTimer(self): checkTime = self.currentTime + 1000 newTime = int(round(t.time() * 1000)) if (checkTime > newTime): - self.movePiece(DOWN) + self.movePiece("DOWN") + print("Timer checked") return True def stopGame(self): + print("Game Over") + sys.exit() self.board.stop_game() +if __name__ == "__main__": + board = Board() + game = TetrisGameManager(board) + game.startGame() - if __name__ == "__main__": - millisec = int(round(t.time() * 1000)) - print(millisec) \ No newline at end of file diff --git a/src/game/block.py b/src/game/block.py index 3d5d574..867655d 100644 --- a/src/game/block.py +++ b/src/game/block.py @@ -1,9 +1,20 @@ +import random + +import random + class Block: + def __init__(self, x, y, blockType): self.x = x self.y = y + self.type = random.randint(0, 6) + + self.color = self.colors[random.randint(0,6)] + # self.type = random.randint(0,6) self.type = blockType self.color = self.colors[blockType] + # self.color = random.choice(self.colors) + # self.rotation = random.randint(0, len(self.figures[self.type]) - 1) self.rotation = 0 @@ -28,41 +39,26 @@ def __init__(self, x, y, blockType): (255, 255, 0) # O ] + + def set_coordinates(self, x, y): + self.x = x + self.y = y + def rotate_left(self): self.rotation = (self.rotation + 1) % len(self.figures[self.type]) def rotate_right(self): self.rotation = (self.rotation - 1) % len(self.figures[self.type]) - def get_block(self): - return self.figures[self.type][self.rotation] - - def get_color(self): - return self.colors[self.type] - - def get_x(self): - return self.x - - def get_y(self): - return self.y + def image(self): return self.figures[self.type][self.rotation] + + def move_down(self): + self.y += 1 - def set_x(self, x): - self.x = x + def move_left(self): + self.x -= 1 - def set_y(self, y): - self.y = y + def move_right(self): + self.x += 1 - def get_position(self): - return self.x, self.y - - def image(self): - return self.figures[self.type][self.rotation] - def get_block_coordinates(self): - # Calculate the coordinates for each block in the figure - positions = self.figures[self.type][self.rotation] - for i in range(4): - for j in range(4): - return - # If the block is in the figure, calculate the coordinates - ## TODO: Fix the coordinates diff --git a/src/game/board.py b/src/game/board.py index bde7c32..16708e7 100644 --- a/src/game/board.py +++ b/src/game/board.py @@ -1,11 +1,12 @@ import pygame +import random +from Block import Block ''' Denne skriver ut brettet i terminal bare. - -Vi lager brettet med en matrise. Det er O overalt i matrisen. legger du en brikke så nendrer vi i matrisen. +Vi lager brettet med en matrise. Det er 0 overalt i matrisen. legger du en brikke så nendrer vi i matrisen. Dersom en hel rad i matrisen er full, så fjerner vi denne raden og flytter alt sammen nedover + oppdatererr poengsummen" -En brikke i matrisen represneteres med x-er. +En brikke i matrisen represneteres med 1-er. ''' class Board: @@ -13,101 +14,92 @@ class Board: columns = 10 gameOver = False rowsRemoved = 0 + board=[] + block = Block(0,5, random.randint(0,6)) #random.randint(0,6) er for å velge en tilfeldig brikke def __init__(self): - self.matrix = [["O" for _ in range(self.columns)] for _ in range(self.rows)] - - def spawnNewBlock(self): - block = Block() - self.placeBlock(Block()) - if block.isValidMove(): - self.placeBlock(block) - - #vi oppretter en nyt blokk - #vi får tilbakemelding om hvilke blokk denne vil være og hvilke koordinater den skal ha. - #Dersom det er plass så plasserer vi den. - - def print_matrix(self): - for row in self.matrix: - print(' '.join(row)) - - def placeBlock(self, block): - if block.isValidMove(): - #block.position = [(x,y),(x,y)(x,y),(x,y)] - - for gridPositions in block.getPosition(): #må ha noe bedre logikk for å fjerne gamle posisjoner - for x, y in gridPositions - self.matrix[x][y] = "O" - - for gridPositions in block.getPosition(): - for x, y in gridPositions: - self.matrix[x][y] = "X" - - def rotateBlockRight(self, block): - if block.rotateRight().isValidMove(): - self.plaser_brikke(block.rotateRight()) + for i in range(0,self.rows-1): + newLine= [] + for j in range(0,self.columns-1): + newLine.append(0) + self.board.append(newLine) + + + def printBoard(self): + for row in self.board: + print((' ').join(str(row))) + + + def rotateBlockRight(self): + if self.block.rotateRight().validMove(): + self.placeBlock(self.block.rotate_right()) + - def moveBlockDown(self, block): - if block.moveDown().isValidMove(): - self.plaser_brikke(block.moveDown()) + def moveBlockDown(self): + if self.block.moveDown().validMove(): + self.placeBlock(block.move_down()) + + - def moveBlockLeft(self, block): - if block.moveLeft().isValidMove(): - self.plaser_brikke(block.moveLeft()) + def moveBlockLeft(self): + if self.block.moveLeft().validMove(): + self.placeBlock(self.block.move_left()) + - def moveBlockRight(self, block): - if block.moveRight().isValidMove(): - self.plaser_brikke(block.moveRight()) + def moveBlockRight(self): + if self.block.moveRight().validMove(): + self.placeBlock(self.block.move_right()) + - def rotateBlockLeft(self, block): - if block.rotateLeft().isValidMove(): - self.plaser_brikke(block.roterLeft()) + def rotateBlockLeft(self): + if self.block.rotateLeft().validMove(): + self.plaser_brikke(self.block.roter_left()) + def gameOver(self): return self.gameOver + + def validMove(self): + for i in range(4): + for j in range(4): + if i * 4 + j in self.block.image(): + if i + self.block.y > self.rows - 1 or \ + j + self.block.x > self.columns - 1 or \ + j + self.block.x < 0 or \ + self.board[i + self.block.y][j + self.block.x] > 0: + return False # Returnerer False ved kollisjon eller ugyldig trekk + + + def clearRow(self, rownumber): + # Fjerner den angitte raden og legger til en ny tom rad ved bunnen av matrisen + newMatrix = self.board[:rownumber] + self.board[rownumber+1:] + newMatrix.append([0 for _ in range(self.columns)]) + self.matrix = newMatrix # Oppdaterer matrisen med den nye matrisen + self.rowsRemoved += 1 # Oppdaterer antall fjernede rader + - def isvalidMove(self, block): - for gridPositions in block.position: - for x, y in gridPositions: - if self.matrix[x][y] != "O": - return False - return True - - def clearRow(self, rownumber): #tar vare på alt under randen som skal fjernes og legger alt over den som skal fjernes over + lager ny tom rad - newMatrix = self.matrix[0, rownumber] + self.matrix[rownumber+1, self.rows] + ["O" for _ in range(self.columns)] - self.Matrix = newMatrix - rowsRemoved += 1 - - def checkGameState(self): #itterer over alle rader og sjekker om de er fulle. fjerner alle som er fulle og teller hvor mange på rad som ble fjernet + def checkGameState(self): amount = 0 - for row in self.matrix: - if "O" not in row: - self.clearRow(row) - amount += 1 - return amount - - + fullRows = [] + + for rowIndex, row in enumerate(self.board): # Itererer over matrisen for å finne fulle rader + if 0 not in row: # Sjekker om raden er full + fullRows.append(rowIndex) # Legger til indeksen til listen over fulle rader + + for rowIndex in reversed(fullRows): # Går gjennom listen over fulle rader i reversert rekkefølge for å fjerne dem + self.clearRow(rowIndex) # Fjerner raden basert på dens indeks + amount += 1 # Øker telleren for antall fjernede rader + return amount # Returnerer totalt antall fjernede rader + + def placeBlock(self): + if not self.block.validMove(): + for i in range(4): + for j in range(4): + if i * 4 + j in self.block.image(): + self.board[i + self.block.x][j + self.block.y] = 1 #self.block.color + return self.checkGameState() #hvis denne sjekkes hver gang og gior false, var det ikke mulig å plassere blokken og spillet er over ffs. -#for å teste greiene -# def plaser_brikke(): -# def plaser_brikke(self): -# # Choose a random position on the board to place the brick. -# row = random.randint(0, self.rows - 1) -# col = random.randint(0, self.columns - 1) - -# # Place the brick on the board. -# self.board[row][col] = 1 - -# # Print the updated board. -# self.print_board()'' - - -# # Create an instance of the Board class. - -my_board = Board() -my_board.print_matrix() -