最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

利用python制作俄羅斯方塊詳細(xì)圖文教程

 更新時(shí)間:2023年10月16日 08:37:28   作者:極客李華  
俄羅斯方塊是一款經(jīng)典的游戲,它可以用多種編程語言來實(shí)現(xiàn),這篇文章主要給大家介紹了關(guān)于利用python制作俄羅斯方塊的詳細(xì)圖文教程,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

簡介

俄羅斯方塊》(Tetris, 俄文:Тетрис)是一款由俄羅斯人阿列克謝·帕基特諾夫于1984年6月發(fā)明的休閑游戲。

該游戲曾經(jīng)被多家公司代理過。經(jīng)過多輪訴訟后,該游戲的代理權(quán)最終被任天堂獲得。 [1] 任天堂對于俄羅斯方塊來說意義重大,因?yàn)閷⑺cGB搭配在一起后,獲得了巨大的成功。 [1]

《俄羅斯方塊》的基本規(guī)則是移動(dòng)、旋轉(zhuǎn)和擺放游戲自動(dòng)輸出的各種方塊,使之排列成完整的一行或多行并且消除得分。

編碼

搭建基礎(chǔ)頁面

首先是創(chuàng)建一個(gè)python文件

創(chuàng)建一個(gè)窗體,用來顯示這個(gè)游戲的界面

代碼

import tkinter as tk
# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()
win.mainloop()

運(yùn)行結(jié)果

繪制格子

原理如下

畫格子,這里主要應(yīng)用的是tkinter里面Canvas功能。

代碼如下

import tkinter as tk

# 設(shè)置行數(shù)和列數(shù)
row = 20
col = 12

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = row * cell_size
width = col * cell_size

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 在畫板上繪制格子
def draw_cell(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

def draw_blank_board(canvas):
    for ri in range(row):
        for cj in range(col):
            draw_cell(canvas, cj, ri)


# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

draw_blank_board(canvas)

win.mainloop()

繪制俄羅斯方塊

現(xiàn)根據(jù)這個(gè)規(guī)則繪制一個(gè)看看情況

代碼講解

import tkinter as tk

# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue"
}

# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
draw_blank_board(canvas)

# 開始畫圖形了, 這里是先測試一下
draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])


win.mainloop()

運(yùn)行結(jié)果,通過運(yùn)行結(jié)果可以看出來沒有太大的問題

繪制其他的樣式的格子

這里是其他的格子的各種坐標(biāo),只需要往上面的代碼中的SHAPES和SHAPESCOLOR中放就可以了。

演示代碼

import tkinter as tk

# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)],
    "S":[(-1, 0),(0, 0),(0, -1),(1, -1)],
    "T":[(-1, 0),(0, 0),(0, -1),(1, 0)],
    "I":[(0, 1),(0, 0),(0, -1),(0, -2)],
    "L":[(-1, 0),(0, 0),(-1, -1),(-1, -2)],
    "J":[(-1, 0),(0, 0),(0, 1),(0, -2)],
    "Z":[(-1, -1),(0, -1),(0, 0),(1, 0)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue",
    "S":"red",
    "T":"yellow",
    "I":"green",
    "L":"purple",
    "J":"orange",
    "Z":"Cyan",
}

# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
draw_blank_board(canvas)

# 開始畫圖形了, 這里是先測試一下
draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])
draw_cells(canvas, 3, 8, SHAPES['S'], SHAPESCOLOR['S'])
draw_cells(canvas, 3, 13, SHAPES['T'], SHAPESCOLOR['T'])
draw_cells(canvas, 8, 3, SHAPES['I'], SHAPESCOLOR['I'])
draw_cells(canvas, 8, 8, SHAPES['L'], SHAPESCOLOR['L'])
draw_cells(canvas, 8, 13, SHAPES['J'], SHAPESCOLOR['J'])
draw_cells(canvas, 5, 18, SHAPES['Z'], SHAPESCOLOR['Z'])


win.mainloop()

運(yùn)行結(jié)果

通過測試這個(gè)各種的圖形格子是完成了的。

讓格子動(dòng)起來

讓這個(gè)格子使人感覺動(dòng)起來,主要的原理就是設(shè)置一個(gè)刷新時(shí)間,然后這個(gè)格子不斷的加載,然后不斷的刷新,這樣是利用的是game_loop(),draw_block_move(canvas, block, direction=[0,0])兩個(gè)函數(shù)。

代碼講解

import tkinter as tk
import time
# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)],
    "S":[(-1, 0),(0, 0),(0, -1),(1, -1)],
    "T":[(-1, 0),(0, 0),(0, -1),(1, 0)],
    "I":[(0, 1),(0, 0),(0, -1),(0, -2)],
    "L":[(-1, 0),(0, 0),(-1, -1),(-1, -2)],
    "J":[(-1, 0),(0, 0),(0, 1),(0, -2)],
    "Z":[(-1, -1),(0, -1),(0, 0),(1, 0)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue",
    "S":"red",
    "T":"yellow",
    "I":"green",
    "L":"purple",
    "J":"orange",
    "Z":"Cyan",
}

# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
draw_blank_board(canvas)

# 開始畫圖形了, 這里是先測試一下
# draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])
# draw_cells(canvas, 3, 8, SHAPES['S'], SHAPESCOLOR['S'])
# draw_cells(canvas, 3, 13, SHAPES['T'], SHAPESCOLOR['T'])
# draw_cells(canvas, 8, 3, SHAPES['I'], SHAPESCOLOR['I'])
# draw_cells(canvas, 8, 8, SHAPES['L'], SHAPESCOLOR['L'])
# draw_cells(canvas, 8, 13, SHAPES['J'], SHAPESCOLOR['J'])
# draw_cells(canvas, 5, 18, SHAPES['Z'], SHAPESCOLOR['Z'])

# 設(shè)置格子的刷新頻率,單位是毫秒
FPS = 500

# 定義讓俄羅斯方塊移動(dòng)的方法
def draw_block_move(canvas, block, direction=[0,0]):
    """
    :param canvas: 面板對象
    :param block: 俄羅斯方塊
    :param direction: 移動(dòng)的方向
    :return:
    """
    shape_type = block['kind']
    c, r = block['cr']
    cell_list = block['cell_list']

    draw_cells(canvas, c, r, cell_list)

    dc, dr = direction
    new_c, new_r = c + dc, r + dr
    block['cr'] = [new_c, new_r]
    draw_cells(canvas, new_c, new_r, cell_list, SHAPESCOLOR[shape_type])

# 用字典定義每個(gè)形狀的屬性
one_block = {
    'kind': 'O', # 對應(yīng)俄羅斯方塊的類型
    'cell_list': SHAPES['O'], # 對應(yīng)的每個(gè)俄羅斯方塊的坐標(biāo)
    'cr': [3, 3], # 對應(yīng)的行列坐標(biāo)
}

draw_block_move(canvas, one_block)
# 讓游戲不斷循環(huán) 通過遞歸實(shí)現(xiàn)
def game_loop():
    win.update()

    # 往下走
    down = [0, 1]
    draw_block_move(canvas, one_block, down)
    win.after(FPS, game_loop) # 注意的是這個(gè)game_loop后面不能加括號

game_loop()
win.mainloop()

運(yùn)行結(jié)果

這里生成了一個(gè),往下掉的小俄羅斯方塊。

生成,固定,變換,移動(dòng) 生成和固定

演示代碼

import tkinter as tk
import time
# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)],
    "S":[(-1, 0),(0, 0),(0, -1),(1, -1)],
    "T":[(-1, 0),(0, 0),(0, -1),(1, 0)],
    "I":[(0, 1),(0, 0),(0, -1),(0, -2)],
    "L":[(-1, 0),(0, 0),(-1, -1),(-1, -2)],
    "J":[(-1, 0),(0, 0),(0, 1),(0, -2)],
    "Z":[(-1, -1),(0, -1),(0, 0),(1, 0)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue",
    "S":"red",
    "T":"yellow",
    "I":"green",
    "L":"purple",
    "J":"orange",
    "Z":"Cyan",
}

# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
draw_blank_board(canvas)

# 開始畫圖形了, 這里是先測試一下
# draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])
# draw_cells(canvas, 3, 8, SHAPES['S'], SHAPESCOLOR['S'])
# draw_cells(canvas, 3, 13, SHAPES['T'], SHAPESCOLOR['T'])
# draw_cells(canvas, 8, 3, SHAPES['I'], SHAPESCOLOR['I'])
# draw_cells(canvas, 8, 8, SHAPES['L'], SHAPESCOLOR['L'])
# draw_cells(canvas, 8, 13, SHAPES['J'], SHAPESCOLOR['J'])
# draw_cells(canvas, 5, 18, SHAPES['Z'], SHAPESCOLOR['Z'])

# 設(shè)置格子的刷新頻率,單位是毫秒
FPS = 500

# 定義讓俄羅斯方塊移動(dòng)的方法
def draw_block_move(canvas, block, direction=[0,0]):
    """
    :param canvas: 面板對象
    :param block: 俄羅斯方塊
    :param direction: 移動(dòng)的方向
    :return:
    """
    shape_type = block['kind']
    c, r = block['cr']
    cell_list = block['cell_list']

    draw_cells(canvas, c, r, cell_list)

    dc, dr = direction
    new_c, new_r = c + dc, r + dr
    block['cr'] = [new_c, new_r]
    draw_cells(canvas, new_c, new_r, cell_list, SHAPESCOLOR[shape_type])

# 用字典定義每個(gè)形狀的屬性
one_block = {
    'kind': 'O', # 對應(yīng)俄羅斯方塊的類型
    'cell_list': SHAPES['O'], # 對應(yīng)的每個(gè)俄羅斯方塊的坐標(biāo)
    'cr': [3, 3], # 對應(yīng)的行列坐標(biāo)
}

draw_block_move(canvas, one_block)
# 讓游戲不斷循環(huán) 通過遞歸實(shí)現(xiàn)
def game_loop():
    win.update()

    # 往下走
    down = [0, 1]
    draw_block_move(canvas, one_block, down)
    win.after(FPS, game_loop) # 注意的是這個(gè)game_loop后面不能加括號

game_loop()
win.mainloop()

在這這里我們實(shí)現(xiàn)了這個(gè)俄羅斯方塊的不斷的生成,和俄羅斯方塊的不斷的疊加,基本實(shí)現(xiàn)了俄羅斯方塊的生產(chǎn)功能。

運(yùn)行結(jié)果

移動(dòng)

運(yùn)行結(jié)果

這個(gè)效果就是可以左右移動(dòng),具體代碼看下面,主要依靠的是horizontal_move_block(event)這個(gè)函數(shù)的實(shí)現(xiàn)。

完整代碼

import tkinter as tk
import random

# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置格子的刷新頻率,單位是毫秒
FPS = 50

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "Z": [(-1, -1), (0, -1), (0, 0), (1, 0)],
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)],
    "S": [(-1, 0), (0, 0), (0, -1), (1, -1)],
    "T": [(-1, 0), (0, 0), (0, -1), (1, 0)],
    "I": [(0, 1), (0, 0), (0, -1), (0, -2)],
    "L": [(-1, 0), (0, 0), (-1, -1), (-1, -2)],
    "J": [(-1, 0), (0, 0), (0, -1), (0, -2)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue",
    "S":"red",
    "T":"yellow",
    "I":"green",
    "L":"purple",
    "J":"orange",
    "Z":"Cyan",
}

# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

# 繪制板塊
def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

# 繪制單元格
def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
draw_blank_board(canvas)

block_list = []
for i in range(Row):
    i_row = ['' for j in range(Col)]
    block_list.append(i_row)


# 開始畫圖形了, 這里是先測試一下
# draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])
# draw_cells(canvas, 3, 8, SHAPES['S'], SHAPESCOLOR['S'])
# draw_cells(canvas, 3, 13, SHAPES['T'], SHAPESCOLOR['T'])
# draw_cells(canvas, 8, 3, SHAPES['I'], SHAPESCOLOR['I'])
# draw_cells(canvas, 8, 8, SHAPES['L'], SHAPESCOLOR['L'])
# draw_cells(canvas, 8, 13, SHAPES['J'], SHAPESCOLOR['J'])
# draw_cells(canvas, 5, 18, SHAPES['Z'], SHAPESCOLOR['Z'])


# 定義讓俄羅斯方塊移動(dòng)的方法
def draw_block_move(canvas, block, direction=[0,0]):
    """
    :param canvas: 面板對象
    :param block: 俄羅斯方塊
    :param direction: 移動(dòng)的方向
    :return:
    """
    shape_type = block['kind']
    c, r = block['cr']
    cell_list = block['cell_list']

    draw_cells(canvas, c, r, cell_list)

    dc, dr = direction
    new_c, new_r = c + dc, r + dr
    block['cr'] = [new_c, new_r]
    draw_cells(canvas, new_c, new_r, cell_list, SHAPESCOLOR[shape_type])

# 用字典定義每個(gè)形狀的屬性
one_block = {
    'kind': 'O', # 對應(yīng)俄羅斯方塊的類型
    'cell_list': SHAPES['O'], # 對應(yīng)的每個(gè)俄羅斯方塊的坐標(biāo)
    'cr': [3, 3], # 對應(yīng)的行列坐標(biāo)
}

# 測試代碼
# draw_block_move(canvas, one_block)

def product_new_block():
    # 隨機(jī)生成新的俄羅斯方塊
    kind = random.choice(list(SHAPES.keys()))

    cr = [Col // 2, 0]
    new_block = {
        "kind": kind,
        "cell_list": SHAPES[kind],
        'cr': cr
    }
    return new_block

def check_move(block, direction=[0,0]):
    """
    :param block:俄羅斯方塊的前身
    :param direction: 移動(dòng)方向
    :return: boolean 是否可以朝著指定的方向移動(dòng)
    """
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc + direction[0]
        r = cell_r + cr + direction[1]

        # 判斷邊界
        if c < 0 or c >= Col or r >= Row:
            return False
        # r >= 0是防止格子下不來的情況
        if r >= 0 and block_list[r][c]:
            return False
    return True

# 保存當(dāng)前的俄羅斯方塊到列表里面
def save_to_block_list(block):
    shape_type = block['kind']
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc
        r = cell_r + cr

        block_list[r][c] = shape_type


def horizontal_move_block(event):
    """
    左右水平移動(dòng)俄羅斯方塊
    event:鍵盤的監(jiān)聽事件
    """
    # 這里只設(shè)置了左右兩個(gè)方向
    direction = [0, 0]
    if event.keysym == 'Left':
        direction = [-1, 0]
    elif event.keysym == 'Right':
        direction = [1, 0]
    else:
        return

    global current_block
    if current_block is not None and check_move(current_block, direction):
        draw_block_move(canvas, current_block, direction)


# 讓游戲不斷循環(huán) 通過遞歸實(shí)現(xiàn)
def game_loop():
    win.update()

    global current_block
    # 如果當(dāng)前沒有俄羅斯方塊 產(chǎn)生一個(gè)新的
    if current_block is None:
        # 生成新的俄羅斯方塊
        new_block = product_new_block()
        draw_block_move(canvas, new_block)
        current_block = new_block
    # 如果當(dāng)前有了就往下走
    else:
        if check_move(current_block, [0, 1]):
            draw_block_move(canvas, current_block, [0, 1])
        else:
            # 保存當(dāng)前的俄羅斯方塊
            save_to_block_list(current_block)
            current_block = None
    win.after(FPS, game_loop) # 注意的是這個(gè)game_loop后面不能加括號

# 當(dāng)前的俄羅斯方塊
current_block = None

# 畫布聚焦
canvas.focus_set()
# 添加左右移動(dòng)的事件
canvas.bind("<KeyPress-Left>", horizontal_move_block)
canvas.bind("<KeyPress-Right>", horizontal_move_block)


game_loop()
win.mainloop()

變換

這個(gè)是讓這個(gè)俄羅斯方塊的角度可以發(fā)生變換,主要的是利用這個(gè)函數(shù),這個(gè)rotate_block是角度的旋轉(zhuǎn),這個(gè)land是馬上下去的功能。

def rotate_block(event):
    global current_block
    if current_block is None:
        return
 
    cell_list = current_block['cell_list']
    rotate_list = []
    for cell in cell_list:
        cell_c, cell_r = cell
        rotate_cell = [cell_r, -cell_c]
        rotate_list.append(rotate_cell)
 
    block_after_rotate = {
        'kind': current_block['kind'],  # 對應(yīng)俄羅斯方塊的類型
        'cell_list': rotate_list,
        'cr': current_block['cr']
    }
 
    if check_move(block_after_rotate):
        cc, cr= current_block['cr']
        draw_cells(canvas, cc, cr, current_block['cell_list'])
        draw_cells(canvas, cc, cr, rotate_list,SHAPESCOLOR[current_block['kind']])
        current_block = block_after_rotate
 
 
def land(event):
    global current_block
    if current_block is None:
        return
 
    cell_list = current_block['cell_list']
    cc, cr = current_block['cr']
    min_height = R
    for cell in cell_list:
        cell_c, cell_r = cell
        c, r = cell_c + cc, cell_r + cr
        if block_list[r][c]:
            return
        h = 0
        for ri in range(r+1, R):
            if block_list[ri][c]:
                break
            else:
                h += 1
        if h < min_height:
            min_height = h
 
    down = [0, min_height]
    if check_move(current_block, down):
        draw_block_move(canvas, current_block, down)

完整的代碼

import tkinter as tk
import random

# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置格子的刷新頻率,單位是毫秒
FPS = 250

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "Z": [(-1, -1), (0, -1), (0, 0), (1, 0)],
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)],
    "S": [(-1, 0), (0, 0), (0, -1), (1, -1)],
    "T": [(-1, 0), (0, 0), (0, -1), (1, 0)],
    "I": [(0, 1), (0, 0), (0, -1), (0, -2)],
    "L": [(-1, 0), (0, 0), (-1, -1), (-1, -2)],
    "J": [(-1, 0), (0, 0), (0, -1), (0, -2)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue",
    "S":"red",
    "T":"yellow",
    "I":"green",
    "L":"purple",
    "J":"orange",
    "Z":"Cyan",
}

# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

# 繪制板塊
def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

# 繪制單元格
def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
draw_blank_board(canvas)

block_list = []
for i in range(Row):
    i_row = ['' for j in range(Col)]
    block_list.append(i_row)


# 開始畫圖形了, 這里是先測試一下
# draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])
# draw_cells(canvas, 3, 8, SHAPES['S'], SHAPESCOLOR['S'])
# draw_cells(canvas, 3, 13, SHAPES['T'], SHAPESCOLOR['T'])
# draw_cells(canvas, 8, 3, SHAPES['I'], SHAPESCOLOR['I'])
# draw_cells(canvas, 8, 8, SHAPES['L'], SHAPESCOLOR['L'])
# draw_cells(canvas, 8, 13, SHAPES['J'], SHAPESCOLOR['J'])
# draw_cells(canvas, 5, 18, SHAPES['Z'], SHAPESCOLOR['Z'])


# 定義讓俄羅斯方塊移動(dòng)的方法
def draw_block_move(canvas, block, direction=[0,0]):
    """
    :param canvas: 面板對象
    :param block: 俄羅斯方塊
    :param direction: 移動(dòng)的方向
    :return:
    """
    shape_type = block['kind']
    c, r = block['cr']
    cell_list = block['cell_list']

    draw_cells(canvas, c, r, cell_list)

    dc, dr = direction
    new_c, new_r = c + dc, r + dr
    block['cr'] = [new_c, new_r]
    draw_cells(canvas, new_c, new_r, cell_list, SHAPESCOLOR[shape_type])

# 用字典定義每個(gè)形狀的屬性
one_block = {
    'kind': 'O', # 對應(yīng)俄羅斯方塊的類型
    'cell_list': SHAPES['O'], # 對應(yīng)的每個(gè)俄羅斯方塊的坐標(biāo)
    'cr': [3, 3], # 對應(yīng)的行列坐標(biāo)
}

# 測試代碼
# draw_block_move(canvas, one_block)

def product_new_block():
    # 隨機(jī)生成新的俄羅斯方塊
    kind = random.choice(list(SHAPES.keys()))

    cr = [Col // 2, 0]
    new_block = {
        "kind": kind,
        "cell_list": SHAPES[kind],
        'cr': cr
    }
    return new_block

def check_move(block, direction=[0,0]):
    """
    :param block:俄羅斯方塊的前身
    :param direction: 移動(dòng)方向
    :return: boolean 是否可以朝著指定的方向移動(dòng)
    """
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc + direction[0]
        r = cell_r + cr + direction[1]

        # 判斷邊界
        if c < 0 or c >= Col or r >= Row:
            return False
        # r >= 0是防止格子下不來的情況
        if r >= 0 and block_list[r][c]:
            return False
    return True

# 保存當(dāng)前的俄羅斯方塊到列表里面
def save_to_block_list(block):
    shape_type = block['kind']
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc
        r = cell_r + cr

        block_list[r][c] = shape_type


def horizontal_move_block(event):
    """
    左右水平移動(dòng)俄羅斯方塊
    event:鍵盤的監(jiān)聽事件
    """
    # 這里只設(shè)置了左右兩個(gè)方向
    direction = [0, 0]
    if event.keysym == 'Left':
        direction = [-1, 0]
    elif event.keysym == 'Right':
        direction = [1, 0]
    else:
        return

    global current_block
    if current_block is not None and check_move(current_block, direction):
        draw_block_move(canvas, current_block, direction)


def rotate_block(event):
    global current_block
    if current_block is None:
        return

    cell_list = current_block['cell_list']
    rotate_list = []
    for cell in cell_list:
        cell_c, cell_r = cell
        rotate_cell = [cell_r, -cell_c]
        rotate_list.append(rotate_cell)

    block_after_rotate = {
        'kind': current_block['kind'],  # 對應(yīng)俄羅斯方塊的類型
        'cell_list': rotate_list,
        'cr': current_block['cr']
    }

    if check_move(block_after_rotate):
        cc, cr = current_block['cr']
        draw_cells(canvas, cc, cr, current_block['cell_list'])
        draw_cells(canvas, cc, cr, rotate_list, SHAPESCOLOR[current_block['kind']])
        current_block = block_after_rotate


def land(event):
    global current_block
    if current_block is None:
        return

    cell_list = current_block['cell_list']
    cc, cr = current_block['cr']
    min_height = Row
    for cell in cell_list:
        cell_c, cell_r = cell
        c, r = cell_c + cc, cell_r + cr
        if block_list[r][c]:
            return
        h = 0
        for ri in range(r + 1, Row):
            if block_list[ri][c]:
                break
            else:
                h += 1
        if h < min_height:
            min_height = h

    down = [0, min_height]
    if check_move(current_block, down):
        draw_block_move(canvas, current_block, down)


# 讓游戲不斷循環(huán) 通過遞歸實(shí)現(xiàn)
def game_loop():
    win.update()

    global current_block
    # 如果當(dāng)前沒有俄羅斯方塊 產(chǎn)生一個(gè)新的
    if current_block is None:
        # 生成新的俄羅斯方塊
        new_block = product_new_block()
        draw_block_move(canvas, new_block)
        current_block = new_block
    # 如果當(dāng)前有了就往下走
    else:
        if check_move(current_block, [0, 1]):
            draw_block_move(canvas, current_block, [0, 1])
        else:
            # 保存當(dāng)前的俄羅斯方塊
            save_to_block_list(current_block)
            current_block = None
    win.after(FPS, game_loop) # 注意的是這個(gè)game_loop后面不能加括號

# 當(dāng)前的俄羅斯方塊
current_block = None

# 畫布聚焦
canvas.focus_set()
# 添加左右移動(dòng)的事件
canvas.bind("<KeyPress-Left>", horizontal_move_block)
canvas.bind("<KeyPress-Right>", horizontal_move_block)
# 添加變化角度的事件
canvas.bind("<KeyPress-Up>", rotate_block)
canvas.bind("<KeyPress-Down>", land)


game_loop()
win.mainloop()

運(yùn)行結(jié)果

現(xiàn)在這個(gè)俄羅斯方塊可以上下角度變化了。

清除與得分

在這版本中,實(shí)現(xiàn)了清除與得分的功能,每次清除這個(gè)俄羅斯方塊,都可以+10的獎(jiǎng)勵(lì),最后當(dāng)不可以繼續(xù)下去了,這個(gè)游戲就結(jié)束了,然后就退出了。

import tkinter as tk
from tkinter import messagebox
import random

# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置格子的刷新頻率,單位是毫秒
FPS = 150

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "Z": [(-1, -1), (0, -1), (0, 0), (1, 0)],
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)],
    "S": [(-1, 0), (0, 0), (0, -1), (1, -1)],
    "T": [(-1, 0), (0, 0), (0, -1), (1, 0)],
    "I": [(0, 1), (0, 0), (0, -1), (0, -2)],
    "L": [(-1, 0), (0, 0), (-1, -1), (-1, -2)],
    "J": [(-1, 0), (0, 0), (0, -1), (0, -2)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue",
    "S":"red",
    "T":"yellow",
    "I":"green",
    "L":"purple",
    "J":"orange",
    "Z":"Cyan",
}
# 繪制面板,將draw_blank_board方法修改成如下方法
def draw_board(canvas, block_list):
    for ri in range(Row):
        for ci in range(Col):
            cell_type = block_list[ri][ci]
            if cell_type:
                draw_cell_background(canvas, ci, ri, SHAPESCOLOR[cell_type])
            else:
                draw_cell_background(canvas, ci, ri)
# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

# 繪制板塊
def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

# 繪制單元格
def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
block_list = []
for i in range(Row):
    i_row = ['' for j in range(Col)]
    block_list.append(i_row)

draw_board(canvas, block_list)


# 開始畫圖形了, 這里是先測試一下
# draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])
# draw_cells(canvas, 3, 8, SHAPES['S'], SHAPESCOLOR['S'])
# draw_cells(canvas, 3, 13, SHAPES['T'], SHAPESCOLOR['T'])
# draw_cells(canvas, 8, 3, SHAPES['I'], SHAPESCOLOR['I'])
# draw_cells(canvas, 8, 8, SHAPES['L'], SHAPESCOLOR['L'])
# draw_cells(canvas, 8, 13, SHAPES['J'], SHAPESCOLOR['J'])
# draw_cells(canvas, 5, 18, SHAPES['Z'], SHAPESCOLOR['Z'])


# 定義讓俄羅斯方塊移動(dòng)的方法
def draw_block_move(canvas, block, direction=[0,0]):
    """
    :param canvas: 面板對象
    :param block: 俄羅斯方塊
    :param direction: 移動(dòng)的方向
    :return:
    """
    shape_type = block['kind']
    c, r = block['cr']
    cell_list = block['cell_list']

    draw_cells(canvas, c, r, cell_list)

    dc, dr = direction
    new_c, new_r = c + dc, r + dr
    block['cr'] = [new_c, new_r]
    draw_cells(canvas, new_c, new_r, cell_list, SHAPESCOLOR[shape_type])

# 用字典定義每個(gè)形狀的屬性
one_block = {
    'kind': 'O', # 對應(yīng)俄羅斯方塊的類型
    'cell_list': SHAPES['O'], # 對應(yīng)的每個(gè)俄羅斯方塊的坐標(biāo)
    'cr': [3, 3], # 對應(yīng)的行列坐標(biāo)
}

# 測試代碼
# draw_block_move(canvas, one_block)

def product_new_block():
    # 隨機(jī)生成新的俄羅斯方塊
    kind = random.choice(list(SHAPES.keys()))

    cr = [Col // 2, 0]
    new_block = {
        "kind": kind,
        "cell_list": SHAPES[kind],
        'cr': cr
    }
    return new_block

def check_move(block, direction=[0,0]):
    """
    :param block:俄羅斯方塊的前身
    :param direction: 移動(dòng)方向
    :return: boolean 是否可以朝著指定的方向移動(dòng)
    """
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc + direction[0]
        r = cell_r + cr + direction[1]

        # 判斷邊界
        if c < 0 or c >= Col or r >= Row:
            return False
        # r >= 0是防止格子下不來的情況
        if r >= 0 and block_list[r][c]:
            return False
    return True

# 保存當(dāng)前的俄羅斯方塊到列表里面
def save_to_block_list(block):
    shape_type = block['kind']
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc
        r = cell_r + cr

        block_list[r][c] = shape_type


def horizontal_move_block(event):
    """
    左右水平移動(dòng)俄羅斯方塊
    event:鍵盤的監(jiān)聽事件
    """
    # 這里只設(shè)置了左右兩個(gè)方向
    direction = [0, 0]
    if event.keysym == 'Left':
        direction = [-1, 0]
    elif event.keysym == 'Right':
        direction = [1, 0]
    else:
        return

    global current_block
    if current_block is not None and check_move(current_block, direction):
        draw_block_move(canvas, current_block, direction)


def rotate_block(event):
    global current_block
    if current_block is None:
        return

    cell_list = current_block['cell_list']
    rotate_list = []
    for cell in cell_list:
        cell_c, cell_r = cell
        rotate_cell = [cell_r, -cell_c]
        rotate_list.append(rotate_cell)

    block_after_rotate = {
        'kind': current_block['kind'],  # 對應(yīng)俄羅斯方塊的類型
        'cell_list': rotate_list,
        'cr': current_block['cr']
    }

    if check_move(block_after_rotate):
        cc, cr = current_block['cr']
        draw_cells(canvas, cc, cr, current_block['cell_list'])
        draw_cells(canvas, cc, cr, rotate_list, SHAPESCOLOR[current_block['kind']])
        current_block = block_after_rotate


def land(event):
    global current_block
    if current_block is None:
        return

    cell_list = current_block['cell_list']
    cc, cr = current_block['cr']
    min_height = Row
    for cell in cell_list:
        cell_c, cell_r = cell
        c, r = cell_c + cc, cell_r + cr
        if block_list[r][c]:
            return
        h = 0
        for ri in range(r + 1, Row):
            if block_list[ri][c]:
                break
            else:
                h += 1
        if h < min_height:
            min_height = h

    down = [0, min_height]
    if check_move(current_block, down):
        draw_block_move(canvas, current_block, down)



# 在原有的rotate_block方法(外)下面添加
def check_row_complete(row):
    for cell in row:
        if cell == '':
            return False

    return True


score = 0
win.title("SCORES: %s" % score)  # 標(biāo)題中展示分?jǐn)?shù)


def check_and_clear():
    has_complete_row = False
    for ri in range(len(block_list)):
        if check_row_complete(block_list[ri]):
            has_complete_row = True
            # 當(dāng)前行可消除
            if ri > 0:
                for cur_ri in range(ri, 0, -1):
                    block_list[cur_ri] = block_list[cur_ri - 1][:]
                block_list[0] = ['' for j in range(Col)]
            else:
                block_list[ri] = ['' for j in range(Col)]
            global score
            # 每消除一次 加10分
            score += 10


    if has_complete_row:
        draw_board(canvas, block_list)
        # 重新繪制
        win.title("SCORES: %s" % score)


# 讓游戲不斷循環(huán) 通過遞歸實(shí)現(xiàn)
def game_loop():
    win.update()

    global current_block
    # 如果當(dāng)前沒有俄羅斯方塊 產(chǎn)生一個(gè)新的
    if current_block is None:
        # 生成新的俄羅斯方塊
        new_block = product_new_block()
        draw_block_move(canvas, new_block)
        current_block = new_block

        # 游戲結(jié)束
        if not check_move(current_block, [0, 0]):
            messagebox.showinfo("Game Over!", "Your Score is %s" % score)
            win.destroy()
            return

    # 如果當(dāng)前有了就往下走
    else:
        if check_move(current_block, [0, 1]):
            draw_block_move(canvas, current_block, [0, 1])
        else:
            # 保存當(dāng)前的俄羅斯方塊
            save_to_block_list(current_block)
            current_block = None
    # 游戲結(jié)束
    check_and_clear()
    win.after(FPS, game_loop) # 注意的是這個(gè)game_loop后面不能加括號

# 當(dāng)前的俄羅斯方塊
current_block = None

# 畫布聚焦
canvas.focus_set()
# 添加左右移動(dòng)的事件
canvas.bind("<KeyPress-Left>", horizontal_move_block)
canvas.bind("<KeyPress-Right>", horizontal_move_block)
# 添加變化角度的事件
canvas.bind("<KeyPress-Up>", rotate_block)
canvas.bind("<KeyPress-Down>", land)


game_loop()
win.mainloop()

運(yùn)行結(jié)果

這個(gè)是游戲最后的樣子,其實(shí)可以后面再加一個(gè)數(shù)據(jù)庫的功能,記錄每一次的得分結(jié)果。

完整代碼

import tkinter as tk
from tkinter import messagebox
import random

# 設(shè)置行數(shù)和列數(shù)
Row = 20
Col = 12

# 設(shè)置格子的刷新頻率,單位是毫秒
FPS = 150

# 設(shè)置每個(gè)格子的大小
cell_size = 30

# 設(shè)置窗口的高和寬
height = Row * cell_size
width = Col * cell_size

# 設(shè)置不同形狀的格子
SHAPES = {
    "Z": [(-1, -1), (0, -1), (0, 0), (1, 0)],
    "O": [(-1, -1), (0, -1), (-1, 0), (0, 0)],
    "S": [(-1, 0), (0, 0), (0, -1), (1, -1)],
    "T": [(-1, 0), (0, 0), (0, -1), (1, 0)],
    "I": [(0, 1), (0, 0), (0, -1), (0, -2)],
    "L": [(-1, 0), (0, 0), (-1, -1), (-1, -2)],
    "J": [(-1, 0), (0, 0), (0, -1), (0, -2)]
}

# 設(shè)置格子的顏色
SHAPESCOLOR = {
    "O":"blue",
    "S":"red",
    "T":"yellow",
    "I":"green",
    "L":"purple",
    "J":"orange",
    "Z":"Cyan",
}
# 繪制面板,將draw_blank_board方法修改成如下方法
def draw_board(canvas, block_list):
    for ri in range(Row):
        for ci in range(Col):
            cell_type = block_list[ri][ci]
            if cell_type:
                draw_cell_background(canvas, ci, ri, SHAPESCOLOR[cell_type])
            else:
                draw_cell_background(canvas, ci, ri)
# 在畫板上繪制格子
def draw_cell_background(canvas, col, row, color="#CCCCCC"):
    x0 = col * cell_size
    y0 = row * cell_size

    x1 = col * cell_size + cell_size
    y1 = row * cell_size + cell_size

    # 創(chuàng)建矩形
    canvas.create_rectangle(x0, y0, x1, y1, fill=color, outline="white", width=2)

# 繪制板塊
def draw_blank_board(canvas):
    for ri in range(Row):
        for cj in range(Col):
            draw_cell_background(canvas, cj, ri)

# 繪制單元格
def draw_cells(canvas, col, row, cell_list, color="#CCCCCC"):
    """
    :param canvas: 畫板對象
    :param col: 這個(gè)形狀的的原點(diǎn)所在的列
    :param row: 這個(gè)形狀所的原點(diǎn)所在的行
    :param cell_list: 這個(gè)形狀各個(gè)格子相對于自身的原點(diǎn)所處的位置坐標(biāo)
    :param color: 這個(gè)形狀的顏色
    :return:
    """
    for cell in cell_list:
        cell_col, cell_row = cell
        ci = cell_col + col
        ri = cell_row + row
        # 判斷是否越界
        if 0 <= col < Col and 0 <= row < Row:
            draw_cell_background(canvas, ci, ri, color)

# 首先創(chuàng)建一個(gè)窗體
win = tk.Tk()

# 繪制畫布的長寬
canvas = tk.Canvas(win, width=width, height=height)

# 打包放置組件對象
canvas.pack()

# 畫背景
block_list = []
for i in range(Row):
    i_row = ['' for j in range(Col)]
    block_list.append(i_row)

draw_board(canvas, block_list)


# 開始畫圖形了, 這里是先測試一下
# draw_cells(canvas, 3, 3, SHAPES['O'], SHAPESCOLOR['O'])
# draw_cells(canvas, 3, 8, SHAPES['S'], SHAPESCOLOR['S'])
# draw_cells(canvas, 3, 13, SHAPES['T'], SHAPESCOLOR['T'])
# draw_cells(canvas, 8, 3, SHAPES['I'], SHAPESCOLOR['I'])
# draw_cells(canvas, 8, 8, SHAPES['L'], SHAPESCOLOR['L'])
# draw_cells(canvas, 8, 13, SHAPES['J'], SHAPESCOLOR['J'])
# draw_cells(canvas, 5, 18, SHAPES['Z'], SHAPESCOLOR['Z'])


# 定義讓俄羅斯方塊移動(dòng)的方法
def draw_block_move(canvas, block, direction=[0,0]):
    """
    :param canvas: 面板對象
    :param block: 俄羅斯方塊
    :param direction: 移動(dòng)的方向
    :return:
    """
    shape_type = block['kind']
    c, r = block['cr']
    cell_list = block['cell_list']

    draw_cells(canvas, c, r, cell_list)

    dc, dr = direction
    new_c, new_r = c + dc, r + dr
    block['cr'] = [new_c, new_r]
    draw_cells(canvas, new_c, new_r, cell_list, SHAPESCOLOR[shape_type])

# 用字典定義每個(gè)形狀的屬性
one_block = {
    'kind': 'O', # 對應(yīng)俄羅斯方塊的類型
    'cell_list': SHAPES['O'], # 對應(yīng)的每個(gè)俄羅斯方塊的坐標(biāo)
    'cr': [3, 3], # 對應(yīng)的行列坐標(biāo)
}

# 測試代碼
# draw_block_move(canvas, one_block)

def product_new_block():
    # 隨機(jī)生成新的俄羅斯方塊
    kind = random.choice(list(SHAPES.keys()))

    cr = [Col // 2, 0]
    new_block = {
        "kind": kind,
        "cell_list": SHAPES[kind],
        'cr': cr
    }
    return new_block

def check_move(block, direction=[0,0]):
    """
    :param block:俄羅斯方塊的前身
    :param direction: 移動(dòng)方向
    :return: boolean 是否可以朝著指定的方向移動(dòng)
    """
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc + direction[0]
        r = cell_r + cr + direction[1]

        # 判斷邊界
        if c < 0 or c >= Col or r >= Row:
            return False
        # r >= 0是防止格子下不來的情況
        if r >= 0 and block_list[r][c]:
            return False
    return True

# 保存當(dāng)前的俄羅斯方塊到列表里面
def save_to_block_list(block):
    shape_type = block['kind']
    cc, cr = block['cr']
    cell_list = block['cell_list']

    for cell in cell_list:
        cell_c, cell_r = cell
        c = cell_c + cc
        r = cell_r + cr

        block_list[r][c] = shape_type


def horizontal_move_block(event):
    """
    左右水平移動(dòng)俄羅斯方塊
    event:鍵盤的監(jiān)聽事件
    """
    # 這里只設(shè)置了左右兩個(gè)方向
    direction = [0, 0]
    if event.keysym == 'Left':
        direction = [-1, 0]
    elif event.keysym == 'Right':
        direction = [1, 0]
    else:
        return

    global current_block
    if current_block is not None and check_move(current_block, direction):
        draw_block_move(canvas, current_block, direction)


def rotate_block(event):
    global current_block
    if current_block is None:
        return

    cell_list = current_block['cell_list']
    rotate_list = []
    for cell in cell_list:
        cell_c, cell_r = cell
        rotate_cell = [cell_r, -cell_c]
        rotate_list.append(rotate_cell)

    block_after_rotate = {
        'kind': current_block['kind'],  # 對應(yīng)俄羅斯方塊的類型
        'cell_list': rotate_list,
        'cr': current_block['cr']
    }

    if check_move(block_after_rotate):
        cc, cr = current_block['cr']
        draw_cells(canvas, cc, cr, current_block['cell_list'])
        draw_cells(canvas, cc, cr, rotate_list, SHAPESCOLOR[current_block['kind']])
        current_block = block_after_rotate


def land(event):
    global current_block
    if current_block is None:
        return

    cell_list = current_block['cell_list']
    cc, cr = current_block['cr']
    min_height = Row
    for cell in cell_list:
        cell_c, cell_r = cell
        c, r = cell_c + cc, cell_r + cr
        if block_list[r][c]:
            return
        h = 0
        for ri in range(r + 1, Row):
            if block_list[ri][c]:
                break
            else:
                h += 1
        if h < min_height:
            min_height = h

    down = [0, min_height]
    if check_move(current_block, down):
        draw_block_move(canvas, current_block, down)



# 在原有的rotate_block方法(外)下面添加
def check_row_complete(row):
    for cell in row:
        if cell == '':
            return False

    return True


score = 0
win.title("SCORES: %s" % score)  # 標(biāo)題中展示分?jǐn)?shù)


def check_and_clear():
    has_complete_row = False
    for ri in range(len(block_list)):
        if check_row_complete(block_list[ri]):
            has_complete_row = True
            # 當(dāng)前行可消除
            if ri > 0:
                for cur_ri in range(ri, 0, -1):
                    block_list[cur_ri] = block_list[cur_ri - 1][:]
                block_list[0] = ['' for j in range(Col)]
            else:
                block_list[ri] = ['' for j in range(Col)]
            global score
            # 每消除一次 加10分
            score += 10


    if has_complete_row:
        draw_board(canvas, block_list)
        # 重新繪制
        win.title("SCORES: %s" % score)


# 讓游戲不斷循環(huán) 通過遞歸實(shí)現(xiàn)
def game_loop():
    win.update()

    global current_block
    # 如果當(dāng)前沒有俄羅斯方塊 產(chǎn)生一個(gè)新的
    if current_block is None:
        # 生成新的俄羅斯方塊
        new_block = product_new_block()
        draw_block_move(canvas, new_block)
        current_block = new_block

        # 游戲結(jié)束
        if not check_move(current_block, [0, 0]):
            messagebox.showinfo("Game Over!", "Your Score is %s" % score)
            win.destroy()
            return

    # 如果當(dāng)前有了就往下走
    else:
        if check_move(current_block, [0, 1]):
            draw_block_move(canvas, current_block, [0, 1])
        else:
            # 保存當(dāng)前的俄羅斯方塊
            save_to_block_list(current_block)
            current_block = None
    # 游戲結(jié)束
    check_and_clear()
    win.after(FPS, game_loop) # 注意的是這個(gè)game_loop后面不能加括號

# 當(dāng)前的俄羅斯方塊
current_block = None

# 畫布聚焦
canvas.focus_set()
# 添加左右移動(dòng)的事件
canvas.bind("<KeyPress-Left>", horizontal_move_block)
canvas.bind("<KeyPress-Right>", horizontal_move_block)
# 添加變化角度的事件
canvas.bind("<KeyPress-Up>", rotate_block)
canvas.bind("<KeyPress-Down>", land)


game_loop()
win.mainloop()

總結(jié)

到此這篇關(guān)于利用python制作俄羅斯方塊的文章就介紹到這了,更多相關(guān)python制作俄羅斯方塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python按條件篩選、剔除表格數(shù)據(jù)并繪制剔除前后的直方圖(示例代碼)

    Python按條件篩選、剔除表格數(shù)據(jù)并繪制剔除前后的直方圖(示例代碼)

    本文介紹基于Python語言,讀取Excel表格文件數(shù)據(jù),以其中某一列數(shù)據(jù)的值為標(biāo)準(zhǔn),對于這一列數(shù)據(jù)處于指定范圍的所有行,再用其他幾列數(shù)據(jù)的數(shù)值,加以數(shù)據(jù)篩選與剔除,感興趣的朋友跟隨小編一起看看吧
    2024-07-07
  • MNIST數(shù)據(jù)集轉(zhuǎn)化為二維圖片的實(shí)現(xiàn)示例

    MNIST數(shù)據(jù)集轉(zhuǎn)化為二維圖片的實(shí)現(xiàn)示例

    這篇文章主要介紹了MNIST數(shù)據(jù)集轉(zhuǎn)化為二維圖片的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01
  • 使用Python實(shí)現(xiàn)生成對角矩陣和對角塊矩陣

    使用Python實(shí)現(xiàn)生成對角矩陣和對角塊矩陣

    這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)生成對角矩陣和對角塊矩陣,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • Python使用matplotlib繪制動(dòng)畫的方法

    Python使用matplotlib繪制動(dòng)畫的方法

    這篇文章主要介紹了Python使用matplotlib繪制動(dòng)畫的方法,涉及matplotlib模塊的常見使用技巧,需要的朋友可以參考下
    2015-05-05
  • Python OpenCV招商銀行信用卡卡號識別的方法

    Python OpenCV招商銀行信用卡卡號識別的方法

    這篇文章主要介紹了Python OpenCV招商銀行信用卡卡號識別的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Python常用標(biāo)準(zhǔn)庫之os模塊功能

    Python常用標(biāo)準(zhǔn)庫之os模塊功能

    這篇文章主要介紹了Python常用標(biāo)準(zhǔn)庫之os模塊功能,os模塊的主要功能有系統(tǒng)相關(guān)、目錄及文件操作、執(zhí)行命令和管理進(jìn)程,其中的進(jìn)程管理功能主要是Linux相關(guān)的,此處不做討論,對Python標(biāo)準(zhǔn)庫os相關(guān)知識感興趣的朋友跟隨小編一起看看吧
    2022-11-11
  • Python學(xué)習(xí)之列表和元組的使用詳解

    Python學(xué)習(xí)之列表和元組的使用詳解

    如果說在Python語言中找一個(gè)最優(yōu)秀的數(shù)據(jù)類型,那無疑是列表,如果要在推薦一個(gè),那我選擇元組。本篇文章我們的重心會(huì)放在列表上,元組可以看成不能被修改的列表,感興趣的可以了解一下
    2022-10-10
  • python3.x+pyqt5實(shí)現(xiàn)主窗口狀態(tài)欄里(嵌入)顯示進(jìn)度條功能

    python3.x+pyqt5實(shí)現(xiàn)主窗口狀態(tài)欄里(嵌入)顯示進(jìn)度條功能

    這篇文章主要介紹了python3.x+pyqt5實(shí)現(xiàn)主窗口狀態(tài)欄里(嵌入)顯示進(jìn)度條功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-07-07
  • python 判斷文件或文件夾是否存在

    python 判斷文件或文件夾是否存在

    這篇文章主要介紹了python 判斷文件或文件夾是否存在,Python 操作文件時(shí),我們一般要先判斷指定的文件或目錄是否存在,不然容易產(chǎn)生異常,下面我們就來學(xué)習(xí)如何利用python檢查文件是否存在吧
    2022-03-03
  • 分享python中matplotlib指定繪圖顏色的八種方式

    分享python中matplotlib指定繪圖顏色的八種方式

    這篇文章主要給大家分享的是python中matplotlib指定繪圖顏色的八種方式,在使用matplotlib的pyplot庫進(jìn)行繪圖時(shí),經(jīng)常會(huì)發(fā)現(xiàn)各種開源代碼指定“color”的方式并不一致,下面就向大家展示8種指定color的方式,需要的朋友可以參考一下
    2022-03-03

最新評論

辽宁省| 堆龙德庆县| 通许县| 安丘市| 邵武市| 兴化市| 徐水县| 札达县| 右玉县| 玉溪市| 永德县| 台北市| 古丈县| 察雅县| 临朐县| 拉萨市| 江口县| 望谟县| 吴桥县| 安徽省| 北海市| 南澳县| 鹤庆县| 永年县| 和硕县| 饶阳县| 西林县| 阳城县| 久治县| 临安市| 延川县| 黄平县| 罗江县| 江阴市| 高唐县| 左贡县| 高陵县| 宁城县| 南雄市| 淮南市| 手游|