Compare commits

...

13 Commits
0.5 ... master

Author SHA1 Message Date
eca466519b App FFmpeg4 requirement 2019-10-10 19:41:10 +02:00
f5cfb2221f fix held piece texture on lock 2019-10-09 00:18:40 +02:00
250e79c458 V0.6 Release
Speed up
Fix resize
2019-10-08 22:50:13 +02:00
d85c63701c fix resize 2019-10-08 22:48:31 +02:00
4df3c6c9ba optimize 2019-10-08 22:31:05 +02:00
5ed15da4ed small fixes 2019-10-08 19:37:17 +02:00
a3dc434c88 move next piece logic in NextQueue class + comments 2019-10-08 10:26:36 +02:00
2895570f6e pass matrix on new game 2019-10-08 08:50:26 +02:00
0815409953 permit to move piece before game over 2019-10-08 08:42:15 +02:00
8e6359bfa3 comment 2019-10-08 08:35:08 +02:00
0d7470fd51 black 2019-10-08 02:35:04 +02:00
fe93336bb9 __matmul__ 2019-10-08 02:29:57 +02:00
578b126b3e coord rotate 2019-10-08 02:01:41 +02:00
8 changed files with 139 additions and 89 deletions

View File

@ -6,7 +6,8 @@ Tetris clone made with Python and Arcade graphic library
## Requirements ## Requirements
* [Python](https://www.python.org/) 3.6 or later * [Python 3.6 or later](https://www.python.org/)
* [FFmpeg 4](http://ubuntuhandbook.org/index.php/2019/08/install-ffmpeg-4-2-ubuntu-18-04/)
## Install ## Install

View File

@ -1,4 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Tetris clone with arcade GUI library"""
import sys import sys
import random import random
@ -20,7 +23,14 @@ import os
import itertools import itertools
import configparser import configparser
from tetrislogic import TetrisLogic, Color, Coord, I_Tetrimino, Movement, AbstractTimer from tetrislogic import (
TetrisLogic,
Color,
Coord,
I_Tetrimino,
Movement,
AbstractScheduler,
)
# Constants # Constants
@ -35,6 +45,7 @@ FALL_DELAY = 1
AUTOREPEAT_DELAY = 0.300 AUTOREPEAT_DELAY = 0.300
AUTOREPEAT_PERIOD = 0.010 AUTOREPEAT_PERIOD = 0.010
PARTICULE_ACCELERATION = 1.1 PARTICULE_ACCELERATION = 1.1
EXPLOSION_ANIMATION = 1
# Piece init coord # Piece init coord
MATRIX_PIECE_COORD = Coord(4, LINES) MATRIX_PIECE_COORD = Coord(4, LINES)
@ -134,7 +145,7 @@ class State:
OVER = 3 OVER = 3
class Timer(AbstractTimer): class Scheduler(AbstractScheduler):
def __init__(self): def __init__(self):
self.tasks = {} self.tasks = {}
@ -171,18 +182,24 @@ class MinoSprite(arcade.Sprite):
self.append_texture(TEXTURES[mino.color]) self.append_texture(TEXTURES[mino.color])
self.append_texture(TEXTURES[Color.LOCKED]) self.append_texture(TEXTURES[Color.LOCKED])
self.set_texture(0) self.set_texture(0)
self.resize()
def resize(self):
self.scale = self.window.scale
self.size = MINO_SIZE * self.window.scale
def update(self, x, y): def update(self, x, y):
self.scale = self.window.scale self.left = self.window.matrix.bg.left + x * self.size
size = MINO_SIZE * self.scale self.bottom = self.window.matrix.bg.bottom + y * self.size
self.left = self.window.matrix.bg.left + x * size
self.bottom = self.window.matrix.bg.bottom + y * size def fall(self, lines_cleared):
self.bottom -= MINO_SIZE * self.window.scale * lines_cleared
class MinoesSprites(arcade.SpriteList): class MinoesSprites(arcade.SpriteList):
def resize(self, scale): def resize(self):
for sprite in self: for sprite in self:
sprite.scale = scale sprite.resize()
self.update() self.update()
@ -191,6 +208,7 @@ class TetrominoSprites(MinoesSprites):
super().__init__() super().__init__()
self.tetromino = tetromino self.tetromino = tetromino
self.alpha = alpha self.alpha = alpha
self.window = window
for mino in tetromino: for mino in tetromino:
mino.sprite = MinoSprite(mino, window, alpha) mino.sprite = MinoSprite(mino, window, alpha)
self.append(mino.sprite) self.append(mino.sprite)
@ -203,14 +221,13 @@ class TetrominoSprites(MinoesSprites):
def set_texture(self, texture): def set_texture(self, texture):
for mino in self.tetromino: for mino in self.tetromino:
mino.sprite.set_texture(texture) mino.sprite.set_texture(texture)
self.update() mino.sprite.scale = self.window.scale
class MatrixSprites(MinoesSprites): class MatrixSprites(MinoesSprites):
def __init__(self, matrix): def __init__(self, matrix):
super().__init__() super().__init__()
self.matrix = matrix self.matrix = matrix
self.update()
def update(self): def update(self):
for y, line in enumerate(self.matrix): for y, line in enumerate(self.matrix):
@ -218,15 +235,17 @@ class MatrixSprites(MinoesSprites):
if mino: if mino:
mino.sprite.update(x, y) mino.sprite.update(x, y)
def remove_line(self, y): def remove_lines(self, lines_to_remove):
for mino in self.matrix[y]: for y in lines_to_remove:
if mino: for mino in self.matrix[y]:
self.remove(mino.sprite) if mino:
self.remove(mino.sprite)
class TetrArcade(TetrisLogic, arcade.Window): class TetrArcade(TetrisLogic, arcade.Window):
"""Tetris clone with arcade GUI library"""
timer = Timer() timer = Scheduler()
def __init__(self): def __init__(self):
locale.setlocale(locale.LC_ALL, "") locale.setlocale(locale.LC_ALL, "")
@ -385,10 +404,10 @@ AGAIN""".format(
self.play_music = self.conf["MUSIC"].getboolean("play") self.play_music = self.conf["MUSIC"].getboolean("play")
def on_new_game(self, next_pieces): def on_new_game(self, matrix, next_pieces):
self.highlight_texts = [] self.highlight_texts = []
self.matrix.sprites = MatrixSprites(self.matrix) self.matrix.sprites = MatrixSprites(matrix)
for piece in next_pieces: for piece in next_pieces:
piece.sprites = TetrominoSprites(piece, self) piece.sprites = TetrominoSprites(piece, self)
@ -408,12 +427,18 @@ AGAIN""".format(
next_pieces[-1].sprites = TetrominoSprites(next_pieces[-1], self) next_pieces[-1].sprites = TetrominoSprites(next_pieces[-1], self)
for piece, coord in zip(next_pieces, NEXT_PIECES_COORDS): for piece, coord in zip(next_pieces, NEXT_PIECES_COORDS):
piece.coord = coord piece.coord = coord
for piece in [falling_piece, ghost_piece] + next_pieces:
piece.sprites.update()
def on_falling_phase(self, falling_piece): def on_falling_phase(self, falling_piece, ghost_piece):
falling_piece.sprites.set_texture(Texture.NORMAL) falling_piece.sprites.set_texture(Texture.NORMAL)
falling_piece.sprites.update()
ghost_piece.sprites.update()
def on_locked(self, falling_piece): def on_locked(self, falling_piece, ghost_piece):
falling_piece.sprites.set_texture(Texture.LOCKED) falling_piece.sprites.set_texture(Texture.LOCKED)
falling_piece.sprites.update()
ghost_piece.sprites.update()
def on_locks_down(self, matrix, falling_piece): def on_locks_down(self, matrix, falling_piece):
falling_piece.sprites.set_texture(Texture.NORMAL) falling_piece.sprites.set_texture(Texture.NORMAL)
@ -421,6 +446,10 @@ AGAIN""".format(
matrix.sprites.append(mino.sprite) matrix.sprites.append(mino.sprite)
def on_animate_phase(self, matrix, lines_to_remove): def on_animate_phase(self, matrix, lines_to_remove):
if not lines_to_remove:
return
self.timer.cancel(self.clean_particules)
for y in lines_to_remove: for y in lines_to_remove:
line_textures = tuple(TEXTURES[mino.color] for mino in matrix[y]) line_textures = tuple(TEXTURES[mino.color] for mino in matrix[y])
self.exploding_minoes[y] = arcade.Emitter( self.exploding_minoes[y] = arcade.Emitter(
@ -433,22 +462,20 @@ AGAIN""".format(
2 * COLLUMNS * MINO_SIZE, 2 * COLLUMNS * MINO_SIZE,
5 * MINO_SIZE, 5 * MINO_SIZE,
), ),
lifetime=0.2, lifetime=EXPLOSION_ANIMATION,
center_xy=arcade.rand_on_line((0, 0), (matrix.bg.width, 0)), center_xy=arcade.rand_on_line((0, 0), (matrix.bg.width, 0)),
scale=self.scale, scale=self.scale,
alpha=NORMAL_ALPHA, alpha=NORMAL_ALPHA,
change_angle=2, change_angle=2,
mutation_callback=self.speed_up_particule,
), ),
) )
self.timer.postpone(self.clean_particules, EXPLOSION_ANIMATION)
def speed_up_particule(self, particule): def clean_particules(self):
particule.change_x *= PARTICULE_ACCELERATION self.exploding_minoes = [None for y in range(LINES)]
particule.change_y *= PARTICULE_ACCELERATION
def on_eliminate_phase(self, matrix, lines_to_remove): def on_eliminate_phase(self, matrix, lines_to_remove):
for y in lines_to_remove: matrix.sprites.remove_lines(lines_to_remove)
matrix.sprites.remove_line(y)
def on_completion_phase(self, pattern_name, pattern_score, nb_combo, combo_score): def on_completion_phase(self, pattern_name, pattern_score, nb_combo, combo_score):
if pattern_score: if pattern_score:
@ -460,6 +487,8 @@ AGAIN""".format(
held_piece.coord = HELD_PIECE_COORD held_piece.coord = HELD_PIECE_COORD
if type(held_piece) == I_Tetrimino: if type(held_piece) == I_Tetrimino:
held_piece.coord += Movement.LEFT held_piece.coord += Movement.LEFT
held_piece.sprites.set_texture(Texture.NORMAL)
held_piece.sprites.update()
def on_pause(self): def on_pause(self):
self.state = State.PAUSED self.state = State.PAUSED
@ -600,7 +629,7 @@ AGAIN""".format(
self.matrix.bg.left = int(self.matrix.bg.left) self.matrix.bg.left = int(self.matrix.bg.left)
self.matrix.bg.top = int(self.matrix.bg.top) self.matrix.bg.top = int(self.matrix.bg.top)
self.matrix.sprites.resize(self.scale) self.matrix.sprites.resize()
for tetromino in [ for tetromino in [
self.held.piece, self.held.piece,
@ -608,7 +637,7 @@ AGAIN""".format(
self.matrix.ghost, self.matrix.ghost,
] + self.next.pieces: ] + self.next.pieces:
if tetromino: if tetromino:
tetromino.sprites.resize(self.scale) tetromino.sprites.resize()
def load_high_score(self): def load_high_score(self):
try: try:
@ -636,13 +665,6 @@ High score could not be saved:
) )
def update(self, delta_time): def update(self, delta_time):
for piece in [
self.held.piece,
self.matrix.piece,
self.matrix.ghost,
] + self.next.pieces:
if piece:
piece.sprites.update()
for exploding_minoes in self.exploding_minoes: for exploding_minoes in self.exploding_minoes:
if exploding_minoes: if exploding_minoes:
exploding_minoes.update() exploding_minoes.update()

View File

@ -29,7 +29,7 @@ options = {
} }
setup( setup(
name="TetrArcade", name="TetrArcade",
version="0.5", version="0.6",
description="Tetris clone", description="Tetris clone",
author="AdrienMalin", author="AdrienMalin",
executables=[executable], executables=[executable],

View File

@ -29,8 +29,6 @@ game.lock_phase()
game.hold() game.hold()
game.update(0) game.update(0)
game.on_draw() game.on_draw()
game.matrix.sprites.update()
game.on_draw()
while game.state != State.OVER: while game.state != State.OVER:
game.hard_drop() game.hard_drop()
game.on_draw() game.on_draw()

View File

@ -12,4 +12,4 @@ from .tetromino import (
T_Tetrimino, T_Tetrimino,
Z_Tetrimino, Z_Tetrimino,
) )
from .tetrislogic import TetrisLogic, Matrix, AbstractTimer from .tetrislogic import TetrisLogic, Matrix, AbstractScheduler

View File

@ -14,7 +14,7 @@ AUTOREPEAT_DELAY = 0.300 # Official : 0.300 s
AUTOREPEAT_PERIOD = 0.010 # Official : 0.010 s AUTOREPEAT_PERIOD = 0.010 # Official : 0.010 s
# Piece init coord # Piece init coord
MATRIX_PIECE_COORD = Coord(4, LINES) FALLING_PIECE_COORD = Coord(4, LINES)
# Scores # Scores
LINES_CLEAR_NAME = "LINES_CLEAR_NAME" LINES_CLEAR_NAME = "LINES_CLEAR_NAME"

View File

@ -1,4 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Tetris game logic meant to be implemented with GUI
Follows Tetris Guidelines 2009 (see https://tetris.fandom.com/wiki/Tetris_Guideline)
"""
import pickle import pickle
from .utils import Coord, Movement, Spin, T_Spin, T_Slot from .utils import Coord, Movement, Spin, T_Spin, T_Slot
@ -11,7 +16,7 @@ from .consts import (
FALL_DELAY, FALL_DELAY,
AUTOREPEAT_DELAY, AUTOREPEAT_DELAY,
AUTOREPEAT_PERIOD, AUTOREPEAT_PERIOD,
MATRIX_PIECE_COORD, FALLING_PIECE_COORD,
SCORES, SCORES,
LINES_CLEAR_NAME, LINES_CLEAR_NAME,
) )
@ -20,36 +25,46 @@ from .consts import (
CRYPT_KEY = 987943759387540938469837689379857347598347598379584857934579343 CRYPT_KEY = 987943759387540938469837689379857347598347598379584857934579343
class AbstractTimer: class AbstractScheduler:
"""Scheduler class to be implemented"""
def postpone(task, delay): def postpone(task, delay):
raise Warning("AbstractTimer.postpone is not implemented.") """schedule callable task once after delay in second"""
raise Warning("AbstractScheduler.postpone is not implemented.")
def cancel(self, task): def cancel(self, task):
raise Warning("AbstractTimer.stop is not implemented.") """cancel task if schedule of pass"""
raise Warning("AbstractScheduler.stop is not implemented.")
def reset(self, task, period): def reset(self, task, delay):
"""cancel and reschedule task"""
self.timer.cancel(task) self.timer.cancel(task)
self.timer.postpone(task, period) self.timer.postpone(task, delay)
class PieceContainer: class AbstractPieceContainer:
def __init__(self): def __init__(self):
self.piece = None self.piece = None
class HoldQueue(PieceContainer): class HoldQueue(AbstractPieceContainer):
"""the storage place where players can Hold any falling Tetrimino for use later"""
pass pass
class Matrix(list, PieceContainer): class Matrix(list, AbstractPieceContainer):
"""the rectangular arrangement of cells creating the active game area, usually 10 columns wide by 20 rows high."""
def __init__(self, lines, collumns): def __init__(self, lines, collumns):
list.__init__(self) list.__init__(self)
PieceContainer.__init__(self) AbstractPieceContainer.__init__(self)
self.lines = lines self.lines = lines
self.collumns = collumns self.collumns = collumns
self.ghost = None self.ghost = None
def reset(self): def new_game(self):
"""Removes all minoes in matrix"""
self.clear() self.clear()
for y in range(self.lines + 3): for y in range(self.lines + 3):
self.append_new_line() self.append_new_line()
@ -74,14 +89,25 @@ class Matrix(list, PieceContainer):
) )
class NextQueue(PieceContainer): class NextQueue(AbstractPieceContainer):
"""Displays the Next Tetrimino(s) to be placed (generated) just above the Matrix"""
def __init__(self, nb_pieces): def __init__(self, nb_pieces):
super().__init__() super().__init__()
self.nb_pieces = nb_pieces self.nb_pieces = nb_pieces
self.pieces = [] self.pieces = []
def new_game(self):
self.pieces = [Tetromino() for n in range(self.nb_pieces)]
def generation_phase(self):
self.pieces.append(Tetromino())
return self.pieces.pop(0)
class Stats: class Stats:
"""Game statistics"""
def _get_score(self): def _get_score(self):
return self._score return self._score
@ -147,37 +173,41 @@ class Stats:
class TetrisLogic: class TetrisLogic:
"""Tetris game logic"""
# These class attributes can be redefined on inheritance # These class attributes can be redefined on inheritance
AUTOREPEAT_DELAY = AUTOREPEAT_DELAY AUTOREPEAT_DELAY = AUTOREPEAT_DELAY
AUTOREPEAT_PERIOD = AUTOREPEAT_PERIOD AUTOREPEAT_PERIOD = AUTOREPEAT_PERIOD
MATRIX_PIECE_COORD = MATRIX_PIECE_COORD FALLING_PIECE_COORD = FALLING_PIECE_COORD
timer = AbstractTimer() timer = AbstractScheduler()
def __init__(self, lines=LINES, collumns=COLLUMNS, next_pieces=NEXT_PIECES): def __init__(self, lines=LINES, collumns=COLLUMNS, nb_next_pieces=NEXT_PIECES):
"""init game with a `lines`x`collumns` size matrix
and `nb_next_pieces`"""
self.stats = Stats() self.stats = Stats()
self.load_high_score() self.load_high_score()
self.held = HoldQueue() self.held = HoldQueue()
self.matrix = Matrix(lines, collumns) self.matrix = Matrix(lines, collumns)
self.next = NextQueue(next_pieces) self.next = NextQueue(nb_next_pieces)
self.autorepeatable_actions = (self.move_left, self.move_right, self.soft_drop) self.autorepeatable_actions = (self.move_left, self.move_right, self.soft_drop)
self.pressed_actions = [] self.pressed_actions = []
def new_game(self, level=1): def new_game(self, level=1):
"""start a new game at `level`"""
self.stats.new_game(level) self.stats.new_game(level)
self.pressed_actions = [] self.pressed_actions = []
self.matrix.reset() self.matrix.new_game()
self.next.pieces = [Tetromino() for n in range(self.next.nb_pieces)] self.next.new_game()
self.held.piece = None self.held.piece = None
self.timer.postpone(self.stats.update_time, 1) self.timer.postpone(self.stats.update_time, 1)
self.on_new_game(self.next.pieces) self.on_new_game(self.matrix, self.next.pieces)
self.new_level() self.new_level()
def on_new_game(self, next_pieces): def on_new_game(self, matrix, next_pieces):
pass pass
def new_level(self): def new_level(self):
@ -192,18 +222,17 @@ class TetrisLogic:
def generation_phase(self, held_piece=None): def generation_phase(self, held_piece=None):
if not held_piece: if not held_piece:
self.matrix.piece = self.next.pieces.pop(0) self.matrix.piece = self.next.generation_phase()
self.next.pieces.append(Tetromino()) self.matrix.piece.coord = self.FALLING_PIECE_COORD
self.matrix.piece.coord = self.MATRIX_PIECE_COORD
self.matrix.ghost = self.matrix.piece.ghost() self.matrix.ghost = self.matrix.piece.ghost()
self.refresh_ghost() self.refresh_ghost()
# if self.pressed_actions:
# self.timer.postpone(self.repeat_action, self.AUTOREPEAT_DELAY)
self.on_generation_phase( self.on_generation_phase(
self.matrix, self.matrix.piece, self.matrix.ghost, self.next.pieces self.matrix, self.matrix.piece, self.matrix.ghost, self.next.pieces
) )
if self.move(Movement.DOWN): if self.matrix.space_to_move(
self.matrix.piece.coord, (mino.coord for mino in self.matrix.piece)
):
self.falling_phase() self.falling_phase()
else: else:
self.game_over() self.game_over()
@ -226,17 +255,14 @@ class TetrisLogic:
self.timer.cancel(self.locks_down) self.timer.cancel(self.locks_down)
self.matrix.piece.locked = False self.matrix.piece.locked = False
self.timer.postpone(self.lock_phase, self.stats.fall_delay) self.timer.postpone(self.lock_phase, self.stats.fall_delay)
self.on_falling_phase(self.matrix.piece) self.on_falling_phase(self.matrix.piece, self.matrix.ghost)
def on_falling_phase(self, falling_piece): def on_falling_phase(self, falling_piece, ghost_piece):
pass pass
def lock_phase(self): def lock_phase(self):
self.move(Movement.DOWN) self.move(Movement.DOWN)
def on_locked(self, falling_piece):
pass
def move(self, movement, rotated_coords=None, lock=True): def move(self, movement, rotated_coords=None, lock=True):
potential_coord = self.matrix.piece.coord + movement potential_coord = self.matrix.piece.coord + movement
potential_minoes_coords = rotated_coords or ( potential_minoes_coords = rotated_coords or (
@ -254,17 +280,17 @@ class TetrisLogic:
self.falling_phase() self.falling_phase()
else: else:
self.matrix.piece.locked = True self.matrix.piece.locked = True
self.on_locked(self.matrix.piece) self.on_locked(self.matrix.piece, self.matrix.ghost)
self.timer.reset(self.locks_down, self.stats.lock_delay) self.timer.reset(self.locks_down, self.stats.lock_delay)
return True return True
else: else:
return False return False
def on_locked(self, falling_piece, ghost_piece):
pass
def rotate(self, spin): def rotate(self, spin):
rotated_coords = tuple( rotated_coords = tuple(mino.coord @ spin for mino in self.matrix.piece)
Coord(spin * mino.coord.y, -spin * mino.coord.x)
for mino in self.matrix.piece
)
for rotation_point, liberty_degree in enumerate( for rotation_point, liberty_degree in enumerate(
self.matrix.piece.SRS[spin][self.matrix.piece.orientation], start=1 self.matrix.piece.SRS[spin][self.matrix.piece.orientation], start=1
): ):
@ -280,7 +306,6 @@ class TetrisLogic:
return False return False
def locks_down(self): def locks_down(self):
# self.timer.cancel(self.repeat_action)
self.timer.cancel(self.lock_phase) self.timer.cancel(self.lock_phase)
# Game over # Game over
@ -318,24 +343,25 @@ class TetrisLogic:
else: else:
t_spin = T_Spin.NONE t_spin = T_Spin.NONE
# Clear complete lines # Complete lines
self.lines_to_remove = [] lines_to_remove = []
for y, line in reversed(list(enumerate(self.matrix))): for y, line in reversed(list(enumerate(self.matrix))):
if all(mino for mino in line): if all(mino for mino in line):
self.lines_to_remove.append(y) lines_to_remove.append(y)
lines_cleared = len(self.lines_to_remove)
lines_cleared = len(lines_to_remove)
if lines_cleared: if lines_cleared:
self.stats.lines_cleared += lines_cleared self.stats.lines_cleared += lines_cleared
# Animate phase # Animate phase
self.on_animate_phase(self.matrix, self.lines_to_remove) self.on_animate_phase(self.matrix, lines_to_remove)
# Eliminate phase # Eliminate phase
self.on_eliminate_phase(self.matrix, self.lines_to_remove) self.on_eliminate_phase(self.matrix, lines_to_remove)
for y in self.lines_to_remove: for y in lines_to_remove:
self.matrix.pop(y) self.matrix.pop(y)
self.matrix.append_new_line() self.matrix.append_new_line()
# Completion phase # Completion phase

View File

@ -7,6 +7,9 @@ class Coord:
def __add__(self, other): def __add__(self, other):
return Coord(self.x + other.x, self.y + other.y) return Coord(self.x + other.x, self.y + other.y)
def __matmul__(self, spin):
return Coord(spin * self.y, -spin * self.x)
class Movement: class Movement: