Skip to content

Commit

Permalink
melhorando readme
Browse files Browse the repository at this point in the history
  • Loading branch information
LuigiVanin committed Jul 2, 2022
1 parent 7afce26 commit 79b9cf7
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 43 deletions.
91 changes: 87 additions & 4 deletions README.MD
Original file line number Diff line number Diff line change
@@ -1,9 +1,92 @@
## Criando Tetris usando Python
<h1 align="center"> Tetris no terminaaaal!</h1>

<p align="center">
<img src="./assets/tetris.gif" width="425px"/>

---
</p>

## Descrição 📎

Projeto 4fun para relembrer conceitos de POO em python.
<p>
Não tem muito o que falar, é o tetris que você já conhece só que no terminal do linux! O jogo é completamente feito com caracteres de texto(unicode) e respodende a eventos de teclado. Foi tudo escrito em python🐍.

Tal projeto consiste na criação do jogo tetris no cosole linux usando python.
## Requisitos ❗

- Git
- Python 3.8+
- Pip 20
- Ubuntu

_OBS.:_ **O código pode facilmente rodar em outros sistemas**, porém só testei em meu ambiente, logo, não posso garantir nenhuma compatibilidade

## Como baixar e rodar 🚀

- Primeiramente é necessário baixar o código fonte do repositório:

```bash
git clone https://github.com/LuigiVanin/Tetris-on-Python.git
```

- Após isso é necessário instalar as bibliotecas com sudo(!). O sudo é necessário, pois a biblioteca keyboard precisa de acesso máximo para conseguir captar os eventos de teclado(😔).

```bash
sudo pip3 install -r requirements.txt
```

- Com as bibliotecas baixadas agora podemos aproveitar do jogo. Basta rodar o script main com sudo!

```bash
sudo python3 main.py
```

- Aproveite a gameplay🚀🚀🚀

## Como Jogar 🎮

- Movimentação:

- Esquerda → **A**
- Direita → **D**
- Baixo → **S**
- Cima → **W**

- Rotação:

- Horário → **K**
- Anti-Horário → **J**

- Extra:
- Encerrar o Jogo → **Ctr+Z**

## Como funciona ❓

Para fazer o Tetris funcionar é utilizado o espaço vazio com uma calaração diferente para que seja possível representar blocos e o fundo, a realização da curtomização das cores se usar os código ANSI de cores([Link](https://raccoon.ninja/pt/dev-pt/tabela-de-cores-ansi-python/)).
A atualização da tela, na verdade, não é atualização dos pixels em sí, na verdade o que o código faz é printar um novo tabuleiro abaixo do anterior, porém com muito espaço entre eles, dando a impressão de uma nova tela. Há melhores maneiras de fazer isso? Sim, como por exemplo utilizando a biblioteca nativa do python [curses](https://pypi.org/project/windows-curses/), mas optei por uma implementação mais "bruta" usando prints rsrsrs.
Para gerar o tabuleiro utilizei a famosa lib numpy, pois gosto do sistema de arrays multidimensionais, sendo assim mais fácil de trabalhar com matrizes.

## Ferramentas Utilizadas 🛠️

<br>

<p align="center">
<img src="https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54">
<img src="https://img.shields.io/badge/numpy-%23013243.svg?style=for-the-badge&logo=numpy&logoColor=white" />
<img src="https://img.shields.io/badge/Git-E34F26?style=for-the-badge&logo=git&logoColor=white" />
</p>

## Outras Ferramentas 📦

- [Keyboard](https://pypi.org/project/keyboard/).

## Entre em contato 📞

<br>

<p align="center">
<a href="https://www.linkedin.com/in/luis-felipe-vanin-martins-5a5b38215">
<img src="https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=blue">
</a>
<a href="mailto:luisfvanin2@gmail.com">
<img src="https://img.shields.io/badge/Gmail:%20luisfvanin2@gmail.com-D14836?style=for-the-badge&logo=gmail&logoColor=white">
</a>
</p>
Binary file added assets/tetris.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2021 Luis Felipe Vanin

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11 changes: 6 additions & 5 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from modules.models.models import Board
from modules.models.board import Board
from modules.utils.utils import KeyBoardMove


def main():

buttonLeft = KeyBoardMove('a')
Expand All @@ -16,12 +17,12 @@ def main():
while True:
if board.updateBoardCheck.timeCheck(buttonSpeed.HoldMove()):
board.pieceDrop()

buttonLeft.PressedMove(board.pieceLeft)
buttonRight.PressedMove(board.pieceRight)
buttonRight.PressedMove(board.pieceRight)
buttonRotate.PressedMove(board.pieceRotate)
buttonUnRotate.PressedMove(board.pieceUnRotate)


if __name__ == "__main__":
main()

main()
2 changes: 1 addition & 1 deletion modules/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from .pieces import *
from .models import *
from .board import *
File renamed without changes.
72 changes: 39 additions & 33 deletions modules/utils/utils.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
from typing import Union
from config import *
from modules.models.pieces import *
from modules.models.pieces import *
# from ..models import *

class KeyBoardMove():
def __init__(self, key : str):

class KeyBoardMove():
def __init__(self, key: str):
self._button_toggle = False
self.key = key

def PressedMove(self, move: Callable) -> bool:
if keyboard.is_pressed(self.key):
if self._button_toggle == False:
move()
move()
self._button_toggle = True
else:
self._button_toggle = False
self._button_toggle = False

def HoldMove(self) -> bool:
return keyboard.is_pressed(self.key)
Expand All @@ -25,15 +27,15 @@ def __init__(self):
self._speed = 0
self.mult: float = 0.3

def timeCheck(self, speed : bool = False) -> bool:
def timeCheck(self, speed: bool = False) -> bool:
if speed == False:
self._time += 1
if self._time == 200000*self.mult:
self._time = 0
return True
else:
return False
else:
else:
self._speed += 1
if self._speed == 200000*(self.mult/10):
self._speed = 0
Expand All @@ -42,12 +44,12 @@ def timeCheck(self, speed : bool = False) -> bool:
return False


def choosePiece() -> (PieceA, PieceB, PieceC, PieceD, PieceE):
type = random.choice([1,2,3,4,5]) # quantidade de peças a de definir
def choosePiece() -> Union[PieceA, PieceB, PieceC, PieceD, PieceE]:
type = random.choice([1, 2, 3, 4, 5]) # quantidade de peças a de definir
print(type)
if (type == 1):
return PieceA()

elif (type == 2):
return PieceB()

Expand All @@ -61,9 +63,9 @@ def choosePiece() -> (PieceA, PieceB, PieceC, PieceD, PieceE):
return PieceE()


def printFormat(format : Optional[Piece],
endrow : str = "\n",
end : str = "\n") -> None:
def printFormat(format: Optional[Piece],
endrow: str = "\n",
end: str = "\n") -> None:

if type(format) != list:
format = list(format)
Expand All @@ -77,43 +79,47 @@ def printFormat(format : Optional[Piece],
def matrixSize(matrix: List[List[Optional[int]]]) -> Tuple[int, int]:
return (len(matrix), len(matrix[0]))

def unRotateMatrix(matrix : List[List[Optional[int]]]) -> List[List[Optional[int]]]:

def unRotateMatrix(matrix: List[List[Optional[int]]]) -> List[List[Optional[int]]]:
final = []
tmp = []
row, column = matrixSize(matrix)
for j in range(column - 1, -1, -1):
for i in range(row):
tmp.append(matrix[i][j])
tmp.append(matrix[i][j])
final.append(tmp)
tmp = []

return final

def rotateMatrix(matrix : List[List[Optional[int]]]) -> List[List[Optional[int]]]:

def rotateMatrix(matrix: List[List[Optional[int]]]) -> List[List[Optional[int]]]:
final = []
tmp = []
row, column = matrixSize(matrix)
for j in range(column):
for i in range(row - 1, -1, -1):
tmp.append(matrix[i][j])
tmp.append(matrix[i][j])
final.append(tmp)
tmp = []
return final


def printBoard(table: ndarray) -> None:
print('\n' * 20)
for i in table:
for item in i:
if item == 0:
print('\x1b[%sm %s \x1b[0m' % ("0;37;40" ,"" ), end="") #branco = "0;37;47"
elif item == 1:
print('\x1b[%sm %s \x1b[0m' % ("0;37;45" ,"" ), end="")
elif item == 2:
print('\x1b[%sm %s \x1b[0m' % ("0;37;44" ,"" ), end="")
elif item == 3:
print('\x1b[%sm %s \x1b[0m' % ("0;37;42" ,"" ), end="")
elif item == 4:
print('\x1b[%sm %s \x1b[0m' % ("0;37;43" ,"" ), end="")
else:
print('\x1b[%sm %s \x1b[0m' % ("0;37;41" ,"" ), end="")
print()
print('\n' * 20)
for i in table:
for item in i:
if item == 0:
print('\x1b[%sm %s \x1b[0m' %
("0;37;40", ""), end="") # branco = "0;37;47"
elif item == 1:
print('\x1b[%sm %s \x1b[0m' % ("0;37;45", ""), end="")
elif item == 2:
print('\x1b[%sm %s \x1b[0m' % ("0;37;44", ""), end="")
elif item == 3:
print('\x1b[%sm %s \x1b[0m' % ("0;37;42", ""), end="")
elif item == 4:
print('\x1b[%sm %s \x1b[0m' % ("0;37;43", ""), end="")
else:
print('\x1b[%sm %s \x1b[0m' % ("0;37;41", ""), end="")
print()

0 comments on commit 79b9cf7

Please sign in to comment.