Compare commits
50 Commits
3b4bf3c8a2
...
0.1
Author | SHA1 | Date | |
---|---|---|---|
abaeb3be9a | |||
dff4ae487a | |||
5c830fd828 | |||
a46c07af8b | |||
338371f443 | |||
a95463438e | |||
06fe72d8db | |||
4a69c12349 | |||
2bd75be892 | |||
3015a36984 | |||
7fc342e061 | |||
0e68ea4e51 | |||
b95478ea8d | |||
df8257c4da | |||
0b3dd847d3 | |||
2a7900586c | |||
be66bada11 | |||
02e4aa066d | |||
5b6cfd6512 | |||
f1ffb1a7c6 | |||
dda475a584 | |||
b8e20199af | |||
4c44089f41 | |||
f2bbafeb8b | |||
54f2554b2a | |||
5f10bd782e | |||
9aa461fe07 | |||
ca0a18a8c5 | |||
ecd2915b12 | |||
ab8afe6fdd | |||
fa9a323af1 | |||
c2ec677f3f | |||
11c6321f17 | |||
58a7736d53 | |||
578f33ae64 | |||
00e2adf60c | |||
b1cef21f00 | |||
2c4808312f | |||
9db4f4d122 | |||
850aad353e | |||
97b687c085 | |||
a654458610 | |||
f7a47efecf | |||
59b21145f4 | |||
1437207c5d | |||
759c6f2054 | |||
4edad3c1cf | |||
d70173f87b | |||
f5225b3a55 | |||
70c69b3b7b |
18
README.md
@ -2,9 +2,11 @@
|
||||
|
||||
Tetris clone made with Python and Arcade graphic library
|
||||
|
||||

|
||||
|
||||
## Requirements
|
||||
|
||||
* [Python](https://www.python.org/)
|
||||
* [Python](https://www.python.org/) 3.6 or upper
|
||||
|
||||
## Install
|
||||
|
||||
@ -19,3 +21,17 @@ python -m pip install -r requirements.txt
|
||||
```shell
|
||||
python tetrarcade.py
|
||||
```
|
||||
|
||||
## Settings
|
||||
|
||||
* Windows: Edit `%appdata%\Tetrarcade\TetrArcade.ini`
|
||||
* Linux: Edit `~/.local/share/Tetrarcade/TetrArcade.ini`
|
||||
|
||||
Use key name from [arcade.key package](http://arcade.academy/arcade.key.html).
|
||||
|
||||
## Build
|
||||
|
||||
```shell
|
||||
python -m pip install -r build-requirements.txt
|
||||
python setup.py bdist
|
||||
```
|
||||
|
491
TetrArcade.py
Normal file
@ -0,0 +1,491 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import locale
|
||||
import time
|
||||
import os
|
||||
|
||||
import configparser
|
||||
|
||||
try:
|
||||
import arcade
|
||||
except ImportError as e:
|
||||
sys.exit(
|
||||
str(e)
|
||||
+ """
|
||||
This game require arcade library.
|
||||
You can install it with:
|
||||
python -m pip install --user arcade"""
|
||||
)
|
||||
|
||||
from tetrislogic import TetrisLogic, Color, State
|
||||
|
||||
|
||||
# Constants
|
||||
# Window
|
||||
WINDOW_WIDTH = 800
|
||||
WINDOW_HEIGHT = 600
|
||||
WINDOW_MIN_WIDTH = 517
|
||||
WINDOW_MIN_HEIGHT = 388
|
||||
WINDOW_TITLE = "TETRARCADE"
|
||||
BG_COLOR = (7, 11, 21)
|
||||
|
||||
# Delays (seconds)
|
||||
HIGHLIGHT_TEXT_DISPLAY_DELAY = 0.7
|
||||
|
||||
# Transparency (0=invisible, 255=opaque)
|
||||
NORMAL_ALPHA = 200
|
||||
PRELOCKED_ALPHA = 100
|
||||
GHOST_ALPHA = 30
|
||||
MATRIX_BG_ALPHA = 100
|
||||
BAR_ALPHA = 75
|
||||
|
||||
# Sprites
|
||||
WINDOW_BG_PATH = "res/bg.jpg"
|
||||
MATRIX_BG_PATH = "res/matrix.png"
|
||||
HELD_BG_PATH = "res/held.png"
|
||||
NEXT_BG_PATH = "res/next.png"
|
||||
MINOES_SPRITES_PATH = "res/minoes.png"
|
||||
Color.PRELOCKED = 7
|
||||
MINOES_COLOR_ID = {
|
||||
Color.BLUE: 0,
|
||||
Color.CYAN: 1,
|
||||
Color.GREEN: 2,
|
||||
Color.MAGENTA: 3,
|
||||
Color.ORANGE: 4,
|
||||
Color.RED: 5,
|
||||
Color.YELLOW: 6,
|
||||
Color.PRELOCKED: 7,
|
||||
}
|
||||
MINO_SIZE = 20
|
||||
MINO_SPRITE_SIZE = 21
|
||||
TEXTURES = arcade.load_textures(
|
||||
MINOES_SPRITES_PATH, ((i * MINO_SPRITE_SIZE, 0, MINO_SPRITE_SIZE, MINO_SPRITE_SIZE) for i in range(8))
|
||||
)
|
||||
TEXTURES = {color: TEXTURES[i] for color, i in MINOES_COLOR_ID.items()}
|
||||
|
||||
# User profile path
|
||||
if sys.platform == "win32":
|
||||
USER_PROFILE_DIR = os.environ.get("appdata", os.path.expanduser("~\Appdata\Roaming"))
|
||||
else:
|
||||
USER_PROFILE_DIR = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
|
||||
USER_PROFILE_DIR = os.path.join(USER_PROFILE_DIR, "TetrArcade")
|
||||
HIGH_SCORE_PATH = os.path.join(USER_PROFILE_DIR, ".high_score")
|
||||
CONF_PATH = os.path.join(USER_PROFILE_DIR, "TetrArcade.ini")
|
||||
|
||||
# Text
|
||||
TEXT_COLOR = arcade.color.BUBBLES
|
||||
FONT_NAME = "res/joystix monospace.ttf"
|
||||
STATS_TEXT_MARGIN = 40
|
||||
STATS_TEXT_SIZE = 14
|
||||
STATS_TEXT_WIDTH = 150
|
||||
HIGHLIGHT_TEXT_COLOR = arcade.color.BUBBLES
|
||||
HIGHLIGHT_TEXT_SIZE = 20
|
||||
|
||||
|
||||
class MinoSprite(arcade.Sprite):
|
||||
def __init__(self, mino, window, alpha):
|
||||
super().__init__()
|
||||
self.alpha = alpha
|
||||
self.window = window
|
||||
self.append_texture(TEXTURES[mino.color])
|
||||
self.append_texture(TEXTURES[Color.PRELOCKED])
|
||||
self.set_texture(0)
|
||||
|
||||
def refresh(self, x, y, prelocked=False):
|
||||
self.scale = self.window.scale
|
||||
size = MINO_SIZE * self.scale
|
||||
self.left = self.window.matrix_bg.left + x * size
|
||||
self.bottom = self.window.matrix_bg.bottom + y * size
|
||||
self.set_texture(prelocked)
|
||||
|
||||
|
||||
class MinoesSprites(arcade.SpriteList):
|
||||
def resize(self, scale):
|
||||
for sprite in self:
|
||||
sprite.scale = scale
|
||||
self.refresh()
|
||||
|
||||
|
||||
class TetrominoSprites(MinoesSprites):
|
||||
def __init__(self, tetromino, window, alpha=NORMAL_ALPHA):
|
||||
super().__init__()
|
||||
self.tetromino = tetromino
|
||||
self.alpha = alpha
|
||||
for mino in tetromino:
|
||||
mino.sprite = MinoSprite(mino, window, alpha)
|
||||
self.append(mino.sprite)
|
||||
|
||||
def refresh(self):
|
||||
for mino in self.tetromino:
|
||||
coord = mino.coord + self.tetromino.coord
|
||||
mino.sprite.refresh(coord.x, coord.y, self.tetromino.prelocked)
|
||||
|
||||
|
||||
class MatrixSprites(MinoesSprites):
|
||||
def __init__(self, matrix):
|
||||
super().__init__()
|
||||
self.matrix = matrix
|
||||
self.refresh()
|
||||
|
||||
def refresh(self):
|
||||
for y, line in enumerate(self.matrix):
|
||||
for x, mino in enumerate(line):
|
||||
if mino:
|
||||
mino.sprite.refresh(x, y)
|
||||
self.append(mino.sprite)
|
||||
|
||||
|
||||
class TetrArcade(TetrisLogic, arcade.Window):
|
||||
def __init__(self):
|
||||
locale.setlocale(locale.LC_ALL, "")
|
||||
self.highlight_texts = []
|
||||
self.tasks = {}
|
||||
|
||||
self.conf = configparser.ConfigParser()
|
||||
if self.conf.read(CONF_PATH):
|
||||
try:
|
||||
self.load_conf()
|
||||
except:
|
||||
self.new_conf()
|
||||
self.load_conf()
|
||||
else:
|
||||
self.new_conf()
|
||||
self.load_conf()
|
||||
|
||||
super().__init__()
|
||||
arcade.Window.__init__(
|
||||
self,
|
||||
width=self.init_width,
|
||||
height=self.init_height,
|
||||
title=WINDOW_TITLE,
|
||||
resizable=True,
|
||||
antialiasing=False,
|
||||
fullscreen=self.init_fullscreen,
|
||||
)
|
||||
|
||||
arcade.set_background_color(BG_COLOR)
|
||||
self.set_minimum_size(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGHT)
|
||||
self.bg = arcade.Sprite(WINDOW_BG_PATH)
|
||||
self.matrix_bg = arcade.Sprite(MATRIX_BG_PATH)
|
||||
self.matrix_bg.alpha = MATRIX_BG_ALPHA
|
||||
self.held_bg = arcade.Sprite(HELD_BG_PATH)
|
||||
self.held_bg.alpha = BAR_ALPHA
|
||||
self.next_bg = arcade.Sprite(NEXT_BG_PATH)
|
||||
self.next_bg.alpha = BAR_ALPHA
|
||||
self.matrix.sprites = MatrixSprites(self.matrix)
|
||||
self.on_resize(self.init_width, self.init_height)
|
||||
|
||||
def new_conf(self):
|
||||
self.conf["WINDOW"] = {"width": WINDOW_WIDTH, "height": WINDOW_HEIGHT, "fullscreen": False}
|
||||
self.conf["KEYBOARD"] = {
|
||||
"start": "ENTER",
|
||||
"move left": "LEFT",
|
||||
"move right": "RIGHT",
|
||||
"soft drop": "DOWN",
|
||||
"hard drop": "SPACE",
|
||||
"rotate clockwise": "UP",
|
||||
"rotate counter": "Z",
|
||||
"hold": "C",
|
||||
"pause": "ESCAPE",
|
||||
"fullscreen": "F11",
|
||||
}
|
||||
self.conf["AUTO-REPEAT"] = {"delay": 0.3, "period": 0.01}
|
||||
self.load_conf()
|
||||
if not os.path.exists(USER_PROFILE_DIR):
|
||||
os.makedirs(USER_PROFILE_DIR)
|
||||
with open(CONF_PATH, "w") as f:
|
||||
self.conf.write(f)
|
||||
|
||||
def load_conf(self):
|
||||
self.init_width = int(self.conf["WINDOW"]["width"])
|
||||
self.init_height = int(self.conf["WINDOW"]["height"])
|
||||
self.init_fullscreen = self.conf["WINDOW"].getboolean("fullscreen")
|
||||
|
||||
for action, key in self.conf["KEYBOARD"].items():
|
||||
self.conf["KEYBOARD"][action] = key.upper()
|
||||
self.key_map = {
|
||||
State.STARTING: {
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["start"]): self.new_game,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["fullscreen"]): self.toggle_fullscreen,
|
||||
},
|
||||
State.PLAYING: {
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["move left"]): self.move_left,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["move right"]): self.move_right,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["soft drop"]): self.soft_drop,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["hard drop"]): self.hard_drop,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["rotate clockwise"]): self.rotate_clockwise,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["rotate counter"]): self.rotate_counter,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["hold"]): self.swap,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["pause"]): self.pause,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["fullscreen"]): self.toggle_fullscreen,
|
||||
},
|
||||
State.PAUSED: {
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["pause"]): self.resume,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["fullscreen"]): self.toggle_fullscreen,
|
||||
},
|
||||
State.OVER: {
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["start"]): self.new_game,
|
||||
getattr(arcade.key, self.conf["KEYBOARD"]["fullscreen"]): self.toggle_fullscreen,
|
||||
},
|
||||
}
|
||||
|
||||
self.AUTOREPEAT_DELAY = float(self.conf["AUTO-REPEAT"]["delay"])
|
||||
self.AUTOREPEAT_PERIOD = float(self.conf["AUTO-REPEAT"]["period"])
|
||||
|
||||
controls_text = (
|
||||
"\n\n\nCONTROLS\n\n"
|
||||
+ "\n".join(
|
||||
"{:<16s}{:>6s}".format(key, action)
|
||||
for key, action in tuple(self.conf["KEYBOARD"].items()) + (("QUIT", "ALT+F4"),)
|
||||
)
|
||||
+ "\n\n\n"
|
||||
)
|
||||
self.start_text = "TETRARCADE" + controls_text + "PRESS [{}] TO START".format(self.conf["KEYBOARD"]["start"])
|
||||
self.pause_text = "PAUSE" + controls_text + "PRESS [{}] TO RESUME".format(self.conf["KEYBOARD"]["pause"])
|
||||
self.game_over_text = """GAME
|
||||
OVER
|
||||
|
||||
PRESS
|
||||
[{}]
|
||||
TO PLAY
|
||||
AGAIN""".format(
|
||||
self.conf["KEYBOARD"]["start"]
|
||||
)
|
||||
|
||||
def new_game(self):
|
||||
self.highlight_texts = []
|
||||
super().new_game()
|
||||
|
||||
def new_tetromino(self):
|
||||
tetromino = super().new_tetromino()
|
||||
tetromino.sprites = TetrominoSprites(tetromino, self)
|
||||
return tetromino
|
||||
|
||||
def new_current(self):
|
||||
self.matrix.sprites = MatrixSprites(self.matrix)
|
||||
super().new_current()
|
||||
self.ghost.sprites = TetrominoSprites(self.ghost, self, GHOST_ALPHA)
|
||||
for tetromino in [self.current, self.ghost] + self.next:
|
||||
tetromino.sprites.refresh()
|
||||
|
||||
def move(self, movement, prelock=True):
|
||||
moved = super().move(movement, prelock)
|
||||
self.current.sprites.refresh()
|
||||
if moved:
|
||||
self.ghost.sprites.refresh()
|
||||
return moved
|
||||
|
||||
def rotate(self, rotation):
|
||||
rotated = super().rotate(rotation)
|
||||
if rotated:
|
||||
for tetromino in (self.current, self.ghost):
|
||||
tetromino.sprites.refresh()
|
||||
return rotated
|
||||
|
||||
def swap(self):
|
||||
super().swap()
|
||||
self.ghost.sprites = TetrominoSprites(self.ghost, self, GHOST_ALPHA)
|
||||
for tetromino in [self.held, self.current, self.ghost]:
|
||||
if tetromino:
|
||||
tetromino.sprites.refresh()
|
||||
|
||||
def lock(self):
|
||||
self.current.prelocked = False
|
||||
self.current.sprites.refresh()
|
||||
super().lock()
|
||||
|
||||
def on_key_press(self, key, modifiers):
|
||||
for key_or_modifier in (key, modifiers):
|
||||
try:
|
||||
action = self.key_map[self.state][key_or_modifier]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
self.do_action(action)
|
||||
|
||||
def on_key_release(self, key, modifiers):
|
||||
for key_or_modifier in (key, modifiers):
|
||||
try:
|
||||
action = self.key_map[self.state][key_or_modifier]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
self.remove_action(action)
|
||||
|
||||
def show_text(self, text):
|
||||
self.highlight_texts.append(text)
|
||||
self.restart(self.del_highlight_text, HIGHLIGHT_TEXT_DISPLAY_DELAY)
|
||||
|
||||
def del_highlight_text(self):
|
||||
if self.highlight_texts:
|
||||
self.highlight_texts.pop(0)
|
||||
else:
|
||||
self.stop(self.del_highlight_text)
|
||||
|
||||
def on_draw(self):
|
||||
arcade.start_render()
|
||||
self.bg.draw()
|
||||
|
||||
if self.state in (State.PLAYING, State.OVER):
|
||||
self.matrix_bg.draw()
|
||||
self.held_bg.draw()
|
||||
self.next_bg.draw()
|
||||
self.matrix.sprites.draw()
|
||||
|
||||
for tetromino in [self.held, self.current, self.ghost] + self.next:
|
||||
if tetromino:
|
||||
tetromino.sprites.draw()
|
||||
|
||||
t = time.localtime(self.time)
|
||||
font_size = STATS_TEXT_SIZE * self.scale
|
||||
for y, text in enumerate(("TIME", "LINES", "GOAL", "LEVEL", "HIGH SCORE", "SCORE")):
|
||||
arcade.draw_text(
|
||||
text=text,
|
||||
start_x=self.matrix_bg.left - self.scale * (STATS_TEXT_MARGIN + STATS_TEXT_WIDTH),
|
||||
start_y=self.matrix_bg.bottom + 1.5 * (2 * y + 1) * font_size,
|
||||
color=TEXT_COLOR,
|
||||
font_size=font_size,
|
||||
align="right",
|
||||
font_name=FONT_NAME,
|
||||
anchor_x="left",
|
||||
)
|
||||
for y, text in enumerate(
|
||||
(
|
||||
"{:02d}:{:02d}:{:02d}".format(t.tm_hour - 1, t.tm_min, t.tm_sec),
|
||||
"{:n}".format(self.nb_lines_cleared),
|
||||
"{:n}".format(self.goal),
|
||||
"{:n}".format(self.level),
|
||||
"{:n}".format(self.high_score),
|
||||
"{:n}".format(self.score),
|
||||
)
|
||||
):
|
||||
arcade.draw_text(
|
||||
text=text,
|
||||
start_x=self.matrix_bg.left - STATS_TEXT_MARGIN * self.scale,
|
||||
start_y=self.matrix_bg.bottom + 3 * y * font_size,
|
||||
color=TEXT_COLOR,
|
||||
font_size=font_size,
|
||||
align="right",
|
||||
font_name=FONT_NAME,
|
||||
anchor_x="right",
|
||||
)
|
||||
|
||||
highlight_text = {
|
||||
State.STARTING: self.start_text,
|
||||
State.PLAYING: self.highlight_texts[0] if self.highlight_texts else "",
|
||||
State.PAUSED: self.pause_text,
|
||||
State.OVER: self.game_over_text,
|
||||
}.get(self.state, "")
|
||||
if highlight_text:
|
||||
arcade.draw_text(
|
||||
text=highlight_text,
|
||||
start_x=self.matrix_bg.center_x,
|
||||
start_y=self.matrix_bg.center_y,
|
||||
color=HIGHLIGHT_TEXT_COLOR,
|
||||
font_size=HIGHLIGHT_TEXT_SIZE * self.scale,
|
||||
align="center",
|
||||
font_name=FONT_NAME,
|
||||
anchor_x="center",
|
||||
anchor_y="center",
|
||||
)
|
||||
|
||||
def on_hide(self):
|
||||
self.pause()
|
||||
|
||||
def toggle_fullscreen(self):
|
||||
self.set_fullscreen(not self.fullscreen)
|
||||
|
||||
def on_resize(self, width, height):
|
||||
super().on_resize(width, height)
|
||||
center_x = width / 2
|
||||
center_y = height / 2
|
||||
self.scale = min(width / WINDOW_WIDTH, height / WINDOW_HEIGHT)
|
||||
|
||||
self.bg.scale = max(width / WINDOW_WIDTH, height / WINDOW_HEIGHT)
|
||||
self.bg.center_x = center_x
|
||||
self.bg.center_y = center_y
|
||||
|
||||
self.matrix_bg.scale = self.scale
|
||||
self.matrix_bg.center_x = center_x
|
||||
self.matrix_bg.center_y = center_y
|
||||
self.matrix_bg.left = int(self.matrix_bg.left)
|
||||
self.matrix_bg.top = int(self.matrix_bg.top)
|
||||
|
||||
self.held_bg.scale = self.scale
|
||||
self.held_bg.right = self.matrix_bg.left
|
||||
self.held_bg.top = self.matrix_bg.top
|
||||
|
||||
self.next_bg.scale = self.scale
|
||||
self.next_bg.left = self.matrix_bg.right
|
||||
self.next_bg.top = self.matrix_bg.top
|
||||
|
||||
self.matrix.sprites.resize(self.scale)
|
||||
|
||||
for tetromino in [self.held, self.current, self.ghost] + self.next:
|
||||
if tetromino:
|
||||
tetromino.sprites.resize(self.scale)
|
||||
|
||||
def load_high_score(self):
|
||||
try:
|
||||
with open(HIGH_SCORE_PATH, "rb") as f:
|
||||
crypted_high_score = f.read()
|
||||
super().load_high_score(crypted_high_score)
|
||||
except:
|
||||
self.high_score = 0
|
||||
|
||||
def save_high_score(self):
|
||||
try:
|
||||
if not os.path.exists(USER_PROFILE_DIR):
|
||||
os.makedirs(USER_PROFILE_DIR)
|
||||
with open(HIGH_SCORE_PATH, mode="wb") as f:
|
||||
crypted_high_score = super().save_high_score()
|
||||
f.write(crypted_high_score)
|
||||
except Exception as e:
|
||||
sys.exit(
|
||||
"""High score: {:n}
|
||||
High score could not be saved:
|
||||
""".format(
|
||||
self.high_score
|
||||
)
|
||||
+ str(e)
|
||||
)
|
||||
|
||||
def start(self, task, period):
|
||||
_task = lambda _: task()
|
||||
self.tasks[task] = _task
|
||||
arcade.schedule(_task, period)
|
||||
|
||||
def stop(self, task):
|
||||
try:
|
||||
_task = self.tasks[task]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
arcade.unschedule(_task)
|
||||
del self.tasks[task]
|
||||
|
||||
def restart(self, task, period):
|
||||
try:
|
||||
_task = self.tasks[task]
|
||||
except KeyError:
|
||||
_task = lambda _: task()
|
||||
self.tasks[task] = _task
|
||||
else:
|
||||
arcade.unschedule(_task)
|
||||
arcade.schedule(_task, period)
|
||||
|
||||
def on_close(self):
|
||||
self.save_high_score()
|
||||
super().on_close()
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
TetrArcade()
|
||||
arcade.run()
|
||||
except Exception as e:
|
||||
sys.exit(e)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
1
build-requirements.txt
Normal file
@ -0,0 +1 @@
|
||||
arcade cx-freeze
|
BIN
icon48.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
Before Width: | Height: | Size: 165 B |
Before Width: | Height: | Size: 151 B |
Before Width: | Height: | Size: 167 B |
Before Width: | Height: | Size: 165 B |
Before Width: | Height: | Size: 165 B |
Before Width: | Height: | Size: 165 B |
Before Width: | Height: | Size: 143 B |
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 153 KiB |
BIN
res/held.png
Normal file
After Width: | Height: | Size: 499 B |
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
BIN
res/minoes.png
Normal file
After Width: | Height: | Size: 389 B |
BIN
res/next.png
Normal file
After Width: | Height: | Size: 475 B |
43
setup.py
Normal file
@ -0,0 +1,43 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
from cx_Freeze import setup, Executable
|
||||
|
||||
if sys.platform == "win32":
|
||||
base = "Win32GUI"
|
||||
icon = "icon.ico"
|
||||
else:
|
||||
base = None
|
||||
icon = None
|
||||
|
||||
excludes = [
|
||||
"tkinter",
|
||||
"PyQt4",
|
||||
"PyQt5",
|
||||
"PySide",
|
||||
"PySide2"
|
||||
]
|
||||
|
||||
executable = Executable(
|
||||
script = "TetrArcade.py",
|
||||
icon = icon,
|
||||
base = base,
|
||||
shortcutName="TetrArcade",
|
||||
shortcutDir="DesktopFolder"
|
||||
)
|
||||
|
||||
options = {
|
||||
"build_exe": {
|
||||
"packages": ["arcade", "pyglet"],
|
||||
"excludes": excludes,
|
||||
"include_files": "res",
|
||||
"silent": True
|
||||
}
|
||||
}
|
||||
setup(
|
||||
name = "TetrArcade",
|
||||
version = "0.1",
|
||||
description = "Tetris clone",
|
||||
author = "AdrienMalin",
|
||||
executables = [executable],
|
||||
options = options,
|
||||
)
|
15
test.py
Normal file
@ -0,0 +1,15 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from TetrArcade import TetrArcade, State
|
||||
|
||||
game = TetrArcade()
|
||||
game.new_game()
|
||||
game.move_left()
|
||||
game.move_right()
|
||||
game.rotate_clockwise()
|
||||
game.rotate_counter()
|
||||
for i in range(12):
|
||||
game.soft_drop()
|
||||
game.on_draw()
|
||||
while game.state != State.OVER:
|
||||
game.hard_drop()
|
407
tetrarcade.py
@ -1,407 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys
|
||||
import locale
|
||||
import time
|
||||
import os
|
||||
|
||||
try:
|
||||
import arcade
|
||||
except ImportError:
|
||||
sys.exit(
|
||||
"""This game require arcade library.
|
||||
You can install it with:
|
||||
python -m pip install --user arcade"""
|
||||
)
|
||||
|
||||
from tetrislogic import TetrisLogic, State
|
||||
|
||||
|
||||
# Constants
|
||||
# Window
|
||||
WINDOW_WIDTH = 800
|
||||
WINDOW_HEIGHT = 600
|
||||
WINDOW_TITLE = "TETRARCADE"
|
||||
|
||||
# Delays (seconds)
|
||||
HIGHLIGHT_TEXT_DISPLAY_DELAY = 0.7
|
||||
|
||||
# Transparency (0=invisible, 255=opaque)
|
||||
NORMAL_ALPHA = 200
|
||||
PRELOCKED_ALPHA = 100
|
||||
GHOST_ALPHA = 30
|
||||
MATRIX_SPRITE_ALPHA = 100
|
||||
|
||||
# Paths
|
||||
WINDOW_BG_PATH = "images/bg.jpg"
|
||||
MATRIX_SPRITE_PATH = "images/matrix.png"
|
||||
MINOES_SPRITES_PATHS = {
|
||||
"orange": "images/orange_mino.png",
|
||||
"blue": "images/blue_mino.png",
|
||||
"yellow": "images/yellow_mino.png",
|
||||
"cyan": "images/cyan_mino.png",
|
||||
"green": "images/green_mino.png",
|
||||
"red": "images/red_mino.png",
|
||||
"magenta": "images/magenta_mino.png"
|
||||
}
|
||||
if sys.platform == "win32":
|
||||
USER_PROFILE_DIR = os.environ.get("appdata", os.path.expanduser("~\Appdata\Roaming"))
|
||||
else:
|
||||
USER_PROFILE_DIR = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
|
||||
USER_PROFILE_DIR = os.path.join(USER_PROFILE_DIR, "TetrArcade")
|
||||
HIGH_SCORE_PATH = os.path.join(USER_PROFILE_DIR, ".high_score")
|
||||
|
||||
# Text
|
||||
TEXT_COLOR = arcade.color.BUBBLES
|
||||
HIGHLIGHT_TEXT_COLOR = arcade.color.BUBBLES
|
||||
FONT_NAME = "joystix monospace.ttf"
|
||||
TEXT_MARGIN = 40
|
||||
FONT_SIZE = 16
|
||||
TEXT_HEIGHT = 20.8
|
||||
HIGHLIGHT_TEXT_FONT_SIZE = 20
|
||||
|
||||
CONTROL_TEXT = """
|
||||
|
||||
|
||||
CONTROLS
|
||||
|
||||
MOVE LEFT ←
|
||||
MOVE RIGHT →
|
||||
SOFT DROP ↓
|
||||
HARD DROP SPACE
|
||||
ROTATE CLOCKWISE ↑
|
||||
ROTATE COUNTER Z
|
||||
HOLD C
|
||||
PAUSE ESC
|
||||
|
||||
|
||||
"""
|
||||
START_TEXT = "TETRARCADE" + CONTROL_TEXT + "PRESS [ENTER] TO START"
|
||||
PAUSE_TEXT = "PAUSE" + CONTROL_TEXT + "PRESS [ESC] TO RESUME"
|
||||
STATS_TEXT = """SCORE
|
||||
|
||||
HIGH SCORE
|
||||
|
||||
LEVEL
|
||||
|
||||
GOAL
|
||||
|
||||
LINES
|
||||
|
||||
TIME
|
||||
"""
|
||||
GAME_OVER_TEXT = """GAME
|
||||
OVER
|
||||
|
||||
PRESS
|
||||
[ENTER]
|
||||
TO PLAY
|
||||
AGAIN"""
|
||||
|
||||
|
||||
class MinoSprites(arcade.SpriteList):
|
||||
|
||||
def __init__(self, matrix):
|
||||
super().__init__()
|
||||
self.matrix = matrix
|
||||
|
||||
def update_mino(self, mino, x, y, alpha):
|
||||
mino.sprite.left = self.matrix.sprite.left + x*(mino.sprite.width-1)
|
||||
mino.sprite.bottom = self.matrix.sprite.bottom + y*(mino.sprite.height-1)
|
||||
mino.sprite.alpha = alpha
|
||||
|
||||
|
||||
class MatrixSprites(MinoSprites):
|
||||
|
||||
def __init__(self, matrix):
|
||||
super().__init__(matrix)
|
||||
for y, line in enumerate(matrix):
|
||||
for x, mino in enumerate(line):
|
||||
if mino:
|
||||
self.update_mino(mino, x, y, NORMAL_ALPHA)
|
||||
self.append(mino.sprite)
|
||||
|
||||
|
||||
class TetrominoSprites(MinoSprites):
|
||||
|
||||
def __init__(self, tetromino, matrix, alpha=NORMAL_ALPHA):
|
||||
super().__init__(matrix)
|
||||
self.tetromino = tetromino
|
||||
path = MINOES_SPRITES_PATHS[tetromino.MINOES_COLOR]
|
||||
self.alpha = alpha
|
||||
for mino in tetromino:
|
||||
mino.sprite = arcade.Sprite(path)
|
||||
mino.sprite.alpha = alpha
|
||||
self.append(mino.sprite)
|
||||
|
||||
def update(self):
|
||||
alpha = (
|
||||
PRELOCKED_ALPHA
|
||||
if self.tetromino.prelocked
|
||||
else self.alpha
|
||||
)
|
||||
for mino in self.tetromino:
|
||||
coord = mino.coord + self.tetromino.coord
|
||||
self.update_mino(mino, coord.x, coord.y, alpha)
|
||||
|
||||
|
||||
class TetrArcade(TetrisLogic, arcade.Window):
|
||||
|
||||
def __init__(self):
|
||||
locale.setlocale(locale.LC_ALL, '')
|
||||
self.highlight_texts = []
|
||||
self.tasks = {}
|
||||
|
||||
self.KEY_MAP = {
|
||||
State.STARTING: {
|
||||
arcade.key.ENTER: self.new_game
|
||||
},
|
||||
State.PLAYING: {
|
||||
arcade.key.LEFT: self.move_left,
|
||||
arcade.key.NUM_4: self.move_left,
|
||||
arcade.key.RIGHT: self.move_right,
|
||||
arcade.key.NUM_6: self.move_right,
|
||||
arcade.key.SPACE: self.hard_drop,
|
||||
arcade.key.NUM_8: self.hard_drop,
|
||||
arcade.key.DOWN: self.soft_drop,
|
||||
arcade.key.NUM_2: self.soft_drop,
|
||||
arcade.key.UP: self.rotate_clockwise,
|
||||
arcade.key.X: self.rotate_clockwise,
|
||||
arcade.key.NUM_1: self.rotate_clockwise,
|
||||
arcade.key.NUM_5: self.rotate_clockwise,
|
||||
arcade.key.NUM_9: self.rotate_clockwise,
|
||||
arcade.key.Z: self.rotate_counter,
|
||||
arcade.key.NUM_3: self.rotate_counter,
|
||||
arcade.key.NUM_7: self.rotate_counter,
|
||||
arcade.key.C: self.swap,
|
||||
arcade.key.MOD_SHIFT: self.swap,
|
||||
arcade.key.NUM_0: self.swap,
|
||||
arcade.key.ESCAPE: self.pause,
|
||||
arcade.key.F1: self.pause,
|
||||
},
|
||||
State.PAUSED: {
|
||||
arcade.key.ESCAPE: self.resume,
|
||||
arcade.key.F1: self.resume
|
||||
},
|
||||
State.OVER: {
|
||||
arcade.key.ENTER: self.new_game
|
||||
}
|
||||
}
|
||||
|
||||
super().__init__()
|
||||
|
||||
center_x = WINDOW_WIDTH / 2
|
||||
center_y = WINDOW_HEIGHT / 2
|
||||
self.bg_sprite = arcade.Sprite(WINDOW_BG_PATH)
|
||||
self.bg_sprite.center_x = center_x
|
||||
self.bg_sprite.center_y = center_y
|
||||
self.matrix.sprite = arcade.Sprite(MATRIX_SPRITE_PATH)
|
||||
self.matrix.sprite.alpha = MATRIX_SPRITE_ALPHA
|
||||
self.matrix.sprite.center_x = center_x
|
||||
self.matrix.sprite.center_y = center_y
|
||||
self.matrix.sprite.left = int(self.matrix.sprite.left)
|
||||
self.matrix.sprite.top = int(self.matrix.sprite.top)
|
||||
self.matrix.sprites = MatrixSprites(self.matrix)
|
||||
self.stats_text = arcade.create_text(
|
||||
text = STATS_TEXT,
|
||||
color = TEXT_COLOR,
|
||||
font_size = FONT_SIZE,
|
||||
font_name = FONT_NAME,
|
||||
anchor_x = 'right'
|
||||
)
|
||||
|
||||
arcade.Window.__init__(
|
||||
self,
|
||||
width = WINDOW_WIDTH,
|
||||
height = WINDOW_HEIGHT,
|
||||
title = WINDOW_TITLE,
|
||||
resizable = False,
|
||||
antialiasing = False
|
||||
)
|
||||
self.new_game()
|
||||
self.on_draw()
|
||||
|
||||
def new_game(self):
|
||||
self.highlight_texts = []
|
||||
self.matrix.sprites = MatrixSprites(self.matrix)
|
||||
super().new_game()
|
||||
|
||||
def new_next(self):
|
||||
super().new_next()
|
||||
self.next[-1].sprites = TetrominoSprites(self.next[-1], self.matrix)
|
||||
|
||||
def new_current(self):
|
||||
super().new_current()
|
||||
self.ghost.sprites = TetrominoSprites(self.ghost, self.matrix, GHOST_ALPHA)
|
||||
for tetromino in [self.current, self.ghost] + self.next:
|
||||
tetromino.sprites.update()
|
||||
|
||||
def move(self, movement, prelock=True):
|
||||
moved = super().move(movement, prelock)
|
||||
if moved or self.current.prelocked:
|
||||
for tetromino in (self.current, self.ghost):
|
||||
tetromino.sprites.update()
|
||||
return moved
|
||||
|
||||
def rotate(self, rotation):
|
||||
rotated = super().rotate(rotation)
|
||||
if rotated:
|
||||
for tetromino in (self.current, self.ghost):
|
||||
tetromino.sprites.update()
|
||||
return rotated
|
||||
|
||||
def swap(self):
|
||||
super().swap()
|
||||
self.ghost.sprites = TetrominoSprites(self.ghost, self.matrix, GHOST_ALPHA)
|
||||
for tetromino in [self.held, self.current, self.ghost]:
|
||||
if tetromino:
|
||||
tetromino.sprites.update()
|
||||
|
||||
def lock(self):
|
||||
self.current.sprites.update()
|
||||
super().lock()
|
||||
self.matrix.sprites = MatrixSprites(self.matrix)
|
||||
|
||||
def game_over(self):
|
||||
super().game_over()
|
||||
|
||||
def on_key_press(self, key, modifiers):
|
||||
for key_or_modifier in (key, modifiers):
|
||||
try:
|
||||
action = self.KEY_MAP[self.state][key_or_modifier]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
self.do_action(action)
|
||||
|
||||
def on_key_release(self, key, modifiers):
|
||||
for key_or_modifier in (key, modifiers):
|
||||
try:
|
||||
action = self.KEY_MAP[self.state][key_or_modifier]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
self.remove_action(action)
|
||||
|
||||
def show_text(self, text):
|
||||
self.highlight_texts.append(text)
|
||||
self.restart(self.del_highlight_text, HIGHLIGHT_TEXT_DISPLAY_DELAY)
|
||||
|
||||
def del_highlight_text(self):
|
||||
if self.highlight_texts:
|
||||
self.highlight_texts.pop(0)
|
||||
else:
|
||||
self.stop(self.del_highlight_text)
|
||||
|
||||
def on_draw(self):
|
||||
arcade.start_render()
|
||||
self.bg_sprite.draw()
|
||||
|
||||
if self.state in (State.PLAYING, State.OVER):
|
||||
self.matrix.sprite.draw()
|
||||
self.matrix.sprites.draw()
|
||||
for tetromino in [self.held, self.current, self.ghost] + self.next:
|
||||
if tetromino:
|
||||
tetromino.sprites.draw()
|
||||
|
||||
arcade.render_text(
|
||||
self.stats_text,
|
||||
self.matrix.sprite.left - TEXT_MARGIN,
|
||||
self.matrix.sprite.bottom
|
||||
)
|
||||
t = time.localtime(self.time)
|
||||
for y, text in enumerate(
|
||||
(
|
||||
|
||||
"{:02d}:{:02d}:{:02d}".format(
|
||||
t.tm_hour-1, t.tm_min, t.tm_sec
|
||||
),
|
||||
"{:n}".format(self.nb_lines_cleared),
|
||||
"{:n}".format(self.goal),
|
||||
"{:n}".format(self.level),
|
||||
"{:n}".format(self.high_score),
|
||||
"{:n}".format(self.score)
|
||||
)
|
||||
):
|
||||
arcade.draw_text(
|
||||
text = text,
|
||||
start_x = self.matrix.sprite.left - TEXT_MARGIN,
|
||||
start_y = self.matrix.sprite.bottom + 2*y*TEXT_HEIGHT,
|
||||
color = TEXT_COLOR,
|
||||
font_size = FONT_SIZE,
|
||||
align = 'right',
|
||||
font_name = FONT_NAME,
|
||||
anchor_x = 'right'
|
||||
)
|
||||
|
||||
highlight_text = {
|
||||
State.STARTING: START_TEXT,
|
||||
State.PLAYING: self.highlight_texts[0] if self.highlight_texts else "",
|
||||
State.PAUSED: PAUSE_TEXT,
|
||||
State.OVER: GAME_OVER_TEXT
|
||||
}.get(self.state, "")
|
||||
if highlight_text:
|
||||
arcade.draw_text(
|
||||
text = highlight_text,
|
||||
start_x = self.matrix.sprite.center_x,
|
||||
start_y = self.matrix.sprite.center_y,
|
||||
color = HIGHLIGHT_TEXT_COLOR,
|
||||
font_size = HIGHLIGHT_TEXT_FONT_SIZE,
|
||||
align = 'center',
|
||||
font_name = FONT_NAME,
|
||||
anchor_x = 'center',
|
||||
anchor_y = 'center'
|
||||
)
|
||||
|
||||
def load_high_score(self):
|
||||
try:
|
||||
with open(HIGH_SCORE_PATH, "r") as f:
|
||||
self.high_score = int(f.read())
|
||||
except:
|
||||
self.high_score = 0
|
||||
|
||||
def save_high_score(self):
|
||||
try:
|
||||
if not os.path.exists(USER_PROFILE_DIR):
|
||||
os.makedirs(USER_PROFILE_DIR)
|
||||
with open(HIGH_SCORE_PATH, mode='w') as f:
|
||||
f.write(str(self.high_score))
|
||||
except Exception as e:
|
||||
sys.exit(
|
||||
"""High score: {:n}
|
||||
High score could not be saved:
|
||||
""".format(self.high_score)
|
||||
+ str(e)
|
||||
)
|
||||
|
||||
def start(self, task, period):
|
||||
_task = lambda _: task()
|
||||
self.tasks[task] = _task
|
||||
arcade.schedule(_task, period)
|
||||
|
||||
def stop(self, task):
|
||||
try:
|
||||
_task = self.tasks[task]
|
||||
except KeyError:
|
||||
pass
|
||||
else:
|
||||
arcade.unschedule(_task)
|
||||
del self.tasks[task]
|
||||
|
||||
def restart(self, task, period):
|
||||
try:
|
||||
_task = self.tasks[task]
|
||||
except KeyError:
|
||||
_task = lambda _: task()
|
||||
self.tasks[task] = _task
|
||||
else:
|
||||
arcade.unschedule(_task)
|
||||
arcade.schedule(_task, period)
|
||||
|
||||
|
||||
def main():
|
||||
tetrarcade = TetrArcade()
|
||||
arcade.run()
|
||||
tetrarcade.save_high_score()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1,3 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from .consts import NB_LINES, NB_COLS, NB_NEXT
|
||||
from .tetrislogic import TetrisLogic, State
|
||||
from .utils import Movement, Rotation, Color
|
||||
from .tetromino import Mino, Tetromino
|
||||
from .tetrislogic import TetrisLogic, State, Matrix
|
||||
|
@ -16,9 +16,5 @@ AUTOREPEAT_PERIOD = 0.010 # Official : 0.010
|
||||
|
||||
# Piece init coord
|
||||
CURRENT_COORD = Coord(4, NB_LINES)
|
||||
NEXT_COORDS = [
|
||||
Coord(NB_COLS+6, NB_LINES-4*n-3)
|
||||
for n in range(NB_NEXT)
|
||||
]
|
||||
HELD_COORD = Coord(-7, NB_LINES-3)
|
||||
HELD_I_COORD = Coord(-7, NB_LINES-3)
|
||||
NEXT_COORDS = [Coord(NB_COLS + 4, NB_LINES - 4 * n - 3) for n in range(NB_NEXT)]
|
||||
HELD_COORD = Coord(-5, NB_LINES - 3)
|
||||
|
@ -1,15 +1,25 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from .utils import Coord, Movement, Rotation, T_Spin, Line
|
||||
from .tetromino import Tetromino
|
||||
import random
|
||||
import pickle
|
||||
|
||||
from .utils import Coord, Movement, Rotation, T_Spin
|
||||
from .tetromino import Tetromino, T, I
|
||||
from .consts import (
|
||||
NB_LINES, NB_COLS, NB_NEXT,
|
||||
LOCK_DELAY, FALL_DELAY,
|
||||
AUTOREPEAT_DELAY, AUTOREPEAT_PERIOD,
|
||||
CURRENT_COORD, NEXT_COORDS, HELD_COORD, HELD_I_COORD
|
||||
NB_LINES,
|
||||
NB_COLS,
|
||||
NB_NEXT,
|
||||
LOCK_DELAY,
|
||||
FALL_DELAY,
|
||||
AUTOREPEAT_DELAY,
|
||||
AUTOREPEAT_PERIOD,
|
||||
CURRENT_COORD,
|
||||
NEXT_COORDS,
|
||||
HELD_COORD,
|
||||
)
|
||||
|
||||
|
||||
LINES_CLEAR_NAME = "LINES_CLEAR_NAME"
|
||||
CRYPT_KEY = 987943759387540938469837689379857347598347598379584857934579343
|
||||
|
||||
|
||||
class State:
|
||||
@ -21,16 +31,23 @@ class State:
|
||||
|
||||
|
||||
class Matrix(list):
|
||||
|
||||
def cell_is_free(self, coord):
|
||||
return (
|
||||
0 <= coord.x < NB_COLS
|
||||
and 0 <= coord.y
|
||||
and not self[coord.y][coord.x]
|
||||
)
|
||||
return 0 <= coord.x < NB_COLS and 0 <= coord.y and not self[coord.y][coord.x]
|
||||
|
||||
|
||||
class TetrisLogic():
|
||||
class TetrisLogic:
|
||||
|
||||
NB_LINES = NB_LINES
|
||||
NB_COLS = NB_COLS
|
||||
NB_NEXT = NB_NEXT
|
||||
LOCK_DELAY = LOCK_DELAY
|
||||
FALL_DELAY = FALL_DELAY
|
||||
AUTOREPEAT_DELAY = AUTOREPEAT_DELAY
|
||||
AUTOREPEAT_PERIOD = AUTOREPEAT_PERIOD
|
||||
CURRENT_COORD = CURRENT_COORD
|
||||
NEXT_COORDS = NEXT_COORDS
|
||||
HELD_COORD = HELD_COORD
|
||||
random_bag = []
|
||||
|
||||
def __init__(self):
|
||||
self.load_high_score()
|
||||
@ -65,26 +82,27 @@ class TetrisLogic():
|
||||
self.pressed_actions = []
|
||||
self.auto_repeat = False
|
||||
|
||||
self.lock_delay = LOCK_DELAY
|
||||
self.fall_delay = FALL_DELAY
|
||||
self.lock_delay = self.LOCK_DELAY
|
||||
self.fall_delay = self.FALL_DELAY
|
||||
|
||||
self.matrix.clear()
|
||||
for y in range(NB_LINES+3):
|
||||
for y in range(self.NB_LINES + 3):
|
||||
self.append_new_line_to_matrix()
|
||||
self.next = []
|
||||
for n in range(NB_NEXT):
|
||||
self.new_next()
|
||||
self.next = [self.new_tetromino() for n in range(self.NB_NEXT)]
|
||||
self.held = None
|
||||
self.state = State.PLAYING
|
||||
self.start(self.update_time, 1)
|
||||
|
||||
self.new_level()
|
||||
|
||||
def new_next(self):
|
||||
self.next.append(Tetromino())
|
||||
def new_tetromino(self):
|
||||
if not self.random_bag:
|
||||
self.random_bag = list(Tetromino.shapes)
|
||||
random.shuffle(self.random_bag)
|
||||
return self.random_bag.pop()()
|
||||
|
||||
def append_new_line_to_matrix(self):
|
||||
self.matrix.append(Line(None for x in range(NB_COLS)))
|
||||
self.matrix.append([None for x in range(self.NB_COLS)])
|
||||
|
||||
def new_level(self):
|
||||
self.level += 1
|
||||
@ -100,18 +118,15 @@ class TetrisLogic():
|
||||
|
||||
def new_current(self):
|
||||
self.current = self.next.pop(0)
|
||||
self.current.coord = CURRENT_COORD
|
||||
self.current.coord = self.CURRENT_COORD
|
||||
self.ghost = self.current.ghost()
|
||||
self.move_ghost()
|
||||
self.new_next()
|
||||
self.next[-1].coord = NEXT_COORDS[-1]
|
||||
for tetromino, coord in zip (self.next, NEXT_COORDS):
|
||||
self.next.append(self.new_tetromino())
|
||||
self.next[-1].coord = self.NEXT_COORDS[-1]
|
||||
for tetromino, coord in zip(self.next, self.NEXT_COORDS):
|
||||
tetromino.coord = coord
|
||||
|
||||
if not self.can_move(
|
||||
self.current.coord,
|
||||
(mino.coord for mino in self.current)
|
||||
):
|
||||
if not self.can_move(self.current.coord, (mino.coord for mino in self.current)):
|
||||
self.game_over()
|
||||
|
||||
def move_left(self):
|
||||
@ -130,10 +145,7 @@ class TetrisLogic():
|
||||
self.ghost.coord = self.current.coord
|
||||
for ghost_mino, current_mino in zip(self.ghost, self.current):
|
||||
ghost_mino.coord = current_mino.coord
|
||||
while self.can_move(
|
||||
self.ghost.coord + Movement.DOWN,
|
||||
(mino.coord for mino in self.ghost)
|
||||
):
|
||||
while self.can_move(self.ghost.coord + Movement.DOWN, (mino.coord for mino in self.ghost)):
|
||||
self.ghost.coord += Movement.DOWN
|
||||
|
||||
def soft_drop(self):
|
||||
@ -152,10 +164,7 @@ class TetrisLogic():
|
||||
|
||||
def move(self, movement, prelock=True):
|
||||
potential_coord = self.current.coord + movement
|
||||
if self.can_move(
|
||||
potential_coord,
|
||||
(mino.coord for mino in self.current)
|
||||
):
|
||||
if self.can_move(potential_coord, (mino.coord for mino in self.current)):
|
||||
if self.current.prelocked:
|
||||
self.restart(self.lock, self.lock_delay)
|
||||
self.current.coord = potential_coord
|
||||
@ -164,23 +173,14 @@ class TetrisLogic():
|
||||
self.move_ghost()
|
||||
return True
|
||||
else:
|
||||
if (
|
||||
prelock and not self.current.prelocked
|
||||
and movement == Movement.DOWN
|
||||
):
|
||||
if prelock and not self.current.prelocked and movement == Movement.DOWN:
|
||||
self.current.prelocked = True
|
||||
self.start(self.lock, self.lock_delay)
|
||||
return False
|
||||
|
||||
def rotate(self, rotation):
|
||||
rotated_coords = tuple(
|
||||
Coord(rotation*mino.coord.y, -rotation*mino.coord.x)
|
||||
for mino in self.current
|
||||
)
|
||||
for rotation_point, liberty_degree in enumerate(
|
||||
self.current.SRS[rotation][self.current.orientation],
|
||||
start = 1
|
||||
):
|
||||
rotated_coords = tuple(Coord(rotation * mino.coord.y, -rotation * mino.coord.x) for mino in self.current)
|
||||
for rotation_point, liberty_degree in enumerate(self.current.SRS[rotation][self.current.orientation], start=1):
|
||||
potential_coord = self.current.coord + liberty_degree
|
||||
if self.can_move(potential_coord, rotated_coords):
|
||||
if self.current.prelocked:
|
||||
@ -188,9 +188,7 @@ class TetrisLogic():
|
||||
self.current.coord = potential_coord
|
||||
for mino, coord in zip(self.current, rotated_coords):
|
||||
mino.coord = coord
|
||||
self.current.orientation = (
|
||||
(self.current.orientation + rotation) % 4
|
||||
)
|
||||
self.current.orientation = (self.current.orientation + rotation) % 4
|
||||
self.current.last_rotation_point = rotation_point
|
||||
self.move_ghost()
|
||||
return True
|
||||
@ -202,41 +200,33 @@ class TetrisLogic():
|
||||
{LINES_CLEAR_NAME: "SINGLE", T_Spin.NONE: 1, T_Spin.MINI: 2, T_Spin.T_SPIN: 8},
|
||||
{LINES_CLEAR_NAME: "DOUBLE", T_Spin.NONE: 3, T_Spin.T_SPIN: 12},
|
||||
{LINES_CLEAR_NAME: "TRIPLE", T_Spin.NONE: 5, T_Spin.T_SPIN: 16},
|
||||
{LINES_CLEAR_NAME: "TETRIS", T_Spin.NONE: 8}
|
||||
{LINES_CLEAR_NAME: "TETRIS", T_Spin.NONE: 8},
|
||||
)
|
||||
|
||||
def lock(self):
|
||||
# Piece unlocked
|
||||
if self.move(Movement.DOWN):
|
||||
return
|
||||
|
||||
# Start lock
|
||||
self.current.prelocked = False
|
||||
self.stop(self.lock)
|
||||
if self.pressed_actions:
|
||||
self.auto_repeat = False
|
||||
self.restart(self.repeat_action, AUTOREPEAT_DELAY)
|
||||
|
||||
# Piece unlocked
|
||||
if self.can_move(self.current.coord + Movement.DOWN, (mino.coord for mino in self.current)):
|
||||
return
|
||||
|
||||
# Game over
|
||||
if all(
|
||||
(mino.coord + self.current.coord).y >= NB_LINES
|
||||
for mino in self.current
|
||||
):
|
||||
if all((mino.coord + self.current.coord).y >= self.NB_LINES for mino in self.current):
|
||||
self.game_over()
|
||||
return
|
||||
|
||||
if self.pressed_actions:
|
||||
self.auto_repeat = False
|
||||
self.restart(self.repeat_action, self.AUTOREPEAT_DELAY)
|
||||
|
||||
# T-Spin
|
||||
if (
|
||||
self.current.__class__ == Tetromino.T
|
||||
and self.current.last_rotation_point is not None
|
||||
):
|
||||
if type(self.current) == T and self.current.last_rotation_point is not None:
|
||||
a = self.is_t_slot(0)
|
||||
b = self.is_t_slot(1)
|
||||
c = self.is_t_slot(3)
|
||||
d = self.is_t_slot(2)
|
||||
if self.current.last_rotation_point == 5 or (
|
||||
a and b and (c or d)
|
||||
):
|
||||
if self.current.last_rotation_point == 5 or (a and b and (c or d)):
|
||||
t_spin = T_Spin.T_SPIN
|
||||
elif c and d and (a or b):
|
||||
t_spin = T_Spin.MINI
|
||||
@ -247,8 +237,8 @@ class TetrisLogic():
|
||||
|
||||
for mino in self.current:
|
||||
coord = mino.coord + self.current.coord
|
||||
del(mino.coord)
|
||||
if coord.y <= NB_LINES+3:
|
||||
del mino.coord
|
||||
if coord.y <= self.NB_LINES + 3:
|
||||
self.matrix[coord.y][coord.x] = mino
|
||||
|
||||
# Clear complete lines
|
||||
@ -294,22 +284,12 @@ class TetrisLogic():
|
||||
self.new_current()
|
||||
|
||||
def can_move(self, potential_coord, minoes_coords):
|
||||
return all(
|
||||
self.matrix.cell_is_free(potential_coord+mino_coord)
|
||||
for mino_coord in minoes_coords
|
||||
)
|
||||
return all(self.matrix.cell_is_free(potential_coord + mino_coord) for mino_coord in minoes_coords)
|
||||
|
||||
T_SLOT_COORDS = (
|
||||
Coord(-1, 1),
|
||||
Coord( 1, 1),
|
||||
Coord(-1, 1),
|
||||
Coord(-1, -1)
|
||||
)
|
||||
T_SLOT_COORDS = (Coord(-1, 1), Coord(1, 1), Coord(-1, 1), Coord(-1, -1))
|
||||
|
||||
def is_t_slot(self, n):
|
||||
t_slot_coord = self.current.coord + self.T_SLOT_COORDS[
|
||||
(self.current.orientation + n) % 4
|
||||
]
|
||||
t_slot_coord = self.current.coord + self.T_SLOT_COORDS[(self.current.orientation + n) % 4]
|
||||
return not self.matrix.cell_is_free(t_slot_coord)
|
||||
|
||||
def swap(self):
|
||||
@ -318,15 +298,15 @@ class TetrisLogic():
|
||||
self.current.prelocked = False
|
||||
self.stop(self.lock)
|
||||
self.current, self.held = self.held, self.current
|
||||
if self.held.__class__ == Tetromino.I:
|
||||
self.held.coord = HELD_I_COORD
|
||||
if type(self.held) == I:
|
||||
self.held.coord = self.HELD_COORD + Movement.LEFT
|
||||
else:
|
||||
self.held.coord = HELD_COORD
|
||||
self.held.coord = self.HELD_COORD
|
||||
for mino, coord in zip(self.held, self.held.MINOES_COORDS):
|
||||
mino.coord = coord
|
||||
|
||||
if self.current:
|
||||
self.current.coord = CURRENT_COORD
|
||||
self.current.coord = self.CURRENT_COORD
|
||||
self.ghost = self.current.ghost()
|
||||
self.move_ghost()
|
||||
else:
|
||||
@ -364,14 +344,14 @@ class TetrisLogic():
|
||||
if action in self.autorepeatable_actions:
|
||||
self.auto_repeat = False
|
||||
self.pressed_actions.append(action)
|
||||
self.restart(self.repeat_action, AUTOREPEAT_DELAY)
|
||||
self.restart(self.repeat_action, self.AUTOREPEAT_DELAY)
|
||||
|
||||
def repeat_action(self):
|
||||
if self.pressed_actions:
|
||||
self.pressed_actions[-1]()
|
||||
if not self.auto_repeat:
|
||||
self.auto_repeat = True
|
||||
self.restart(self.repeat_action, AUTOREPEAT_PERIOD)
|
||||
self.restart(self.repeat_action, self.AUTOREPEAT_PERIOD)
|
||||
else:
|
||||
self.auto_repeat = False
|
||||
self.stop(self.repeat_action)
|
||||
@ -387,19 +367,21 @@ class TetrisLogic():
|
||||
print(text)
|
||||
raise Warning("TetrisLogic.show_text not implemented.")
|
||||
|
||||
def load_high_score(self):
|
||||
self.high_score = 0
|
||||
def load_high_score(self, crypted_high_score=None):
|
||||
if crypted_high_score:
|
||||
crypted_high_score = int(pickle.loads(crypted_high_score))
|
||||
self.high_score = crypted_high_score ^ CRYPT_KEY
|
||||
else:
|
||||
raise Warning(
|
||||
"""TetrisLogic.load_high_score not implemented.
|
||||
High score is set to 0"""
|
||||
)
|
||||
self.high_score = 0
|
||||
|
||||
def save_high_score(self):
|
||||
print("High score: {:n}".format(self.high_score))
|
||||
raise Warning(
|
||||
"""TetrisLogic.save_high_score not implemented.
|
||||
High score is not saved"""
|
||||
)
|
||||
crypted_high_score = self.high_score ^ CRYPT_KEY
|
||||
crypted_high_score = pickle.dumps(crypted_high_score)
|
||||
return crypted_high_score
|
||||
|
||||
def start(task, period):
|
||||
raise Warning("TetrisLogic.start is not implemented.")
|
||||
@ -410,4 +392,3 @@ High score is not saved"""
|
||||
def restart(self, task, period):
|
||||
self.stop(task)
|
||||
self.start(task, period)
|
||||
|
||||
|
@ -1,29 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import random
|
||||
from .utils import Coord, Rotation, Color
|
||||
|
||||
from .utils import Coord, Rotation
|
||||
|
||||
class Mino:
|
||||
|
||||
def __init__(self, color, coord):
|
||||
self.color = color
|
||||
self.coord = coord
|
||||
|
||||
|
||||
class Tetromino:
|
||||
|
||||
random_bag = []
|
||||
|
||||
|
||||
class MetaTetromino(type):
|
||||
|
||||
def __init__(cls, name, bases, dico):
|
||||
super().__init__(name, bases, dico)
|
||||
cls.classes.append(cls)
|
||||
def __init__(cls, name, bases, dct):
|
||||
super().__init__(name, bases, dct)
|
||||
Tetromino.shapes.append(cls)
|
||||
|
||||
|
||||
class AbstractTetromino(list):
|
||||
class Tetromino(list):
|
||||
|
||||
shapes = []
|
||||
# Super rotation system
|
||||
SRS = {
|
||||
Rotation.CLOCKWISE: (
|
||||
@ -39,35 +32,32 @@ class Tetromino:
|
||||
(Coord(0, 0), Coord(-1, 0), Coord(-1, -1), Coord(0, 2), Coord(-1, 2)),
|
||||
),
|
||||
}
|
||||
classes = []
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
Mino(self.MINOES_COLOR, coord)
|
||||
for coord in self.MINOES_COORDS
|
||||
)
|
||||
super().__init__(Mino(self.MINOES_COLOR, coord) for coord in self.MINOES_COORDS)
|
||||
self.orientation = 0
|
||||
self.last_rotation_point = None
|
||||
self.hold_enabled = True
|
||||
self.prelocked = False
|
||||
|
||||
def ghost(self):
|
||||
return self.__class__()
|
||||
return type(self)()
|
||||
|
||||
class O(AbstractTetromino, metaclass=MetaTetromino):
|
||||
|
||||
class O(Tetromino, metaclass=MetaTetromino):
|
||||
|
||||
SRS = {
|
||||
Rotation.CLOCKWISE: (tuple(), tuple(), tuple(), tuple()),
|
||||
Rotation.COUNTER: (tuple(), tuple(), tuple(), tuple()),
|
||||
}
|
||||
MINOES_COORDS = (Coord(0, 0), Coord(1, 0), Coord(0, 1), Coord(1, 1))
|
||||
MINOES_COLOR = "yellow"
|
||||
MINOES_COLOR = Color.YELLOW
|
||||
|
||||
def rotate(self, direction):
|
||||
return False
|
||||
|
||||
|
||||
class I(AbstractTetromino, metaclass=MetaTetromino):
|
||||
class I(Tetromino, metaclass=MetaTetromino):
|
||||
|
||||
SRS = {
|
||||
Rotation.CLOCKWISE: (
|
||||
@ -84,41 +74,34 @@ class Tetromino:
|
||||
),
|
||||
}
|
||||
MINOES_COORDS = (Coord(-1, 0), Coord(0, 0), Coord(1, 0), Coord(2, 0))
|
||||
MINOES_COLOR = "cyan"
|
||||
MINOES_COLOR = Color.CYAN
|
||||
|
||||
|
||||
class T(AbstractTetromino, metaclass=MetaTetromino):
|
||||
class T(Tetromino, metaclass=MetaTetromino):
|
||||
|
||||
MINOES_COORDS = (Coord(-1, 0), Coord(0, 0), Coord(0, 1), Coord(1, 0))
|
||||
MINOES_COLOR = "magenta"
|
||||
MINOES_COLOR = Color.MAGENTA
|
||||
|
||||
|
||||
class L(AbstractTetromino, metaclass=MetaTetromino):
|
||||
class L(Tetromino, metaclass=MetaTetromino):
|
||||
|
||||
MINOES_COORDS = (Coord(-1, 0), Coord(0, 0), Coord(1, 0), Coord(1, 1))
|
||||
MINOES_COLOR = "orange"
|
||||
MINOES_COLOR = Color.ORANGE
|
||||
|
||||
|
||||
class J(AbstractTetromino, metaclass=MetaTetromino):
|
||||
class J(Tetromino, metaclass=MetaTetromino):
|
||||
|
||||
MINOES_COORDS = (Coord(-1, 1), Coord(-1, 0), Coord(0, 0), Coord(1, 0))
|
||||
MINOES_COLOR = "blue"
|
||||
MINOES_COLOR = Color.BLUE
|
||||
|
||||
|
||||
class S(AbstractTetromino, metaclass=MetaTetromino):
|
||||
class S(Tetromino, metaclass=MetaTetromino):
|
||||
|
||||
MINOES_COORDS = (Coord(-1, 0), Coord(0, 0), Coord(0, 1), Coord(1, 1))
|
||||
MINOES_COLOR = "green"
|
||||
MINOES_COLOR = Color.GREEN
|
||||
|
||||
|
||||
class Z(AbstractTetromino, metaclass=MetaTetromino):
|
||||
class Z(Tetromino, metaclass=MetaTetromino):
|
||||
|
||||
MINOES_COORDS = (Coord(-1, 1), Coord(0, 1), Coord(0, 0), Coord(1, 0))
|
||||
MINOES_COLOR = "red"
|
||||
|
||||
|
||||
def __new__(cls):
|
||||
if not cls.random_bag:
|
||||
cls.random_bag = list(Tetromino.AbstractTetromino.classes)
|
||||
random.shuffle(cls.random_bag)
|
||||
return cls.random_bag.pop()()
|
||||
MINOES_COLOR = Color.RED
|
||||
|
@ -1,6 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
class Coord:
|
||||
|
||||
def __init__(self, x, y):
|
||||
self.x = x
|
||||
self.y = y
|
||||
@ -29,6 +28,12 @@ class T_Spin:
|
||||
T_SPIN = "T-SPIN"
|
||||
|
||||
|
||||
class Line(list):
|
||||
pass
|
||||
class Color:
|
||||
|
||||
BLUE = 0
|
||||
CYAN = 1
|
||||
GREEN = 2
|
||||
MAGENTA = 3
|
||||
ORANGE = 4
|
||||
RED = 5
|
||||
YELLOW = 6
|
||||
|