首页 > 编程语言 >俄罗斯方块小游戏(附源码)

俄罗斯方块小游戏(附源码)

时间:2024-06-17 12:32:01浏览次数:20  
标签:turtle map col 小游戏 方块 active 源码 block row

游戏展示

一.导包

import turtle
import random

二.定义一个Block类

  1. 定义一个Block类,用于表示游戏中的方块,包含颜色和形状。
class Block:
    def __init__(self, color, tiles):
        self.color = color
        self.tiles = tiles

三.定义了7个不同的Block对象

  1. 定义了7个不同的Block对象,分别代表游戏中的7种不同的方块,每种方块都有其特定的颜色和形状。
I = Block("cyan", [[[1, 0, 0, 0],
                    [1, 0, 0, 0],
                    [1, 0, 0, 0],
                    [1, 0, 0, 0]],

                   [[0, 0, 0, 0],
                    [0, 0, 0, 0],
                    [0, 0, 0, 0],
                    [1, 1, 1, 1]]])

J = Block("blue", [[[0, 1, 0],
                    [0, 1, 0],
                    [1, 1, 0]],

                   [[0, 0, 0],
                    [1, 1, 1],
                    [0, 0, 1]],

                   [[1, 1, 0],
                    [1, 0, 0],
                    [1, 0, 0]],

                   [[0, 0, 0],
                    [1, 0, 0],
                    [1, 1, 1]]])

L = Block("orange", [[[1, 0, 0],
                      [1, 0, 0],
                      [1, 1, 0]],

                     [[0, 0, 0],
                      [0, 0, 1],
                      [1, 1, 1]],

                     [[0, 1, 1],
                      [0, 0, 1],
                      [0, 0, 1]],

                     [[0, 0, 0],
                      [1, 1, 1],
                      [1, 0, 0]]])

S = Block("lime", [[[0, 0, 0],
                    [0, 1, 1],
                    [1, 1, 0]],

                   [[1, 0, 0],
                    [1, 1, 0],
                    [0, 1, 0]]])

Z = Block("red", [[[0, 0, 0],
                   [1, 1, 0],
                   [0, 1, 1]],

                  [[0, 1, 0],
                   [1, 1, 0],
                   [1, 0, 0]]])

O = Block("yellow", [[[1, 1],
                      [1, 1]]])

T = Block("magenta", [[[0, 0, 0],
                       [0, 1, 0],
                       [1, 1, 1]],

                      [[0, 1, 0],
                       [1, 1, 0],
                       [0, 1, 0]],

                      [[0, 0, 0],
                       [1, 1, 1],
                       [0, 1, 0]],

                      [[1, 0, 0],
                       [1, 1, 0],
                       [1, 0, 0]]])

 四.定义了一些游戏相关的全局变量

定义了一些游戏相关的全局变量,如方块大小、地图大小、地图起始坐标、分数等

tile_size = 25
map_rows = 20
map_cols = 10
map_x = -125
map_y = 250

五.创建了几个Turtle对象

用于在屏幕上绘制地图、方块、分数和游戏结束信息

map_turtle = turtle.Turtle()
map_turtle.hideturtle()
map_turtle.up()

game_map = [["" for _ in range(map_cols)] for _ in range(map_rows)]

active_block = None
active_block_row = 0
active_block_col = 0
active_block_index = 0

block_turtle = turtle.Turtle()
block_turtle.hideturtle()
block_turtle.up()

game_update_interval = 250

score = 0
score_turtle = turtle.Turtle()
score_turtle.hideturtle()
score_turtle.up()
score_turtle.goto(170, 210)
score_turtle.write("Score: " + str(score), font=("Calibri", 20, "bold"))

game_over_turtle = turtle.Turtle()
game_over_turtle.hideturtle()
game_over_turtle.color("red")

六.定义函数

(1)draw_box函数

用于绘制方块

def draw_box(t, width, height, pencolor, fillcolor):
    t.color(pencolor, fillcolor)
    t.down()
    t.begin_fill()
    for _ in range(2):
        t.forward(width)
        t.right(90)
        t.forward(height)
        t.right(90)
    t.end_fill()
    t.up()

(2)draw_map函数

用于绘制地图

def draw_map():
    map_turtle.clear()
    for row in range(map_rows):
        for col in range(map_cols):
            map_turtle.goto(map_x + tile_size * col, map_y - tile_size * row)
            draw_box(map_turtle, tile_size, tile_size, "black",
                     game_map[row][col].color if game_map[row][col] else "mintcream")

(3)make_new_block函数

用于生成新的方块

def make_new_block():
    global active_block
    global active_block_row, active_block_col
    global active_block_index

    active_block = random.choice((I, J, L, S, Z, O, T))
    active_block_row = 0
    active_block_col = 4
    active_block_index = 0

(4)draw_block函数

用于绘制当前方块

def draw_block():
    block_turtle.clear()

    # Find the x and y position of the block
    x = map_x + active_block_col * tile_size
    y = map_y - active_block_row * tile_size

    block_tiles = active_block.tiles[active_block_index]
    block_color = active_block.color
    for row in range(len(block_tiles)):
        for col in range(len(block_tiles[row])):
            if block_tiles[row][col] == 1:
                block_turtle.goto(x + col * tile_size, y - row * tile_size)
                draw_box(block_turtle, tile_size, tile_size, "black", block_color)

(5)is_valid_block函数

用于检查方块是否可以在当前位置放置

def is_valid_block(block_type, block_row, block_col, block_index):
    block_tiles = block_type.tiles[block_index]
    for row in range(len(block_tiles)):
        for col in range(len(block_tiles[row])):
            if block_tiles[row][col] == 1:
                if block_row + row not in range(0, map_rows):
                    return False
                if block_col + col not in range(0, map_cols):
                    return False
                if game_map[block_row + row][block_col + col] != "":
                    return False

    return True

(6)set_block_on_map函数

用于将方块固定到地图上

def set_block_on_map():
    block_tiles = active_block.tiles[active_block_index]
    for row in range(len(block_tiles)):
        for col in range(len(block_tiles[row])):
            if block_tiles[row][col] == 1:
                game_map[active_block_row + row][active_block_col + col] = active_block
    draw_map()


r = 0

(7)remove_completed_rows函数

用于移除完成的行,并更新分数和游戏难度

def remove_completed_rows():
    global game_map
    global score
    global game_update_interval
    global r

    new_map = []
    for row in range(len(game_map)):
        game_row = game_map[row]
        if "" in game_row:
            new_map.append(game_row)
        else:
            score += 10
            score_turtle.clear()
            score_turtle.write("Score: " + str(score), font=("Calibri", 20, "bold"))
            r += 1
            if r == 5:
                game_update_interval = int(game_update_interval / 1.1)
                r = 0

    for row in range(0, map_rows - len(new_map)):
        game_row = ["" for _ in range(map_cols)]
        new_map.insert(0, game_row)

    game_map = new_map
    draw_map()

    # Task: increase the score and difficulty when a row is completed


pause = False

 七.定义了一个游戏循环

用于控制游戏的主要逻辑,如方块的移动、旋转、下落

 设置了键盘事件监听,用于处理玩家的输入,如旋转、移动、加速下落和暂停游戏

def game_loop():
    global active_block, active_block_row

    if active_block is None:
        make_new_block()
        if not is_valid_block(active_block, active_block_row, active_block_col, active_block_index):
            active_block = None
            game_over_turtle.write("Game over!", align="center", font=("Calibri", 60, "bold"))
            return
        draw_block()

    else:
        if is_valid_block(active_block, active_block_row + 1, active_block_col, active_block_index):
            if not pause:
                active_block_row += 1
                draw_block()
        else:
            set_block_on_map()
            active_block = None
            remove_completed_rows()

    turtle.update()

    # Set the next update

    turtle.ontimer(game_loop, game_update_interval)


# Set up the turtle window
turtle.setup(800, 600)
turtle.title("Tetris")
turtle.bgcolor("navajowhite")
turtle.up()
turtle.hideturtle()
turtle.tracer(False)

# Draw the background border around the map
turtle.goto(map_x - 10, map_y + 10)
draw_box(turtle, tile_size * map_cols + 20, tile_size * map_rows + 20, \
         "", "lightslategray")

# Draw the empty map in the window
draw_map()
turtle.update()

# Set up the game loop
turtle.ontimer(game_loop, game_update_interval)


def rotate():
    global active_block_index

    if active_block is None:
        return
    new_block_index = (active_block_index + 1) % len(active_block.tiles)
    if is_valid_block(active_block, active_block_row, active_block_col, new_block_index):
        active_block_index = new_block_index
        draw_block()


turtle.onkeypress(rotate, "Up")


def move_left():
    global active_block_col

    if active_block is None:
        return
    if is_valid_block(active_block, active_block_row, active_block_col - 1, active_block_index):
        active_block_col -= 1
        draw_block()


turtle.onkeypress(move_left, "Left")


def move_right():
    global active_block_col

    if active_block is None:
        return
    if is_valid_block(active_block, active_block_row, active_block_col + 1, active_block_index):
        active_block_col += 1
        draw_block()


turtle.onkeypress(move_right, "Right")


def drop():
    global active_block_row

    if active_block is None:
        return
    while is_valid_block(active_block, active_block_row + 1, active_block_col, active_block_index):
        active_block_row += 1
    draw_block()


turtle.onkeypress(drop, "Down")


def pause_game():
    global pause
    pause = not pause


turtle.onkeypress(pause_game, "space")


def change_block_type():
    global active_block
    global active_block_index

    new_block = random.choice((I, J, L, S, Z, O, T))
    new_block_index = 0
    if is_valid_block(new_block, active_block_row, active_block_col, new_block_index):
        active_block = new_block
        active_block_index = new_block_index
        draw_block()


turtle.onkeypress(change_block_type, "c")

turtle. Listen()

八.启动游戏

turtle.done()

全部代码

代码来自微信公众号python顾木子吖 感兴趣的小伙伴可以关注一下

import turtle
import random


class Block:
    def __init__(self, color, tiles):
        self.color = color
        self.tiles = tiles


I = Block("cyan", [[[1, 0, 0, 0],
                    [1, 0, 0, 0],
                    [1, 0, 0, 0],
                    [1, 0, 0, 0]],

                   [[0, 0, 0, 0],
                    [0, 0, 0, 0],
                    [0, 0, 0, 0],
                    [1, 1, 1, 1]]])

J = Block("blue", [[[0, 1, 0],
                    [0, 1, 0],
                    [1, 1, 0]],

                   [[0, 0, 0],
                    [1, 1, 1],
                    [0, 0, 1]],

                   [[1, 1, 0],
                    [1, 0, 0],
                    [1, 0, 0]],

                   [[0, 0, 0],
                    [1, 0, 0],
                    [1, 1, 1]]])

L = Block("orange", [[[1, 0, 0],
                      [1, 0, 0],
                      [1, 1, 0]],

                     [[0, 0, 0],
                      [0, 0, 1],
                      [1, 1, 1]],

                     [[0, 1, 1],
                      [0, 0, 1],
                      [0, 0, 1]],

                     [[0, 0, 0],
                      [1, 1, 1],
                      [1, 0, 0]]])

S = Block("lime", [[[0, 0, 0],
                    [0, 1, 1],
                    [1, 1, 0]],

                   [[1, 0, 0],
                    [1, 1, 0],
                    [0, 1, 0]]])

Z = Block("red", [[[0, 0, 0],
                   [1, 1, 0],
                   [0, 1, 1]],

                  [[0, 1, 0],
                   [1, 1, 0],
                   [1, 0, 0]]])

O = Block("yellow", [[[1, 1],
                      [1, 1]]])

T = Block("magenta", [[[0, 0, 0],
                       [0, 1, 0],
                       [1, 1, 1]],

                      [[0, 1, 0],
                       [1, 1, 0],
                       [0, 1, 0]],

                      [[0, 0, 0],
                       [1, 1, 1],
                       [0, 1, 0]],

                      [[1, 0, 0],
                       [1, 1, 0],
                       [1, 0, 0]]])

tile_size = 25
map_rows = 20
map_cols = 10
map_x = -125
map_y = 250

map_turtle = turtle.Turtle()
map_turtle.hideturtle()
map_turtle.up()

game_map = [["" for _ in range(map_cols)] for _ in range(map_rows)]

active_block = None
active_block_row = 0
active_block_col = 0
active_block_index = 0

block_turtle = turtle.Turtle()
block_turtle.hideturtle()
block_turtle.up()

game_update_interval = 250

score = 0
score_turtle = turtle.Turtle()
score_turtle.hideturtle()
score_turtle.up()
score_turtle.goto(170, 210)
score_turtle.write("Score: " + str(score), font=("Calibri", 20, "bold"))

game_over_turtle = turtle.Turtle()
game_over_turtle.hideturtle()
game_over_turtle.color("red")


def draw_box(t, width, height, pencolor, fillcolor):
    t.color(pencolor, fillcolor)
    t.down()
    t.begin_fill()
    for _ in range(2):
        t.forward(width)
        t.right(90)
        t.forward(height)
        t.right(90)
    t.end_fill()
    t.up()


def draw_map():
    map_turtle.clear()
    for row in range(map_rows):
        for col in range(map_cols):
            map_turtle.goto(map_x + tile_size * col, map_y - tile_size * row)
            draw_box(map_turtle, tile_size, tile_size, "black",
                     game_map[row][col].color if game_map[row][col] else "mintcream")


def make_new_block():
    global active_block
    global active_block_row, active_block_col
    global active_block_index

    active_block = random.choice((I, J, L, S, Z, O, T))
    active_block_row = 0
    active_block_col = 4
    active_block_index = 0


def draw_block():
    block_turtle.clear()

    # Find the x and y position of the block
    x = map_x + active_block_col * tile_size
    y = map_y - active_block_row * tile_size

    block_tiles = active_block.tiles[active_block_index]
    block_color = active_block.color
    for row in range(len(block_tiles)):
        for col in range(len(block_tiles[row])):
            if block_tiles[row][col] == 1:
                block_turtle.goto(x + col * tile_size, y - row * tile_size)
                draw_box(block_turtle, tile_size, tile_size, "black", block_color)


def is_valid_block(block_type, block_row, block_col, block_index):
    block_tiles = block_type.tiles[block_index]
    for row in range(len(block_tiles)):
        for col in range(len(block_tiles[row])):
            if block_tiles[row][col] == 1:
                if block_row + row not in range(0, map_rows):
                    return False
                if block_col + col not in range(0, map_cols):
                    return False
                if game_map[block_row + row][block_col + col] != "":
                    return False

    return True


def set_block_on_map():
    block_tiles = active_block.tiles[active_block_index]
    for row in range(len(block_tiles)):
        for col in range(len(block_tiles[row])):
            if block_tiles[row][col] == 1:
                game_map[active_block_row + row][active_block_col + col] = active_block
    draw_map()


r = 0


def remove_completed_rows():
    global game_map
    global score
    global game_update_interval
    global r

    new_map = []
    for row in range(len(game_map)):
        game_row = game_map[row]
        if "" in game_row:
            new_map.append(game_row)
        else:
            score += 10
            score_turtle.clear()
            score_turtle.write("Score: " + str(score), font=("Calibri", 20, "bold"))
            r += 1
            if r == 5:
                game_update_interval = int(game_update_interval / 1.1)
                r = 0

    for row in range(0, map_rows - len(new_map)):
        game_row = ["" for _ in range(map_cols)]
        new_map.insert(0, game_row)

    game_map = new_map
    draw_map()

    # Task: increase the score and difficulty when a row is completed


pause = False


def game_loop():
    global active_block, active_block_row

    if active_block is None:
        make_new_block()
        if not is_valid_block(active_block, active_block_row, active_block_col, active_block_index):
            active_block = None
            game_over_turtle.write("Game over!", align="center", font=("Calibri", 60, "bold"))
            return
        draw_block()

    else:
        if is_valid_block(active_block, active_block_row + 1, active_block_col, active_block_index):
            if not pause:
                active_block_row += 1
                draw_block()
        else:
            set_block_on_map()
            active_block = None
            remove_completed_rows()

    turtle.update()

    # Set the next update

    turtle.ontimer(game_loop, game_update_interval)


# Set up the turtle window
turtle.setup(800, 600)
turtle.title("Tetris")
turtle.bgcolor("navajowhite")
turtle.up()
turtle.hideturtle()
turtle.tracer(False)

# Draw the background border around the map
turtle.goto(map_x - 10, map_y + 10)
draw_box(turtle, tile_size * map_cols + 20, tile_size * map_rows + 20, \
         "", "lightslategray")

# Draw the empty map in the window
draw_map()
turtle.update()

# Set up the game loop
turtle.ontimer(game_loop, game_update_interval)


def rotate():
    global active_block_index

    if active_block is None:
        return
    new_block_index = (active_block_index + 1) % len(active_block.tiles)
    if is_valid_block(active_block, active_block_row, active_block_col, new_block_index):
        active_block_index = new_block_index
        draw_block()


turtle.onkeypress(rotate, "Up")


def move_left():
    global active_block_col

    if active_block is None:
        return
    if is_valid_block(active_block, active_block_row, active_block_col - 1, active_block_index):
        active_block_col -= 1
        draw_block()


turtle.onkeypress(move_left, "Left")


def move_right():
    global active_block_col

    if active_block is None:
        return
    if is_valid_block(active_block, active_block_row, active_block_col + 1, active_block_index):
        active_block_col += 1
        draw_block()


turtle.onkeypress(move_right, "Right")


def drop():
    global active_block_row

    if active_block is None:
        return
    while is_valid_block(active_block, active_block_row + 1, active_block_col, active_block_index):
        active_block_row += 1
    draw_block()


turtle.onkeypress(drop, "Down")


def pause_game():
    global pause
    pause = not pause


turtle.onkeypress(pause_game, "space")


def change_block_type():
    global active_block
    global active_block_index

    new_block = random.choice((I, J, L, S, Z, O, T))
    new_block_index = 0
    if is_valid_block(new_block, active_block_row, active_block_col, new_block_index):
        active_block = new_block
        active_block_index = new_block_index
        draw_block()


turtle.onkeypress(change_block_type, "c")

turtle.listen()

turtle.done()

标签:turtle,map,col,小游戏,方块,active,源码,block,row
From: https://blog.csdn.net/jingshi123456/article/details/139739103

相关文章

  • ThreadLocal 核心源码分析
    ThreadLocal简介多线程访问同一个共享变量的时候容易出现并发问题,特别是多个线程对一个变量进行写入的时候,为了保证线程安全,一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线程安全性。ThreadLocal是除了加锁这种同步方式之外的一种保证和规避多线程访问出......
  • 基于springboot的球队训练信息管理系统源码数据库
    传统办法管理信息首先需要花费的时间比较多,其次数据出错率比较高,而且对错误的数据进行更改也比较困难,最后,检索数据费事费力。因此,在计算机上安装球队训练信息管理系统软件来发挥其高效地信息处理的作用,可以规范信息管理流程,让管理工作可以系统化和程序化,同时,球队训练信息管理系......
  • 基于springboot的青年公寓服务平台源码数据库
    传统信息的管理大部分依赖于管理人员的手工登记与管理,然而,随着近些年信息技术的迅猛发展,让许多比较老套的信息管理模式进行了更新迭代,房屋信息因为其管理内容繁杂,管理数量繁多导致手工进行处理不能满足广大用户的需求,因此就应运而生出相应的青年公寓服务平台。本青年公寓服务......
  • 【源码】2024最新陪诊小程序uniapp+thinkphp
    202024最新陪诊小程序uniapp+thinkphp资源来源:52codes.cc20最新陪诊小程序uniapp+thinkphp简介:随着社会逐渐步进入老龄化越来越多的老年人或者不经常去医院的用户对于医院繁琐的流程很是苦劳于是陪诊这个行业开始兴起。小白陪诊开发理念,为了满足用户就医陪......
  • 基于springboot的无人智慧超市管理系统【附源码】
    效果如下:首页注册商品信息个人中心管理员主页面仓储信息管理订单管理界面研究背景近年来,由于计算机技术和互联网技术的快速发展,使得所有企事业单位内部都是数字化、信息化、无纸化的发展趋势,随着趋势的发展,各种决策系统、辅助系统也应运而生,其中无人智慧超......
  • 面向储存的源码级轻量预处理编程
    以下是对它的定义面向储存的源码级轻量预处理编程是一种在算法竞赛(competitiveprogramming)中常用技巧(skill),它是一种基于预处理的思想而演变出来的编程方法。要采用这种方法,首先可以把整个程序分为两部分:生成器(genernater)结果程序(result)我们通常使用生成器把一......
  • Dubbo源码解析-mock原理
    上篇我们介绍了消费端调用流程Dubbo源码解读-Consumer调用流程解析_dubboconsumer-CSDN博客    因为篇幅问题,本文主单独Dubbo消费端mock原理,从dubbo源码角度进行解析。    大家可以好好仔细读一下本文。有疑问欢迎留言。    接着说明,读Dubbo源码......
  • 学生管理系统(超详细教程+源码)
    学生管理系统1.前言1.1项目地址本项目共有前后两端地址(使用Docker部署,也可以自己部署到本地)。前端:SSE-DZH/MS-Vue:MS前端vue(github.com)后端:SSE-DZH/MS-Spring:MS后端(github.com)2.开发环境2.1基础环境JDK版本:17MySQL版本:8.0.36Redis版本:3.2.100......
  • SpringBoot源码学习之AOP切面编程原理
    1.前言&目录AOP切面编程主要用于抽取与具体业务逻辑无关的逻辑并组织起来以另一种方式重新与业务逻辑“耦合”在一起。比如,在WEB项目中,往往需要对接口做鉴权、性能统计、日志记录、事务处理等,这些逻辑跟业务逻辑无关、是独立的,但它也是多数业务逻辑都需要的。将这些横跨多种......
  • Java集合类源码
    Java集合类源码(粒度:方法层面)ArrayList构造方法,有三种publicArrayList(intinitialCapacity)/*初始化容量>0,分配空间初始化容量=0,赋值空数组否则抛IllegalArgumentException异常*/publicArrayList()//直接赋值空数组publicArrayList(Collection<?extendsE>c)......