每日一个小题

news/2025/2/3 6:28:44 标签: python

import pygame

import random

 

# 初始化 Pygame

pygame.init()

 

# 屏幕大小

screen_width = 300

screen_height = 600

block_size = 30

 

# 颜色定义

colors = [

    (0, 0, 0),

    (255, 0, 0),

    (0, 150, 0),

    (0, 0, 255),

    (255, 120, 0),

    (255, 255, 0),

    (180, 0, 255),

    (0, 220, 220)

]

 

# 形状定义

shapes = [

    [[1, 1, 1],

     [0, 1, 0]],

    

    [[0, 2, 2],

     [2, 2, 0]],

    

    [[3, 3, 0],

     [0, 3, 3]],

    

    [[4, 4],

     [4, 4]],

    

    [[0, 5, 0],

     [5, 5, 5]],

    

    [[6, 6, 6, 6]],

    

    [[7, 7],

     [7, 7]]

]

 

class Tetris:

    def __init__(self):

        self.width = screen_width // block_size

        self.height = screen_height // block_size

        self.board = [[0 for x in range(self.width)] for y in range(self.height)]

        self.score = 0

        self.gameover = False

        self.current_piece = self.new_piece()

        self.next_piece = self.new_piece()

        self.clock = pygame.time.Clock()

        self.fall_time = 0

        self.level = 1

        self.lines = 0

 

    def new_piece(self):

        shape = random.choice(shapes)

        color = colors[shapes.index(shape) + 1]

        return {'shape': shape, 'color': color, 'x': self.width // 2 - len(shape[0]) // 2, 'y': 0}

 

    def rotate_piece(self):

        piece = self.current_piece['shape']

        new_piece = list(zip(*piece[::-1]))

        self.current_piece['shape'] = new_piece

 

    def valid_space(self, piece, offset):

        off_x, off_y = offset

        for y, row in enumerate(piece):

            for x, cell in enumerate(row):

                if cell and (x + off_x < 0 or x + off_x >= self.width or y + off_y >= self.height or self.board[y + off_y][x + off_x]):

                    return False

        return True

 

    def freeze(self):

        piece = self.current_piece['shape']

        for y, row in enumerate(piece):

            for x, cell in enumerate(row):

                if cell:

                    self.board[y + self.current_piece['y']][x + self.current_piece['x']] = self.current_piece['color']

        self.clear_lines()

        self.current_piece = self.next_piece

        self.next_piece = self.new_piece()

        if not self.valid_space(self.current_piece['shape'], (self.current_piece['x'], self.current_piece['y'])):

            self.gameover = True

 

    def clear_lines(self):

        lines = 0

        for i, row in enumerate(self.board):

            if all(row):

                del self.board[i]

                self.board.insert(0, [0 for _ in range(self.width)])

                lines += 1

        self.score += lines ** 2 * 100

        self.lines += lines

        if self.lines >= 10:

            self.level += 1

            self.lines -= 10

            pygame.time.set_timer(pygame.USEREVENT+1, max(100, 1000 - (self.level-1)*100))

 

    def drop(self):

        self.current_piece['y'] += 1

        if not self.valid_space(self.current_piece['shape'], (self.current_piece['x'], self.current_piece['y'])):

            self.current_piece['y'] -= 1

            self.freeze()

 

    def move(self, dx):

        self.current_piece['x'] += dx

        if not self.valid_space(self.current_piece['shape'], (self.current_piece['x'], self.current_piece['y'])):

            self.current_piece['x'] -= dx

 

    def draw_grid(self, surface):

        for y in range(self.height):

            for x in range(self.width):

                pygame.draw.rect(surface, colors[self.board[y][x]], (x*block_size, y*block_size, block_size, block_size), 0)

                pygame.draw.rect(surface, (255, 255, 255), (x*block_size, y*block_size, block_size, block_size), 1)

 

    def draw_piece(self, surface):

        shape = self.current_piece['shape']

        for y, row in enumerate(shape):

            for x, cell in enumerate(row):

                if cell:

                    pygame.draw.rect(surface, self.current_piece['color'], ((self.current_piece['x'] + x) * block_size, (self.current_piece['y'] + y) * block_size, block_size, block_size), 0)

                    pygame.draw.rect(surface, (255, 255, 255), ((self.current_piece['x'] + x) * block_size, (self.current_piece['y'] + y) * block_size, block_size, block_size), 1)

 

    def run(self):

        screen = pygame.display.set_mode((screen_width, screen_height))

        pygame.display.set_caption('Tetris')

        pygame.time.set_timer(pygame.USEREVENT+1, 1000)

        while not self.gameover:

            for event in pygame.event.get():

                if event.type == pygame.QUIT:

                    pygame.quit()

                    return

                elif event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_LEFT:

                        self.move(-1)

                    elif event.key == pygame.K_RIGHT:

                        self.move(1)

                    elif event.key == pygame.K_DOWN:

                        self.drop()

                    elif event.key == pygame.K_UP:

                        self.rotate_piece()

                elif event.type == pygame.USEREVENT+1:

                    self.drop()

            self.fall_time += self.clock.get_rawtime()

            self.clock.tick()

            if self.fall_time / 1000 > 1:

                self.drop()

                self.fall_time = 0

            screen.fill((0, 0, 0))

            self.draw_grid(screen)

            self.draw_piece(screen)

            pygame.display.flip()

        print("Game Over! Score:", self.score)

        pygame.quit()

 

if __name__ == '__main__':

    game = Tetris()

    game.run()

实现了一个基本的俄罗斯方块游戏,包括方块的移动、旋转、下落以及行的消除等功能,你可以直接运行这个脚本来玩游戏

 


http://www.niftyadmin.cn/n/5840552.html

相关文章

用BGP的路由聚合功能聚合大陆路由,效果显著不?

正文共&#xff1a;666 字 11 图&#xff0c;预估阅读时间&#xff1a;1 分钟 之前我们统计过中国境内的IP地址和路由信息&#xff08;你知道中国大陆一共有多少IPv4地址吗&#xff1f;&#xff09;&#xff0c;不过数量比较多&#xff0c;有8000多条。截止到2021年底&#xff…

【算法】回溯算法专题② ——组合型回溯 + 剪枝 python

目录 前置知识进入正题小试牛刀实战演练总结 前置知识 【算法】回溯算法专题① ——子集型回溯 python 进入正题 组合https://leetcode.cn/problems/combinations/submissions/596357179/ 给定两个整数 n 和 k&#xff0c;返回范围 [1, n] 中所有可能的 k 个数的组合。 你可以…

RocketMQ中的NameServer主要数据结构

1.前言 NameServer是RocketMQ中的一个比较重要的组件&#xff0c;我们这篇博客针对NameSever中包含的组件进行分析&#xff0c;分析一下NameServer中包含的组件以及组件的作用。以前我有一篇博客中rocketMq源码分析之搭建本地环境-CSDN博客&#xff0c;在这篇博客中就简单看了…

【C语言设计模式学习笔记1】面向接口编程/简单工厂模式/多态

面向接口编程可以提供更高级的抽象&#xff0c;实现的时候&#xff0c;外部不需要知道内部的具体实现&#xff0c;最简单的是使用简单工厂模式来进行实现&#xff0c;比如一个Sensor具有多种表示形式&#xff0c;这时候可以在给Sensor结构体添加一个enum类型的type&#xff0c;…

【go语言】grpc 快速入门

一、什么是 grpc 和 protobuf 1.1 grpc gRPC 是由 Google 开发的一个高效、开源的远程过程调用&#xff08;RPC&#xff09;框架&#xff0c;用于在分布式系统中进行通信。它是基于 HTTP/2 协议&#xff0c;支持多种语言&#xff0c;能够让不同的系统或应用程序&#xff08;即…

【大数据技术】案例01:词频统计样例(hadoop+mapreduce+yarn)

词频统计(hadoop+mapreduce+yarn) 搭建完全分布式高可用大数据集群(VMware+CentOS+FinalShell) 搭建完全分布式高可用大数据集群(Hadoop+MapReduce+Yarn) 在阅读本文前,请确保已经阅读过以上两篇文章,成功搭建了Hadoop+MapReduce+Yarn的大数据集群环境。 写在前面 Wo…

【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(二)

✨感谢您阅读本篇文章&#xff0c;文章内容是个人学习笔记的整理&#xff0c;如果哪里有误的话还请您指正噢✨ ✨ 个人主页&#xff1a;余辉zmh–CSDN博客 ✨ 文章所属专栏&#xff1a;贪心算法篇–CSDN博客 文章目录 前言例题1.买卖股票的最佳时机2.买卖股票的最佳时机23.k次取…

git安装flutter

首先设置 Flutter 的镜像环境变量&#xff08;在 PowerShell 中运行&#xff09;&#xff1a; # 设置 Flutter 镜像 $env:PUB_HOSTED_URL"https://pub.flutter-io.cn" $env:FLUTTER_STORAGE_BASE_URL"https://storage.flutter-io.cn"# 将这些环境变量永久…