当前位置: 首页 > article >正文

每日一个小题

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.kler.cn/a/529683.html

相关文章:

  • C语言中的线程本地变量
  • 数组—学习
  • PVE 中 Debian 虚拟机崩溃后,硬盘数据怎么恢复
  • 【Python-办公自动化】实现自动化输出json数据类型的分析报告和正逆转换
  • 代理模式 - 代理模式的应用
  • Van-Nav:新年,将自己学习的项目地址统一整理搭建自己的私人导航站,供自己后续查阅使用,做技术的同学应该都有一个自己网站的梦想
  • Vue.js `v-memo` 性能优化技巧
  • helm-dashboard为Helm设计的缺失用户界面 - 可视化您的发布,它提供了一种基于UI的方式来查看已安装的Helm图表
  • 根据草图或图片生成网页提示词prompt
  • vue入门到实战 三
  • 基于单片机的盲人智能水杯系统(论文+源码)
  • 93,【1】buuctf web [网鼎杯 2020 朱雀组]phpweb
  • 从实验室到现实,机器人泛化的秘密:Scaling Law如何重塑机器人学习
  • 数据库 - Sqlserver - SQLEXPRESS、由Windows认证改为SQL Server Express认证进行连接 (sa登录)
  • 在Ubuntu上使用Docker部署DeepSeek
  • 基于密度泛函理论研究二维材料掺杂前后光电性能变化的模拟项目规划
  • JavaScript系列(53)--内存管理与垃圾回收机制详解
  • 包装类(全面解析)
  • 如何使用 DeepSeek 和 Dexscreener 构建免费的 AI 加密交易机器人?
  • 【JavaWeb学习Day14】
  • Windows上的本地化部署通义千问qwen,含API调用流式和非流式调用demo
  • 通信易懂唠唠SOME/IP——SOME/IP协议简介
  • UE5 蓝图学习计划 - Day 5:复习与整合实践
  • 3D图形学与可视化大屏:什么是材质属性,有什么作用?
  • 【Block总结】Shuffle Attention,新型的Shuffle注意力|即插即用
  • 在C语言中使用条件变量实现线程同步