from random import *
from math import sin, cos, radians
import time
import keyboard as key
import pygame as game
import numpy as np

# ******************************* -- ERROR CODES -- ************************************ #

ERROR_NUMBER = 0
ERROR_MESSAGE = ""
# 100: Couldn't initialize display
#
#
# 200: Couldn't load image
# 201: Couldn't load block image

# ************************************************************************************** #

# ******************************** -- CONSTANTS -- ************************************* #
WIDTH = 576
HEIGHT = 960
GRID = 32
GRID_HEIGHT = int(HEIGHT / GRID)
GRID_WIDTH = int(WIDTH / GRID)
FRAMES = 64
background_color = (15, 15, 15)
color_darkgray = (60, 60, 60)
global pvcolor
pvcolor = []
global bag
bag = 0

# ************************************************************************************** #

# -- FIGURES --
figures = [game.image.load('sprites/l_block_1.png'), game.image.load('sprites/l_block_2.png'),
           game.image.load('sprites/s_block_1.png'), game.image.load('sprites/s_block_2.png'),
           game.image.load('sprites/square_block.png'), game.image.load('sprites/t_block.png'),
           game.image.load('sprites/long_block.png'), game.image.load('sprites/t_block.png')]

figuresnext = [game.image.load('sprites/l_block_1.png'), game.image.load('sprites/l_block_2.png'),
           game.image.load('sprites/s_block_1.png'), game.image.load('sprites/s_block_2.png'),
           game.image.load('sprites/square_block.png'), game.image.load('sprites/t_block.png'),
           game.image.load('sprites/long_block.png'), game.image.load('sprites/t_block.png')]

values = [0, 1, 2, 3, 4, 5, 6]

########################################################################################


def errorCheck(message, number, error=True, value="Exists"):
    if not error or value == None:
        print(F"DEBUG ERROR NUMBER {number}: {message}")
        exit(number)


# Pick a random color, which can't be the same as the previous three
def newColor():
    value = randint(1, 7)
    colorpick = {
        "1": (0, 255, 255),  # Cyan
        "2": (255, 255, 0),  # Yellow
        "3": (128, 0, 128),  # Purple
        "4": (0, 255, 0),  # Green
        "5": (255, 0, 0),  # Red
        "6": (0, 0, 255),  # Blue
        "7": (255, 127, 0),  # Orange
    }
    for k in range(len(pvcolor)):
        if pvcolor[k] == colorpick[f"{value}"]:
            return newColor()
    return colorpick[f"{value}"]


def randomBlock():
    # Create a "bag" of pieces. Each of this "bags" contains 1 of each piece in a random order.
    # This ensures that every block will appear every 7 blocks, and allows for
    # up to 2 repeated blocks in a row
    global bag
    if bag <= 0:
        shuffle(values)
        values.append(7)
    bag += 1
    if bag > 6 or values[bag] == None:
        bag = 0
        del values[-1]
        return randomBlock()
    if figures[values[bag]] == None:
        errorCheck("Couldn't load block image", 201, value=figures[values[bag]])
    return figures[values[bag]]


class collidable_block(game.sprite.Sprite):
    def __init__(self, x, y):
        super(collidable_block, self).__init__()
        self.image = game.image.load('sprites/block.png')
        self.rect = self.image.get_rect(topleft=(x, y))
        self.mask = game.mask.from_surface(self.image)

    def draw(self, surface, x, y):
        for i in range(10):
            surface.blit(self.image, (x+GRID*i+GRID, y))


class wall(game.sprite.Sprite):
    def __init__(self, x, y):
        super(wall, self).__init__()
        self.image = game.image.load('sprites/walls.png')
        self.rect = self.image.get_rect(topleft=(x, -GRID*3))
        self.mask = game.mask.from_surface(self.image)

    def draw(self, surface, x, y):
        for i in range(2):
            surface.blit(self.image, (x+(WIDTH-GRID*7)*i, -GRID*3))

class nextBlock(game.sprite.Sprite):
    def __init__(self):
        super(nextBlock, self).__init__()
        self.x = GRID * 13
        self.y = GRID * 3 + GRID / 2
        self.image = figuresnext[values[bag + 1]]

    def rotate(self):
        self.image = game.transform.rotate(self.image, -90)
        self.mask = game.mask.from_surface(self.image)

    def draw(self, surface):
        global bag
        if bag < 6:
            self.image = figuresnext[values[bag + 1]]
        else:
            self.image = figuresnext[values[-1]]
        if values[bag+1] == 6:
            self.rotate()
            surface.blit(self.image, (self.x, self.y-GRID))
        elif values[bag+1] == 4:
            surface.blit(self.image, (self.x-GRID/2, self.y))
        else:
            surface.blit(self.image, (self.x, self.y))


class controlblock(game.sprite.Sprite):
    def __init__(self):
        super(controlblock, self).__init__()
        global pvcolor
        global bag
        self.x = GRID*3
        self.y = -GRID*3
        self.angle = 0
        self.image = randomBlock()
        self.rect = self.image.get_rect()
        self.mask = game.mask.from_surface(self.image)
        var = game.PixelArray(self.image)
        newcolor = newColor()
        if len(pvcolor) < 3:
            pvcolor.append(newcolor)
        else:
            del pvcolor[0]
            pvcolor.append(newcolor)
        darker = tuple(x/2 for x in newcolor)
        var.replace((255, 255, 255), newcolor)
        var.replace((0, 0, 0), darker)
        del var

    def copypixels(self):
        pixel = game.PixelArray(self.image)
        #game.pixelcopy.surface_to_array(pixel, self.image)
        return pixel

    def move(self, x, y):
        self.x += x
        self.y += y

    def rotate(self):
        if values[bag] != 4:
            self.image = game.transform.rotate(self.image, -90)
            self.mask = game.mask.from_surface(self.image)

    def draw(self, surface):
        self.rect = game.Rect(self.x, self.y, 0, 0)
        surface.blit(self.image, (self.x, self.y))

class placedblock(game.sprite.Sprite):
    def __init__(self, x, y, pixelarray):
        super(placedblock, self).__init__()
        self.x = x
        self.y = y
        self.rect = game.Rect(0, 0, GRID, GRID)
        self.image = game.PixelArray.make_surface(pixelarray)

    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))
        #game.draw.rect(surface, (255,255,255), game.Rect(x+GRID,y,GRID,GRID))


def main():
    game.init()
    game.display.init()
    errorCheck("Couldn't initialize display", 100, game.display.get_init())
    DISPLAY = game.display.set_mode([WIDTH, HEIGHT])
    DISPLAY.fill(background_color)
    game.display.set_caption("Tetris in Python")

    decwall = game.image.load("sprites/walls.png")
    nextdisplay = game.Rect((GRID*12, GRID * 2), (GRID*5, GRID*5))

    def render():
        DISPLAY.fill(background_color)

        for k in range(5):
            DISPLAY.blit(decwall, (GRID*k+GRID*12, 0))

        DISPLAY.blit(decwall, (WIDTH - GRID, 0))
        game.draw.rect(DISPLAY, background_color, nextdisplay)
        nxtblock.draw(DISPLAY)

        for b in collision:
            b.draw(DISPLAY, 0, HEIGHT-GRID)

        w_left.draw(DISPLAY, 0, -GRID*3)
        w_right.draw(DISPLAY, 0, -GRID*3)
        block[n].draw(DISPLAY)
        #for c in block:
        #    c.draw(DISPLAY)
        for m in placedblocks:
            m.draw(DISPLAY)
        game.display.flip()

    n = 0  # Current block number
    block = [controlblock()]
    placedblocks = []
    collision = []
    nxtblock = nextBlock()
    for i in range(10):
        collision.append(collidable_block(GRID*i+GRID, HEIGHT-GRID))
    w_left = 0
    w_right = 0
    for i in range(1):
        w_left = wall((WIDTH - GRID * 9) * i + 32, 0)
        w_right = wall((WIDTH - GRID * 9) * 1 + 32, 0)

    collision_blocks = game.sprite.Group(collision)
    self_collision = game.sprite.Group()
    wall_left = game.sprite.Group(w_left)
    wall_right = game.sprite.Group(w_right)

    clock = game.time.Clock()
    time = 0
    stop = False

    while True:
        game.event.pump()

        clock.tick(FRAMES)

        if game.sprite.spritecollideany(block[n], self_collision, game.sprite.collide_mask):
            block[n].move(0, -GRID)
            self_collision.add(block[n])
            block.append(controlblock())
            placedblocks.append(placedblock(block[n].x, block[n].y, block[n].copypixels()))
            n += 1

        if not game.sprite.spritecollideany(block[n], collision_blocks, game.sprite.collide_mask):
            if time % (FRAMES / 2) == 0:
                block[n].move(0, GRID)
                time = 0

            # Up and down
            if key.is_pressed('down'):
                block[n].move(0, 32)

            # Left and right
            if not stop and key.is_pressed('left') \
                    and not game.sprite.spritecollideany(block[n], wall_left, game.sprite.collide_mask):
                block[n].move(-GRID, 0)
                stop = True
            elif not stop and key.is_pressed('right') \
                    and not game.sprite.spritecollideany(block[n], wall_right, game.sprite.collide_mask):
                block[n].move(GRID, 0)
                stop = True

            if not stop and key.is_pressed('r'):
                block[n].rotate()
                stop = True

            # Reset
            if stop and not key.is_pressed('left') \
                    and not key.is_pressed('right') \
                    and not key.is_pressed('r'):
                stop = False
        else:
            block[n].move(0, -GRID)
            self_collision.add(block[n])
            block.append(controlblock())
            placedblocks.append(placedblock(block[n].x, block[n].y, block[n].copypixels()))
            n += 1

        render()

        if key.is_pressed('escape'):
            break

        time += 1


if __name__ == "__main__":
    main() 

Python Online Compiler

Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.

Taking inputs (stdin)

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.

import sys
name = sys.stdin.readline()
print("Hello "+ name)

About Python

Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.

Tutorial & Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if conditional-expression
    #code
elif conditional-expression
    #code
else:
    #code

Note:

Indentation is very important in Python, make sure the indentation is followed correctly

2. For:

For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.

Example:

mylist=("Iphone","Pixel","Samsung")
for i in mylist:
    print(i)

3. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while condition  
    #code 

Collections

There are four types of collections in Python.

1. List:

List is a collection which is ordered and can be changed. Lists are specified in square brackets.

Example:

mylist=["iPhone","Pixel","Samsung"]
print(mylist)

2. Tuple:

Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.

Example:

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)

Below throws an error if you assign another value to tuple again.

myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)

3. Set:

Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.

Example:

myset = {"iPhone","Pixel","Samsung"}
print(myset)

4. Dictionary:

Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.

Example:

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11"
}
print(mydict)

Supported Libraries

Following are the libraries supported by OneCompiler's Python compiler

NameDescription
NumPyNumPy python library helps users to work on arrays with ease
SciPySciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation
SKLearn/Scikit-learnScikit-learn or Scikit-learn is the most useful library for machine learning in Python
PandasPandas is the most efficient Python library for data manipulation and analysis
DOcplexDOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling