42 Commits

Author SHA1 Message Date
363a89a590 V0.4 Exploding lines 2019-10-06 23:11:51 +02:00
f9c1fe4688 remove no longer necessary const 2019-10-06 18:19:14 +02:00
a0a414db14 particules! 2019-10-06 17:59:27 +02:00
4522ac1d4b rename refresh update 2019-10-06 13:42:37 +02:00
e3e05e87d7 replace mp3 by ogg 2019-10-06 12:57:01 +02:00
82f2b74e68 fix build-requirements.txt 2019-10-06 12:02:59 +02:00
504ebf8e51 reset held piece's minoes coord 2019-10-06 11:16:08 +02:00
4452eb821c refresh on update 2019-10-06 11:12:51 +02:00
e041a8118a refresh ghost on hold 2019-10-06 10:59:31 +02:00
0db5dd4d0d move up held in next pieces 2019-10-06 10:57:45 +02:00
fe69557bc6 improve tetrislogic API 2019-10-06 02:43:38 +02:00
32bf60313c black 2019-10-06 02:43:19 +02:00
f013a061b2 fix line remove 2019-10-04 18:03:35 +02:00
f025ad5fd8 change tetrislogic api 2019-10-04 17:48:47 +02:00
9a7aead918 fix (at last?) music codec warning 2019-10-04 16:15:54 +02:00
b173b6ff73 Warn on music codec not found 2019-10-04 16:07:40 +02:00
ddf7ea0f4e Warn on music codec not found 2019-10-04 15:54:06 +02:00
d308618556 music warning 2019-10-04 12:51:11 +02:00
9c77096bfb Don't play music if codec not found 2019-10-04 12:24:49 +02:00
093264c351 enable level choice 2019-10-04 01:23:47 +02:00
5b3e6ec931 fix setup.py 2019-10-03 21:34:55 +02:00
0970e1f6df V0.3 Release
New musics
Piece lock optimize
2019-10-03 21:33:39 +02:00
f48f1fc000 redefine consts in TetrArcade.py 2019-10-03 18:14:07 +02:00
5f137a62ec V0.2 Release
Music
Soft drop autorepeat delay set to fall delay / 20
2019-10-03 01:41:21 +02:00
ec42f17ca7 soft drop autorepeat delay set to fall delay / 20 2019-10-03 01:32:52 +02:00
0d6386d22b music!
change API (pieces are attributes of TetrominoContainers)
2019-10-03 01:26:31 +02:00
abaeb3be9a v0.1 release 2019-10-02 23:14:41 +02:00
dff4ae487a setup.py 2019-10-02 17:19:11 +02:00
5c830fd828 update setup.py info 2019-10-02 16:44:25 +02:00
a46c07af8b add start menu shortcut for windows installer 2019-10-02 16:39:37 +02:00
338371f443 fix resize error since texture use 2019-10-02 16:37:39 +02:00
a95463438e Add screenshot 2019-10-02 16:22:16 +02:00
06fe72d8db Merge branch 'master' of https://git.malingrey.fr/adrien/TetrArcade 2019-10-02 15:44:02 +02:00
4a69c12349 no python2 2019-10-02 14:51:56 +02:00
2bd75be892 Arcade require Python 3.6+ 2019-10-02 13:07:30 +02:00
3015a36984 case insensitive keyboard conf 2019-10-02 12:36:03 +02:00
7fc342e061 V0.2-dev 2019-10-02 12:35:35 +02:00
0e68ea4e51 build-requirements.txt 2019-10-02 12:16:41 +02:00
b95478ea8d use texture, import from, black 2019-10-02 11:54:50 +02:00
df8257c4da held mino sprite 2019-10-02 09:00:35 +02:00
0b3dd847d3 exclude Qt from build 2019-10-02 02:29:00 +02:00
2a7900586c Autorepeat in conf 2019-10-02 02:28:49 +02:00
27 changed files with 755 additions and 473 deletions

View File

@ -2,9 +2,11 @@
Tetris clone made with Python and Arcade graphic library
![Screenshot](https://malingrey.fr/images/fMd4EseZ/VtwJIMyQ.png)
## Requirements
* [Python](https://www.python.org/)
* [Python](https://www.python.org/) 3.6 or upper
## Install
@ -30,6 +32,6 @@ Use key name from [arcade.key package](http://arcade.academy/arcade.key.html).
## Build
```shell
python -m pip install cx-freeze
python setup.py build
```
python -m pip install -r build-requirements.txt
python setup.py bdist
```

View File

@ -1,60 +1,112 @@
# -*- coding: utf-8 -*-
import sys
import locale
import time
import os
try:
import configparser
except ImportError:
import ConfigParser as configparser
import random
try:
import arcade
except ImportError as e:
sys.exit(str(e) + """
sys.exit(
str(e)
+ """
This game require arcade library.
You can install it with:
python -m pip install --user arcade"""
)
import pyglet
import tetrislogic
import locale
import time
import os
import itertools
import configparser
from tetrislogic import TetrisLogic, Color, Phase, Coord, I_Tetrimino, Movement
# Constants
# Matrix
LINES = 20
COLLUMNS = 10
NEXT_PIECES = 6
# Delays (seconds)
LOCK_DELAY = 0.5
FALL_DELAY = 1
AUTOREPEAT_DELAY = 0.300
AUTOREPEAT_PERIOD = 0.010
PARTICULE_ACCELERATION = 1.1
# Piece init coord
MATRIX_PIECE_COORD = Coord(4, LINES)
NEXT_PIECES_COORDS = [Coord(COLLUMNS + 4, LINES - 4 * n) for n in range(NEXT_PIECES)]
HELD_PIECE_COORD = Coord(-5, LINES)
# Window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
WINDOW_MIN_WIDTH = 517
WINDOW_MIN_HEIGHT = 388
WINDOW_TITLE = "TETRARCADE"
MINO_SIZE = 20
BG_COLOR = (7, 11, 21)
# Delays (seconds)
HIGHLIGHT_TEXT_DISPLAY_DELAY = 0.7
# Transparency (0=invisible, 255=opaque)
NORMAL_ALPHA = 200
NORMAL_ALPHA = 255
PRELOCKED_ALPHA = 100
GHOST_ALPHA = 30
MATRIX_BG_ALPHA = 100
BAR_ALPHA = 75
# Mino size
MINO_SIZE = 20
MINO_SPRITE_SIZE = 21
if getattr(sys, "frozen", False):
# The application is frozen
PROGRAM_DIR = os.path.dirname(sys.executable)
else:
# The application is not frozen
PROGRAM_DIR = os.path.dirname(__file__)
RESOURCES_DIR = os.path.join(PROGRAM_DIR, "resources")
# 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_PATHS = {
"orange": "res/orange_mino.png",
"blue": "res/blue_mino.png",
"yellow": "res/yellow_mino.png",
"cyan": "res/cyan_mino.png",
"green": "res/green_mino.png",
"red": "res/red_mino.png",
"magenta": "res/magenta_mino.png",
IMAGES_DIR = os.path.join(RESOURCES_DIR, "images")
WINDOW_BG_PATH = os.path.join(IMAGES_DIR, "bg.jpg")
MATRIX_BG_PATH = os.path.join(IMAGES_DIR, "matrix.png")
MINOES_SPRITES_PATH = os.path.join(IMAGES_DIR, "minoes.png")
Color.LOCKED = 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.LOCKED: 7,
}
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()}
NORMAL_TEXTURE = 0
LOCKED_TEXTURE = 1
# Music
MUSIC_DIR = os.path.join(RESOURCES_DIR, "musics")
MUSICS_PATHS = (entry.path for entry in os.scandir(MUSIC_DIR))
# Text
TEXT_COLOR = arcade.color.BUBBLES
FONT_NAME = os.path.join(RESOURCES_DIR, "fonts/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
# User profile path
if sys.platform == "win32":
@ -69,33 +121,29 @@ 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__(MINOES_SPRITES_PATHS[mino.color], window.scale)
super().__init__()
self.alpha = alpha
self.window = window
self.append_texture(TEXTURES[mino.color])
self.append_texture(TEXTURES[Color.LOCKED])
self.set_texture(0)
def set_position(self, x, y):
def update(self, x, y, texture=0):
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.left = self.window.matrix.bg.left + x * size
self.bottom = self.window.matrix.bg.bottom + y * size
self.set_texture(texture)
class MinoesSprites(arcade.SpriteList):
def resize(self, scale):
for sprite in self:
sprite.scale = scale
self.refresh()
self.update()
class TetrominoSprites(MinoesSprites):
@ -107,32 +155,31 @@ class TetrominoSprites(MinoesSprites):
mino.sprite = MinoSprite(mino, window, alpha)
self.append(mino.sprite)
def refresh(self):
if self.tetromino.prelocked:
alpha = PRELOCKED_ALPHA
else:
alpha = self.alpha
def update(self, texture=NORMAL_TEXTURE):
for mino in self.tetromino:
coord = mino.coord + self.tetromino.coord
mino.sprite.set_position(coord.x, coord.y)
mino.sprite.alpha = alpha
mino.sprite.update(coord.x, coord.y, texture)
class MatrixSprites(MinoesSprites):
def __init__(self, matrix):
super().__init__()
self.matrix = matrix
self.refresh()
self.update()
def refresh(self):
def update(self):
for y, line in enumerate(self.matrix):
for x, mino in enumerate(line):
if mino:
mino.sprite.set_position(x, y)
self.append(mino.sprite)
mino.sprite.update(x, y)
def remove_line(self, y):
for mino in self.matrix[y]:
if mino:
self.remove(mino.sprite)
class TetrArcade(tetrislogic.TetrisLogic, arcade.Window):
class TetrArcade(TetrisLogic, arcade.Window):
def __init__(self):
locale.setlocale(locale.LC_ALL, "")
self.highlight_texts = []
@ -149,7 +196,7 @@ class TetrArcade(tetrislogic.TetrisLogic, arcade.Window):
self.new_conf()
self.load_conf()
super().__init__()
super().__init__(LINES, COLLUMNS, NEXT_PIECES)
arcade.Window.__init__(
self,
width=self.init_width,
@ -163,14 +210,24 @@ class TetrArcade(tetrislogic.TetrisLogic, arcade.Window):
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.bg = arcade.Sprite(MATRIX_BG_PATH)
self.matrix.bg.alpha = MATRIX_BG_ALPHA
self.matrix.sprites = MatrixSprites(self.matrix)
self.on_resize(self.init_width, self.init_height)
self.exploding_minoes = [None for y in range(LINES)]
if self.play_music:
try:
self.music = pyglet.media.Player()
playlist = itertools.cycle(
pyglet.media.load(path) for path in MUSICS_PATHS
)
self.music.queue(playlist)
except:
Warning("Can't play music.")
self.music = None
else:
self.music = None
def new_conf(self):
self.conf["WINDOW"] = {
@ -190,6 +247,8 @@ class TetrArcade(tetrislogic.TetrisLogic, arcade.Window):
"pause": "ESCAPE",
"fullscreen": "F11",
}
self.conf["MUSIC"] = {"play": True}
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)
@ -201,14 +260,16 @@ class TetrArcade(tetrislogic.TetrisLogic, arcade.Window):
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 = {
tetrislogic.State.STARTING: {
Phase.STARTING: {
getattr(arcade.key, self.conf["KEYBOARD"]["start"]): self.new_game,
getattr(
arcade.key, self.conf["KEYBOARD"]["fullscreen"]
): self.toggle_fullscreen,
},
tetrislogic.State.PLAYING: {
Phase.FALLING: {
getattr(arcade.key, self.conf["KEYBOARD"]["move left"]): self.move_left,
getattr(
arcade.key, self.conf["KEYBOARD"]["move right"]
@ -221,19 +282,38 @@ class TetrArcade(tetrislogic.TetrisLogic, arcade.Window):
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"]["hold"]): self.hold,
getattr(arcade.key, self.conf["KEYBOARD"]["pause"]): self.pause,
getattr(
arcade.key, self.conf["KEYBOARD"]["fullscreen"]
): self.toggle_fullscreen,
},
tetrislogic.State.PAUSED: {
Phase.LOCK: {
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.hold,
getattr(arcade.key, self.conf["KEYBOARD"]["pause"]): self.pause,
getattr(
arcade.key, self.conf["KEYBOARD"]["fullscreen"]
): self.toggle_fullscreen,
},
Phase.PAUSED: {
getattr(arcade.key, self.conf["KEYBOARD"]["pause"]): self.resume,
getattr(
arcade.key, self.conf["KEYBOARD"]["fullscreen"]
): self.toggle_fullscreen,
},
tetrislogic.State.OVER: {
Phase.OVER: {
getattr(arcade.key, self.conf["KEYBOARD"]["start"]): self.new_game,
getattr(
arcade.key, self.conf["KEYBOARD"]["fullscreen"]
@ -241,6 +321,9 @@ class TetrArcade(tetrislogic.TetrisLogic, arcade.Window):
},
}
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(
@ -270,52 +353,91 @@ AGAIN""".format(
self.conf["KEYBOARD"]["start"]
)
def new_game(self):
self.play_music = self.conf["MUSIC"].getboolean("play")
def on_new_game(self, next_pieces):
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()
for piece in next_pieces:
piece.sprites = TetrominoSprites(piece, self)
def move(self, movement, prelock=True):
moved = super().move(movement, prelock)
self.current.sprites.refresh()
if moved:
self.ghost.sprites.refresh()
return moved
if self.music:
self.music.seek(0)
self.music.play()
def rotate(self, rotation):
rotated = super().rotate(rotation)
if rotated:
for tetromino in (self.current, self.ghost):
tetromino.sprites.refresh()
return rotated
def on_new_level(self, level):
self.show_text("LEVEL\n{:n}".format(level))
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 on_generation_phase(self, matrix, falling_piece, ghost_piece, next_pieces):
matrix.sprites.update()
falling_piece.sprites = TetrominoSprites(falling_piece, self)
ghost_piece.sprites = TetrominoSprites(ghost_piece, self, GHOST_ALPHA)
next_pieces[-1].sprites = TetrominoSprites(next_pieces[-1], self)
for piece, coord in zip(next_pieces, NEXT_PIECES_COORDS):
piece.coord = coord
def lock(self):
self.current.prelocked = False
self.current.sprites.refresh()
super().lock()
def on_locked(self, matrix, locked_piece):
for mino in locked_piece:
matrix.sprites.append(mino.sprite)
def on_line_remove(self, matrix, y):
line_textures = tuple(TEXTURES[mino.color] for mino in matrix[y])
self.exploding_minoes[y] = arcade.Emitter(
center_xy=(matrix.bg.left, matrix.bg.bottom + (y + 0.5) * MINO_SIZE),
emit_controller=arcade.EmitBurst(COLLUMNS),
particle_factory=lambda emitter: arcade.LifetimeParticle(
filename_or_texture=random.choice(line_textures),
change_xy=arcade.rand_in_rect(
(-COLLUMNS * MINO_SIZE, -4 * MINO_SIZE),
2 * COLLUMNS * MINO_SIZE,
5 * MINO_SIZE,
),
lifetime=1,
center_xy=arcade.rand_on_line((0, 0), (matrix.bg.width, 0)),
scale=self.scale,
alpha=NORMAL_ALPHA,
change_angle=2,
mutation_callback=self.speed_up_particule,
),
)
matrix.sprites.remove_line(y)
def speed_up_particule(self, particule):
particule.change_x *= PARTICULE_ACCELERATION
particule.change_y *= PARTICULE_ACCELERATION
def on_pattern_phase(self, pattern_name, pattern_score, nb_combo, combo_score):
if pattern_score:
self.show_text("{:s}\n{:n}".format(pattern_name, pattern_score))
if combo_score:
self.show_text("COMBO x{:n}\n{:n}".format(nb_combo, combo_score))
def on_hold(self, held_piece, falling_piece, ghost_piece):
held_piece.coord = HELD_PIECE_COORD
if type(held_piece) == I_Tetrimino:
held_piece.coord += Movement.LEFT
ghost_piece.sprites = TetrominoSprites(ghost_piece, self, GHOST_ALPHA)
def pause(self):
super().pause()
if self.music:
self.music.pause()
def resume(self):
super().resume()
if self.music:
self.music.play()
def on_game_over(self):
if self.music:
self.music.pause()
def on_key_press(self, key, modifiers):
for key_or_modifier in (key, modifiers):
try:
action = self.key_map[self.state][key_or_modifier]
action = self.key_map[self.phase][key_or_modifier]
except KeyError:
pass
else:
@ -324,7 +446,7 @@ AGAIN""".format(
def on_key_release(self, key, modifiers):
for key_or_modifier in (key, modifiers):
try:
action = self.key_map[self.state][key_or_modifier]
action = self.key_map[self.phase][key_or_modifier]
except KeyError:
pass
else:
@ -344,26 +466,28 @@ AGAIN""".format(
arcade.start_render()
self.bg.draw()
if self.state in (tetrislogic.State.PLAYING, tetrislogic.State.OVER):
self.matrix_bg.draw()
self.held_bg.draw()
self.next_bg.draw()
if self.phase not in (Phase.STARTING, Phase.PAUSED):
self.matrix.bg.draw()
self.matrix.sprites.draw()
for tetromino in [self.held, self.current, self.ghost] + self.next:
for tetromino in [
self.held.piece,
self.matrix.piece,
self.matrix.ghost,
] + self.next.pieces:
if tetromino:
tetromino.sprites.draw()
t = time.localtime(self.time)
t = time.localtime(self.stats.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
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,
start_y=self.matrix.bg.bottom + 1.5 * (2 * y + 1) * font_size,
color=TEXT_COLOR,
font_size=font_size,
align="right",
@ -373,17 +497,17 @@ AGAIN""".format(
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),
"{:n}".format(self.stats.lines_cleared),
"{:n}".format(self.stats.goal),
"{:n}".format(self.stats.level),
"{:n}".format(self.stats.high_score),
"{:n}".format(self.stats.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,
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",
@ -391,19 +515,21 @@ AGAIN""".format(
anchor_x="right",
)
for exploding_minoes in self.exploding_minoes:
if exploding_minoes:
exploding_minoes.draw()
highlight_text = {
tetrislogic.State.STARTING: self.start_text,
tetrislogic.State.PLAYING: self.highlight_texts[0]
if self.highlight_texts
else "",
tetrislogic.State.PAUSED: self.pause_text,
tetrislogic.State.OVER: self.game_over_text,
}.get(self.state, "")
Phase.STARTING: self.start_text,
Phase.FALLING: self.highlight_texts[0] if self.highlight_texts else "",
Phase.PAUSED: self.pause_text,
Phase.OVER: self.game_over_text,
}.get(self.phase, "")
if highlight_text:
arcade.draw_text(
text=highlight_text,
start_x=self.matrix_bg.center_x,
start_y=self.matrix_bg.center_y,
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",
@ -428,23 +554,19 @@ AGAIN""".format(
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.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.matrix.sprites.resize(self.scale)
for tetromino in [self.held, self.current, self.ghost] + self.next:
for tetromino in [
self.held.piece,
self.matrix.piece,
self.matrix.ghost,
] + self.next.pieces:
if tetromino:
tetromino.sprites.resize(self.scale)
@ -454,7 +576,7 @@ AGAIN""".format(
crypted_high_score = f.read()
super().load_high_score(crypted_high_score)
except:
self.high_score = 0
self.stats.high_score = 0
def save_high_score(self):
try:
@ -497,14 +619,30 @@ High score could not be saved:
arcade.unschedule(_task)
arcade.schedule(_task, period)
def update(self, delta_time):
for piece in [self.held.piece, self.matrix.ghost] + self.next.pieces:
if piece:
piece.sprites.update()
if self.matrix.piece:
texture = LOCKED_TEXTURE if self.phase == Phase.LOCK else NORMAL_TEXTURE
self.matrix.piece.sprites.update(texture=texture)
for exploding_minoes in self.exploding_minoes:
if exploding_minoes:
exploding_minoes.update()
def on_close(self):
self.save_high_score()
if self.music:
self.music.pause()
super().on_close()
def main():
TetrArcade()
arcade.run()
try:
TetrArcade()
arcade.run()
except Exception as e:
sys.exit(e)
if __name__ == "__main__":

2
build-requirements.txt Normal file
View File

@ -0,0 +1,2 @@
arcade
cx-freeze

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 151 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 499 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 475 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 B

View File

Before

Width:  |  Height:  |  Size: 153 KiB

After

Width:  |  Height:  |  Size: 153 KiB

View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
resources/images/minoes.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 389 B

Binary file not shown.

BIN
resources/musics/2-!!!.ogg Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -9,22 +9,29 @@ 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": "resources",
"silent": True,
}
}
setup(
name="TetrArcade",
version="0.1",
version="0.4",
description="Tetris clone",
author="adrienmalin",
executables=[Executable(
script="TetrArcade.py",
icon=icon,
base=base
)],
options={
"build_exe": {
"packages": ["arcade", "pyglet"],
"excludes": ["tkinter"],
"include_files": "res",
"silent": True
}
},
author="AdrienMalin",
executables=[executable],
options=options,
)

21
test.py
View File

@ -1,15 +1,30 @@
# -*- coding: utf-8 -*-
from TetrArcade import TetrArcade, tetrislogic
from TetrArcade import TetrArcade, Phase, MinoSprite
from tetrislogic import Mino, Color, Coord
game = TetrArcade()
game.new_game()
for x in range(game.matrix.collumns):
mino = Mino(Color.ORANGE, Coord(x, 0))
mino.sprite = MinoSprite(mino, game, 200)
game.matrix[0][x] = mino
game.matrix.sprites.append(mino.sprite)
game.move_left()
game.pause()
game.resume()
game.move_right()
game.hold()
game.rotate_clockwise()
game.hold()
game.rotate_counter()
for i in range(12):
for i in range(22):
game.soft_drop()
game.on_draw()
game.lock_phase()
game.hold()
game.matrix.sprites.update()
game.on_draw()
while game.state != tetrislogic.State.OVER:
while game.phase != Phase.OVER:
game.hard_drop()
game.on_draw()

View File

@ -1,5 +1,15 @@
# -*- coding: utf-8 -*-
from .consts import NB_LINES, NB_COLS, NB_NEXT
from .utils import Movement, Rotation
from .tetromino import Mino, Tetromino
from .tetrislogic import TetrisLogic, State, Matrix
from .consts import LINES, COLLUMNS, NEXT_PIECES
from .utils import Movement, Rotation, Color, Coord, Phase
from .tetromino import (
Mino,
Tetromino,
I_Tetrimino,
J_Tetrimino,
L_Tetrimino,
O_Tetrimino,
S_Tetrimino,
T_Tetrimino,
Z_Tetrimino,
)
from .tetrislogic import TetrisLogic, Matrix

View File

@ -3,18 +3,15 @@ from .utils import Coord
# Matrix
NB_LINES = 20
NB_COLS = 10
NB_NEXT = 5
LINES = 20
COLLUMNS = 10
NEXT_PIECES = 5
# Delays (seconds)
LOCK_DELAY = 0.5
FALL_DELAY = 1
AUTOREPEAT_DELAY = 0.200 # Official : 0.300
AUTOREPEAT_PERIOD = 0.010 # Official : 0.010
AUTOREPEAT_DELAY = 0.300 # Official : 0.300 s
AUTOREPEAT_PERIOD = 0.010 # Official : 0.010 s
# Piece init coord
CURRENT_COORD = Coord(4, NB_LINES)
NEXT_COORDS = [Coord(NB_COLS + 4, NB_LINES - 4 * n - 3) for n in range(NB_NEXT)]
HELD_COORD = Coord(-5, NB_LINES - 3)
MATRIX_PIECE_COORD = Coord(4, LINES)

View File

@ -1,20 +1,17 @@
# -*- coding: utf-8 -*-
import random
import pickle
from .utils import Coord, Movement, Rotation, T_Spin, Line
from .tetromino import Tetromino, T, I
from .utils import Coord, Movement, Rotation, T_Spin, Phase
from .tetromino import Tetromino, T_Tetrimino
from .consts import (
NB_LINES,
NB_COLS,
NB_NEXT,
LINES,
COLLUMNS,
NEXT_PIECES,
LOCK_DELAY,
FALL_DELAY,
AUTOREPEAT_DELAY,
AUTOREPEAT_PERIOD,
CURRENT_COORD,
NEXT_COORDS,
HELD_COORD,
MATRIX_PIECE_COORD,
)
@ -22,87 +19,79 @@ LINES_CLEAR_NAME = "LINES_CLEAR_NAME"
CRYPT_KEY = 987943759387540938469837689379857347598347598379584857934579343
class State:
STARTING = "STARTING"
PLAYING = "PLAYING"
PAUSED = "PAUSED"
OVER = "OVER"
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]
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 = []
class PieceContainer:
def __init__(self):
self.load_high_score()
self.state = State.STARTING
self.matrix = Matrix()
self.next = []
self.current = None
self.ghost = None
self.held = None
self.time = 0
self.autorepeatable_actions = (self.move_left, self.move_right, self.soft_drop)
self.pressed_actions = []
self._score = 0
self.piece = None
def get_score(self):
class HoldQueue(PieceContainer):
pass
class Matrix(list, PieceContainer):
def __init__(self, lines, collumns):
list.__init__(self)
PieceContainer.__init__(self)
self.lines = lines
self.collumns = collumns
self.ghost = None
def reset(self):
self.clear()
for y in range(self.lines + 3):
self.append_new_line()
def append_new_line(self):
self.append([None for x in range(self.collumns)])
def cell_is_free(self, coord):
return (
0 <= coord.x < self.collumns and 0 <= coord.y and not self[coord.y][coord.x]
)
class NextQueue(PieceContainer):
def __init__(self, nb_pieces):
super().__init__()
self.nb_pieces = nb_pieces
self.pieces = []
class Stats:
SCORES = (
{LINES_CLEAR_NAME: "", T_Spin.NONE: 0, T_Spin.MINI: 1, T_Spin.T_SPIN: 4},
{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},
)
def _get_score(self):
return self._score
def set_score(self, new_score):
def _set_score(self, new_score):
self._score = new_score
if self._score > self.high_score:
self.high_score = self._score
score = property(get_score, set_score)
score = property(_get_score, _set_score)
def new_game(self):
self.level = 0
self.score = 0
self.nb_lines_cleared = 0
self.goal = 0
def __init__(self):
self._score = 0
self.high_score = 0
self.time = 0
self.pressed_actions = []
self.auto_repeat = False
def new_game(self, level):
self.level = level - 1
self.score = 0
self.lines_cleared = 0
self.goal = 0
self.time = 0
self.combo = -1
self.lock_delay = self.LOCK_DELAY
self.fall_delay = self.FALL_DELAY
self.matrix.clear()
for y in range(self.NB_LINES + 3):
self.append_new_line_to_matrix()
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_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(self.NB_COLS)))
self.lock_delay = LOCK_DELAY
self.fall_delay = FALL_DELAY
def new_level(self):
self.level += 1
@ -111,23 +100,277 @@ class TetrisLogic:
self.fall_delay = pow(0.8 - ((self.level - 1) * 0.007), self.level - 1)
if self.level > 15:
self.lock_delay = 0.5 * pow(0.9, self.level - 15)
self.show_text("LEVEL\n{:n}".format(self.level))
self.restart(self.fall, self.fall_delay)
self.new_current()
def update_time(self):
self.time += 1
def new_current(self):
self.current = self.next.pop(0)
self.current.coord = self.CURRENT_COORD
self.ghost = self.current.ghost()
self.move_ghost()
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
def pattern_phase(self, t_spin, lines_cleared):
pattern_name = []
pattern_score = 0
combo_score = 0
if not self.can_move(self.current.coord, (mino.coord for mino in self.current)):
if t_spin:
pattern_name.append(t_spin)
if lines_cleared:
pattern_name.append(self.SCORES[lines_cleared][LINES_CLEAR_NAME])
self.combo += 1
else:
self.combo = -1
if lines_cleared or t_spin:
pattern_score = self.SCORES[lines_cleared][t_spin]
self.goal -= pattern_score
pattern_score *= 100 * self.level
pattern_name = "\n".join(pattern_name)
if self.combo >= 1:
combo_score = (20 if lines_cleared == 1 else 50) * self.combo * self.level
self.score += pattern_score + combo_score
return pattern_name, pattern_score, self.combo, combo_score
class TetrisLogic:
LINES = LINES
COLLUMNS = COLLUMNS
NEXT_PIECES = NEXT_PIECES
AUTOREPEAT_DELAY = AUTOREPEAT_DELAY
AUTOREPEAT_PERIOD = AUTOREPEAT_PERIOD
MATRIX_PIECE_COORD = MATRIX_PIECE_COORD
def __init__(self, lines=LINES, collumns=COLLUMNS, next_pieces=NEXT_PIECES):
self.stats = Stats()
self.load_high_score()
self.phase = Phase.STARTING
self.held = HoldQueue()
self.matrix = Matrix(lines, collumns)
self.next = NextQueue(next_pieces)
self.autorepeatable_actions = (self.move_left, self.move_right, self.soft_drop)
self.pressed_actions = []
def new_game(self, level=1):
self.stats.new_game(level)
self.pressed_actions = []
self.auto_repeat = False
self.matrix.reset()
self.next.pieces = [Tetromino() for n in range(self.next.nb_pieces)]
self.held.piece = None
self.start(self.stats.update_time, 1)
self.on_new_game(self.next.pieces)
self.new_level()
def on_new_game(self, next_pieces):
pass
def new_level(self):
self.stats.new_level()
self.on_new_level(self.stats.level)
self.generation_phase()
def on_new_level(self, level):
pass
def generation_phase(self):
self.phase = Phase.GENERATION
self.matrix.piece = self.next.pieces.pop(0)
self.next.pieces.append(Tetromino())
self.matrix.piece.coord = self.MATRIX_PIECE_COORD
self.matrix.ghost = self.matrix.piece.ghost()
self.on_generation_phase(
self.matrix, self.matrix.piece, self.matrix.ghost, self.next.pieces
)
if not self.move(Movement.DOWN):
self.game_over()
else:
self.restart(self.fall, self.stats.fall_delay)
self.falling_phase()
def on_generation_phase(self, matrix, falling_piece, ghost_piece, next_pieces):
pass
def falling_phase(self):
self.phase = Phase.FALLING
self.matrix.ghost.coord = self.matrix.piece.coord
for ghost_mino, current_mino in zip(self.matrix.ghost, self.matrix.piece):
ghost_mino.coord = current_mino.coord
while self.space_to_move(
self.matrix.ghost.coord + Movement.DOWN,
(mino.coord for mino in self.matrix.ghost),
):
self.matrix.ghost.coord += Movement.DOWN
self.on_falling_phase(self.matrix.piece, self.matrix.ghost)
def on_falling_phase(self, falling_piece, ghost_piece):
pass
def fall(self):
self.move(Movement.DOWN)
def move(self, movement, rotated_coords=None, lock=True):
potential_coord = self.matrix.piece.coord + movement
if self.space_to_move(
potential_coord,
rotated_coords or (mino.coord for mino in self.matrix.piece),
):
self.matrix.piece.coord = potential_coord
if rotated_coords:
for mino, coord in zip(self.matrix.piece, rotated_coords):
mino.coord = coord
else:
if movement != Movement.DOWN:
self.matrix.piece.last_rotation_point = None
if self.phase == Phase.LOCK:
self.restart(self.pattern_phase, self.stats.lock_delay)
self.falling_phase()
return True
else:
if lock and self.phase != Phase.LOCK and movement == Movement.DOWN:
self.lock_phase()
return False
def lock_phase(self):
self.phase = Phase.LOCK
self.on_lock_phase(self.matrix.piece)
self.start(self.pattern_phase, self.stats.lock_delay)
def on_lock_phase(self, locked_piece):
pass
def space_to_move(self, potential_coord, minoes_coord):
return all(
self.matrix.cell_is_free(potential_coord + mino_coord)
for mino_coord in minoes_coord
)
def rotate(self, rotation):
rotated_coords = tuple(
Coord(rotation * mino.coord.y, -rotation * mino.coord.x)
for mino in self.matrix.piece
)
for rotation_point, liberty_degree in enumerate(
self.matrix.piece.SRS[rotation][self.matrix.piece.orientation], start=1
):
if self.move(liberty_degree, rotated_coords):
self.matrix.piece.orientation = (
self.matrix.piece.orientation + rotation
) % 4
self.matrix.piece.last_rotation_point = rotation_point
return True
else:
return False
def hold(self):
if not self.matrix.piece.hold_enabled:
return
self.matrix.piece.hold_enabled = False
self.stop(self.pattern_phase)
self.stop(self.fall)
self.matrix.piece, self.held.piece = self.held.piece, self.matrix.piece
for mino, coord in zip(self.held.piece, self.held.piece.MINOES_COORDS):
mino.coord = coord
if self.matrix.piece:
self.matrix.piece.coord = self.MATRIX_PIECE_COORD
self.matrix.ghost = self.matrix.piece.ghost()
self.on_hold(self.held.piece, self.matrix.piece, self.matrix.ghost)
self.falling_phase()
else:
self.generation_phase()
self.on_hold(self.held.piece, self.matrix.piece, self.matrix.ghost)
def on_hold(self, held_piece, falling_piece, ghost_piece):
pass
def pattern_phase(self):
self.phase = Phase.PATTERN
self.matrix.piece.prelocked = False
self.stop(self.pattern_phase)
self.stop(self.fall)
# Piece unlocked
if self.space_to_move(
self.matrix.piece.coord + Movement.DOWN,
(mino.coord for mino in self.matrix.piece),
):
return
# Game over
if all(
(mino.coord + self.matrix.piece.coord).y >= self.matrix.lines
for mino in self.matrix.piece
):
self.game_over()
return
if self.pressed_actions:
self.auto_repeat = False
self.stop(self.repeat_action)
for mino in self.matrix.piece:
coord = mino.coord + self.matrix.piece.coord
if coord.y <= self.matrix.lines + 3:
self.matrix[coord.y][coord.x] = mino
self.on_locked(self.matrix, self.matrix.piece)
# T-Spin
if (
type(self.matrix.piece) == T_Tetrimino
and self.matrix.piece.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.matrix.piece.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
else:
t_spin = T_Spin.NONE
else:
t_spin = T_Spin.NONE
# Clear complete lines
lines_cleared = 0
for y, line in reversed(list(enumerate(self.matrix))):
if all(mino for mino in line):
lines_cleared += 1
self.on_line_remove(self.matrix, y)
self.matrix.pop(y)
self.matrix.append_new_line()
if lines_cleared:
self.stats.lines_cleared += lines_cleared
pattern_name, pattern_score, nb_combo, combo_score = self.stats.pattern_phase(
t_spin, lines_cleared
)
self.on_pattern_phase(pattern_name, pattern_score, nb_combo, combo_score)
if self.stats.goal <= 0:
self.new_level()
else:
self.generation_phase()
if self.pressed_actions:
self.start(self.repeat_action, self.AUTOREPEAT_DELAY)
def on_locked(self, matrix, locked_piece):
pass
def on_line_remove(self, matrix, y):
pass
def on_pattern_phase(self, pattern_name, pattern_score, nb_combo, combo_score):
pass
def move_left(self):
self.move(Movement.LEFT)
@ -141,227 +384,64 @@ class TetrisLogic:
def rotate_counter(self):
self.rotate(Rotation.COUNTER)
def move_ghost(self):
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)
):
self.ghost.coord += Movement.DOWN
def soft_drop(self):
moved = self.move(Movement.DOWN)
if moved:
self.score += 1
self.stats.score += 1
return moved
def hard_drop(self):
while self.move(Movement.DOWN, prelock=False):
self.score += 2
self.lock()
def fall(self):
self.move(Movement.DOWN)
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.current.prelocked:
self.restart(self.lock, self.lock_delay)
self.current.coord = potential_coord
if not movement == Movement.DOWN:
self.current.last_rotation_point = None
self.move_ghost()
return True
else:
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
):
potential_coord = self.current.coord + liberty_degree
if self.can_move(potential_coord, rotated_coords):
if self.current.prelocked:
self.restart(self.lock, self.lock_delay)
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.last_rotation_point = rotation_point
self.move_ghost()
return True
else:
return False
SCORES = (
{LINES_CLEAR_NAME: "", T_Spin.NONE: 0, T_Spin.MINI: 1, T_Spin.T_SPIN: 4},
{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},
)
def lock(self):
self.current.prelocked = False
self.stop(self.lock)
# 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 >= 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 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)):
t_spin = T_Spin.T_SPIN
elif c and d and (a or b):
t_spin = T_Spin.MINI
else:
t_spin = T_Spin.NONE
else:
t_spin = T_Spin.NONE
for mino in self.current:
coord = mino.coord + self.current.coord
del mino.coord
if coord.y <= self.NB_LINES + 3:
self.matrix[coord.y][coord.x] = mino
# Clear complete lines
nb_lines_cleared = 0
for y, line in reversed(list(enumerate(self.matrix))):
if all(mino for mino in line):
nb_lines_cleared += 1
self.matrix.pop(y)
self.append_new_line_to_matrix()
if nb_lines_cleared:
self.nb_lines_cleared += nb_lines_cleared
# Scoring
lock_strings = []
lock_score = 0
if t_spin:
lock_strings.append(t_spin)
if nb_lines_cleared:
lock_strings.append(self.SCORES[nb_lines_cleared][LINES_CLEAR_NAME])
self.combo += 1
else:
self.combo = -1
if nb_lines_cleared or t_spin:
ds = self.SCORES[nb_lines_cleared][t_spin]
self.goal -= ds
ds *= 100 * self.level
lock_score += ds
lock_strings.append(str(ds))
self.show_text("\n".join(lock_strings))
if self.combo >= 1:
ds = (20 if nb_lines_cleared == 1 else 50) * self.combo * self.level
lock_score += ds
self.show_text("COMBO x{:n}\n{:n}".format(self.combo, ds))
self.score += lock_score
if self.goal <= 0:
self.new_level()
else:
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
)
while self.move(Movement.DOWN, lock=False):
self.stats.score += 2
self.pattern_phase()
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]
self.matrix.piece.coord
+ self.T_SLOT_COORDS[(self.matrix.piece.orientation + n) % 4]
)
return not self.matrix.cell_is_free(t_slot_coord)
def swap(self):
if self.current.hold_enabled:
self.current.hold_enabled = False
self.current.prelocked = False
self.stop(self.lock)
self.current, self.held = self.held, self.current
if type(self.held) == I:
self.held.coord = self.HELD_COORD + Movement.LEFT
else:
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 = self.CURRENT_COORD
self.ghost = self.current.ghost()
self.move_ghost()
else:
self.new_current()
def pause(self):
self.state = State.PAUSED
self.phase = Phase.PAUSED
self.stop_all()
self.pressed_actions = []
self.auto_repeat = False
self.stop(self.repeat_action)
def resume(self):
self.state = State.PLAYING
self.start(self.fall, self.fall_delay)
if self.current.prelocked:
self.start(self.lock, self.lock_delay)
self.start(self.update_time, 1)
self.phase = Phase.FALLING
self.start(self.fall, self.stats.fall_delay)
if self.phase == Phase.LOCK:
self.start(self.pattern_phase, self.stats.lock_delay)
self.start(self.stats.update_time, 1)
def game_over(self):
self.state = State.OVER
self.phase = Phase.OVER
self.stop_all()
self.save_high_score()
self.on_game_over()
def on_game_over(self):
pass
def stop_all(self):
self.stop(self.fall)
self.stop(self.lock)
self.stop(self.update_time)
def update_time(self):
self.time += 1
self.stop(self.pattern_phase)
self.stop(self.stats.update_time)
def do_action(self, action):
action()
if action in self.autorepeatable_actions:
self.auto_repeat = False
self.pressed_actions.append(action)
self.restart(self.repeat_action, self.AUTOREPEAT_DELAY)
if action == self.soft_drop:
delay = self.stats.fall_delay / 20
else:
delay = self.AUTOREPEAT_DELAY
self.restart(self.repeat_action, delay)
def repeat_action(self):
if self.pressed_actions:
@ -387,16 +467,16 @@ class TetrisLogic:
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
self.stats.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
self.stats.high_score = 0
def save_high_score(self):
crypted_high_score = self.high_score ^ CRYPT_KEY
crypted_high_score = self.stats.high_score ^ CRYPT_KEY
crypted_high_score = pickle.dumps(crypted_high_score)
return crypted_high_score

View File

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
from .utils import Coord, Rotation
import random
from .utils import Coord, Rotation, Color
class Mino:
@ -14,9 +16,20 @@ class MetaTetromino(type):
Tetromino.shapes.append(cls)
class Tetromino(list):
class Tetromino:
shapes = []
random_bag = []
def __new__(cls):
if not cls.random_bag:
cls.random_bag = list(cls.shapes)
random.shuffle(cls.random_bag)
return cls.random_bag.pop()()
class TetrominoBase(list):
# Super rotation system
SRS = {
Rotation.CLOCKWISE: (
@ -44,20 +57,20 @@ class Tetromino(list):
return type(self)()
class O(Tetromino, metaclass=MetaTetromino):
class O_Tetrimino(TetrominoBase, 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(Tetromino, metaclass=MetaTetromino):
class I_Tetrimino(TetrominoBase, metaclass=MetaTetromino):
SRS = {
Rotation.CLOCKWISE: (
@ -74,34 +87,34 @@ class I(Tetromino, metaclass=MetaTetromino):
),
}
MINOES_COORDS = (Coord(-1, 0), Coord(0, 0), Coord(1, 0), Coord(2, 0))
MINOES_COLOR = "cyan"
MINOES_COLOR = Color.CYAN
class T(Tetromino, metaclass=MetaTetromino):
class T_Tetrimino(TetrominoBase, 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(Tetromino, metaclass=MetaTetromino):
class L_Tetrimino(TetrominoBase, 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(Tetromino, metaclass=MetaTetromino):
class J_Tetrimino(TetrominoBase, 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(Tetromino, metaclass=MetaTetromino):
class S_Tetrimino(TetrominoBase, 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(Tetromino, metaclass=MetaTetromino):
class Z_Tetrimino(TetrominoBase, metaclass=MetaTetromino):
MINOES_COORDS = (Coord(-1, 1), Coord(0, 1), Coord(0, 0), Coord(1, 0))
MINOES_COLOR = "red"
MINOES_COLOR = Color.RED

View File

@ -28,5 +28,23 @@ 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
class Phase:
STARTING = "STARTING"
GENERATION = "GENERATION"
FALLING = "FALLING"
LOCK = "LOCK"
PATTERN = "PATTERN"
PAUSED = "PAUSED"
OVER = "OVER"