Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tetris 3
#1
import pygame
import random

pygame.font.init()

#GLOBAL VARS

s_width = 800
s_height = 700
play_width = 300
play_height = 600
block_size = 30

top_left_x = (s_width - play_width) // 2
top_left_y = (s_height - play_height)

#SHAPE FORMATS

S= [['.....',
    '.....',
    '..00.',
    '.00..',
    '.....'],
   ['.....',
    '..0..',
    '..00.',
    '...0.',
    '.....']]

Z= [['.....',
     '.....'
     '.00..'
     '..00.'
     '.....'
     '.....']]

I = [['..0..',
      '..0..',
      '..0..',
      '..0..',
      '..0..'],
     ['.....',
      '0000.',
      '.....',
      '.....',
      '.....',]]

O = [['.....',
      '.....',
      '.00..',
      '.00..',
      '.....']]

J = [['.....',
      '.0...',
      '.000.',
      '.....',
      '.....'],
      ['.....',
       '..00.',
       '..0..'
       '..0..',
       '.....'],
     ['.....',
      '.....',
      '.000.',
      '...0.',
      '.....'],
      ['.....',
       '..0..',
       '..0..'
       '.00..',
       '.....']]
L = [['.....',
      '...0.',
      '.000.',
      '.....',
      '.....'],
     ['.....',
      '..0..',
      '..0..',
      '..00.',
      '.....'],
     ['.....',
      '.000.',
      '.0...',
      '.....',
      '.....'],
     ['.....',
      '.00..',
      '..0..',
      '..0..',
      '.....']]
T = [['.....',
      '..0..',
      '.000.',
      '.....',
      '.....'],
     ['.....',
      '..0..',
      '..00.',
      '..0..',
      '.....'],
     ['.....',
      '.....',
      '.000.',
      '..0..',
      '.....'],
     ['.....',
      '..0..',
      '.00..',
      '..0..',
      '.....']]

shapes = [S, Z, I, O, J, L, T]
shape_colors = [(0, 255, 0), (255, 0, 0), (0, 255, 255), (255, 255, 0), (255, 165, 0), (0, 0, 255), (120, 0, 120)]
#index 0- 6 represent shape

class Piece (object): #* 
    def __init__(self, x, y, shape):
        self.x = x
        self.y = y
        self.shape = shape
        self.color = shape_colors[shapes.index(shape)]
        self.rotation = 0
    

def create_grid(locked_pos = []): #*
    grid = [[(0, 0, 0) for _ in range(10)] for _ in range(20)]

    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if (j, i) in locked_pos:
                c =  locked_pos[(j, i)]
                grid[i][j] = c
    return grid

def convert_shape_format(shape): 
    positions = []
    format = shape.shape[shape.rotation % len(shape.shape)]

    for i, line in enumerate (format):
        row = list(line)
        for j, column in  enumerate(row):
            if column == '0':
                positions.append((shape.x  + j, shape.y + i))

    for i, pos in enumerate(positions):
        positions[i] = (pos[0] - 2, pos[1] - 4)

    return positions
        
def valid_space(shape, grid):
    accepted_pos = [[(j , i) for j in range(10) if grid[i][j] == (0, 0, 0)] for i in range(20)]
    accepted_pos = [j  for sub  in accepted_pos for j in sub]

    formatted = convert_shape_format(shape)

    for pos in formatted: 
        if pos  not in  accepted_pos:
            if  pos [l] > - 1:
                return False
    return True

def check_lost():
    for pos in positions:
        x, y = pos
        if y < 1:
            return True
    return False

def get_shape(): 
    return Piece(5, 0, random.choice(shapes))
    
def draw_text_middle(surface, text, size, color):
    font = pygame.font.SysFont('comicsans', size, bold=True)
    label = font.render(text, 1, color)

    surface.blit(label, (top_left_x + play_width/2 - (label.get_width/2, top_left_y + play_height/2 - label.get_height()/2)))

def draw_grid(surface, grid):

    sx =  top_left_x
    sy = top_left_y

    for i in range(len(grid)):
        pygame.draw.line(surface, (128, 128, 128), (sx, sy,  + i*block_size), (sx+play_width, sy+ i*block_size))
        for j in range(len(grid[i])):
            pygame.draw.line(surface, (128, 128, 128), (sx + j*block_size, sy), (sx+ j*block_size, sy + play_height))

    pygame.draw.rect(surface, (255, 0, 0), (top_left_x, top_let_y, play_width, play_height), 4)
    

    
def clear_rows():

    inc = 0
    for i in range(len(grid)-1, -1, -1):
        row = grid[i]
        if (0,0,0) not in row:
            inc += 1
            ind = 1
            for j in range (len(row)):
                try:
                    del locked[(j, i)]
                except:
                    continue
    

def draw_next_shape(shape, surface):
    font = pygame.font.SysFont('comicsans', 30)
    label = font.render('Next Shape',1, (255, 255, 255))

    sx = top_left_x + play_width + 50
    sy = top_left_y + play_height/2 - 100
    format = shape.shape[shape.rotation% len(shape.shape)]

    for i, line in enumerate(format):
        row = list(line)
        for j, column, in enumerate(row):
            if column == '0':
                pygame.draw.rect(surface, shape.color, (sx + j*10, sy + i*block_size, block_size), 0)
                
    surface.blit(label, (sx + 10, sy - 10))
                 
def draw_window(surface, grid): #*
    surface.fill((0, 0, 0))

    pygame.font.init()
    font = pygame.font.SysFont('comicsans', 60)
    label = font.render('Tetris', 1, (255, 255, 255))

    surface.blit(label, (top_left_x + play_width / 2 - (label.get.width() / 2), 30))

    font = pygame.font.SysFont('comicsans', 30)
    label = font.render('Score: ' + str(score), 1, (255, 255, 255))

    sx = top_left_x + play_width + 50
    sy = top_left_y + play_height/2 - 100

    surface.blit(label, (sx + 20, sy +160))
                        
    for i in range(len(grid)):
        pygame.draw.line(surface, (120, 120, 120), (sx, sy,  + i*block_size), (sx+play_width, sy+ i*block_size))
        for j in range(len(grid[i])):
            pygame.draw.line(surface, (120, 120, 120), (sx + j*block_size, sy), (sx+ j*block_size, sy + play_height))


    draw_grid(surface, grid)
    pygame.display.update()

    

def main(win): #*

    locked_positions = []
    grid = create_grid(locked_positions)

    change_piece = False
    run = True
    current_piece = get_shape()
    next_piece = get_shape()
    clock = pygame.time.Clock()
    fall_time = 0
    fall_speed = 0.27

    if fall_time/1000 > fall_speed:
        fall_time = 0
        current_piece.y += 1
        if not(valid_space(current_piece.grid) and current_piece.y > 0):
               current_piece.y -= 1
               change_piece = True
    while run:
        grid = create_grid(locked_positions)
        fall_time += clock.get_rawtime()
        clock.tick()

        if fall_time/1000 > fall_speed:
            fall_time = 0
            current_piece.y += 1
            if not(valid_space(current_piece, grid)) and current_piece.y > 0:
                current_piece.y -= 1
                change_piece = True
            
            
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
              run = False
             
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    current_piece.x -= 1
                    if not[valid_space(current_piece, grid)]:
                        current_piece += 1
                if event.key == pygame.K_RIGHT:
                    current_piece.x += 1
                    if not[valid_space(current_piece, grid)]:
                        current_piece.x -= 1
                if event.key == pygame.K_DOWN:
                    current_piece.y += 1
                    if not[valid_space(current_piece, grid)]:
                        current_piece.y -= 1
                if event.key == pygame.K_UP:
                    current_piece.rotation += 1
                    if not[valid_space(current_piece, grid)]:
                        current_piece.rotation -= 1

        draw_window(surface, grid)
             
        shape_pos = convert_shape_format(current_piece)

        for i in range(len(shape_pos)):
            x, y = shape_pos =[i]
            if y > -1:
                grid[y][x] = current_piece.color

        if change_piece:
            for pos in shape_pos:
                p = (pos[0], pos[1])
                locked_positions[p] = current_piece.color
            current_piece = next_piece
            next_piece = get_shape()
            change_piece = False

        draw_next_shape(next_piece, win)
        draw_window(win.grid)

        if check_lost(locked_positions):
           draw_text_middle(win, 'YOU LOST!', 80, (255, 255, 255))
           pygame.display.update()
           pygame.time.delay(1500)
           run = False
            
    pygame.display.quit()    
            
      
    
                 
def  main_menu(win): #*
    run = True
    while run:
        win.fill((0, 0, 0))
        draw_text_middle(win, 'Press Any Key To Play', 60, (255, 255, 255))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                main()

    pygame.display.quit()
    main(win)


win =  pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption('Tetris')
main_menu(win)
                 
                 
So, i have the following error message:

Traceback (most recent call last):
File "E:\Users\Usuario1\Documents\abscorp\Python\tetris.py", line 357, in <module>
main_menu(win)
File "E:\Users\Usuario1\Documents\abscorp\Python\tetris.py", line 343, in main_menu
draw_text_middle(win, 'Press Any Key To Play', 60, (255, 255, 255))
File "E:\Users\Usuario1\Documents\abscorp\Python\tetris.py", line 179, in draw_text_middle
surface.blit(label, (top_left_x + play_width/2 - (label.get_width/2, top_left_y + play_height/2 - label.get_height()/2)))
TypeError: unsupported operand type(s) for /: 'builtin_function_or_method' and 'int'
>>>

I hope someone can help

See u soon!
Reply
#2
you're missing parens after
label.get_width
on line 179; should be
label.get_width()
Reply
#3
New error message:

Traceback (most recent call last):
File "E:\Users\Usuario1\Documents\abscorp\Python\tetris.py", line 357, in <module>
main_menu(win)
File "E:\Users\Usuario1\Documents\abscorp\Python\tetris.py", line 343, in main_menu
draw_text_middle(win, 'Press Any Key To Play', 60, (255, 255, 255))
File "E:\Users\Usuario1\Documents\abscorp\Python\tetris.py", line 179, in draw_text_middle
surface.blit(label, (top_left_x + play_width/2 - (label.get_width()/2, top_left_y + play_height/2 - label.get_height()/2)))
TypeError: unsupported operand type(s) for -: 'float' and 'tuple'
>>>

I hope someone can help. See you soon!
Reply
#4
If a line is too complex to understand, then use more lines. Subtracting a tuple from a float doesn't make sense, so the solution isn't obvious.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tetris inteligence DanTDRG 5 1,509 Oct-05-2022, 08:30 AM
Last Post: DanTDRG
  Tetris 2 abscorpy 1 1,807 Dec-05-2019, 12:03 AM
Last Post: Windspar
  Tetris abscorpy 1 2,448 Nov-05-2019, 01:57 AM
Last Post: SheeppOSU
  Basically a Python Tetris game [pygame] rather keyboard arrows can be controlled with lsepolis123 9 5,005 Sep-10-2019, 08:12 PM
Last Post: metulburr
  Tetris - AttributeError: 'list' object has no attribute 'y' abscorpy 6 6,486 Feb-28-2019, 05:20 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020