首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >CodeBuddy惊艳了我

CodeBuddy惊艳了我

原创
作者头像
Windows技术交流
修改2025-10-24 18:17:53
修改2025-10-24 18:17:53
8600
代码可运行
举报
文章被收录于专栏:Windows技术交流Windows技术交流
运行总次数:0
代码可运行

「无界生成力」CodeBuddy 1024活动征文

#CodeBuddy 1024

「工具协作」:CodeBuddy 助力开发效率提升的真实案例

#CodeBuddy

#CodeBuddyIDE

#CodeBuddyCode

#无界生成力

CodeBuddy打从刚上线我就开始在使用了,几个月下来,已经离不开它了

今天2025.10.24是IT人特殊的节日,不得不说CodeBuddy新版初始界面真的很好看!

个人简介:本人从事云计算技术支持超过11年,从事Windows专项5年,累计写过超1000篇Windows方面的文档。

我这里分享自身实践的2个CodeBuddy 助力开发效率提升的真实案例

①腾讯云userdata初始化windows数据盘的需求,用CodeBuddy(我选的GPT5)完美实现,只两三个交互调试就OK了,惊艳!

生成的初始化windows数据盘的powershell代码我放到了cos:http://windowsbj-1251783334.cos.ap-beijing.myqcloud.com/Init-DataDisks.ps1

以下是userdata的完整调用(需要机器有公网才可以拉取cos文件,单机没网测试的话,需要提前把脚本放到硬盘里备用)

代码语言:txt
复制
#ps1
Set-executionpolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -Force;
wget http://windowsbj-1251783334.cos.ap-beijing.myqcloud.com/Init-DataDisks.ps1 -Outfile c:\Init-DataDisks.ps1
C:\Init-DataDisks.ps1 -DryRun:$false -AcknowledgeDataLoss -PrimaryLetter E -GptThresholdGiB 2047 -LargeThresholdGiB 16383 -DefaultUnitKB 4 -LargeUnitKB 64 -Log C:\Init-DataDisks.txt

②用CodeBuddy一句话生成俄罗斯方块游戏,简单几次提修改要求后,达到完美(我只会扫雷、俄罗斯方块这2个简单的游戏,其他的不会玩),结尾附CodeBuddy生成的源码,我一个字母都没改!

RussiaBlock.zip

main.py

代码语言:python
代码运行次数:0
运行
复制
# -*- coding: utf-8 -*-
import sys
import random
import pygame
import math
from pygame import Rect

# ------------------------------
# 基础设置
# ------------------------------
CELL_SIZE = 30
COLUMNS = 10
ROWS = 20
# 侧栏按像素动态计算,保证容纳“Score: ”+ 20 位数字
SIDE_PANEL_MIN_PX = 6 * CELL_SIZE  # 最小宽度(像素)
SIDE_PANEL_W_PX = SIDE_PANEL_MIN_PX  # 运行时会根据字体测量更新
FPS = 60

WIDTH = None  # 运行时根据侧栏像素宽度计算
HEIGHT = ROWS * CELL_SIZE
PLAYFIELD_X = 2 * CELL_SIZE  # 左边留空距,居中观感更好
PLAYFIELD_Y = CELL_SIZE
PLAYFIELD_WIDTH = COLUMNS * CELL_SIZE
PLAYFIELD_HEIGHT = ROWS * CELL_SIZE

# 颜色
BLACK = (18, 18, 18)
DARK = (24, 24, 24)
GRAY = (60, 60, 60)
LIGHT = (200, 200, 200)
WHITE = (245, 245, 245)

COLORS = [
    (80, 227, 230),  # I 青
    (36, 95, 223),   # J 蓝
    (223, 173, 36),  # L 橙
    (223, 62, 62),   # Z 红
    (62, 223, 76),   # S 绿
    (156, 39, 176),  # T 紫
    (223, 223, 36),  # O 黄
]

# 形状(以 4x4 方阵为基准),每个元素为旋转状态列表
SHAPES = {
    'I': [
        [(0, 1), (1, 1), (2, 1), (3, 1)],
        [(2, 0), (2, 1), (2, 2), (2, 3)],
    ],
    'J': [
        [(0, 0), (0, 1), (1, 1), (2, 1)],
        [(1, 0), (2, 0), (1, 1), (1, 2)],
        [(0, 1), (1, 1), (2, 1), (2, 2)],
        [(1, 0), (1, 1), (0, 2), (1, 2)],
    ],
    'L': [
        [(2, 0), (0, 1), (1, 1), (2, 1)],
        [(1, 0), (1, 1), (1, 2), (2, 2)],
        [(0, 1), (1, 1), (2, 1), (0, 2)],
        [(0, 0), (1, 0), (1, 1), (1, 2)],
    ],
    'Z': [
        [(0, 1), (1, 1), (1, 2), (2, 2)],
        [(2, 0), (1, 1), (2, 1), (1, 2)],
    ],
    'S': [
        [(1, 1), (2, 1), (0, 2), (1, 2)],
        [(1, 0), (1, 1), (2, 1), (2, 2)],
    ],
    'T': [
        [(1, 0), (0, 1), (1, 1), (2, 1)],
        [(1, 0), (1, 1), (2, 1), (1, 2)],
        [(0, 1), (1, 1), (2, 1), (1, 2)],
        [(1, 0), (0, 1), (1, 1), (1, 2)],
    ],
    'O': [
        [(1, 0), (2, 0), (1, 1), (2, 1)],
    ],
}

PIECE_ORDER = ['I', 'J', 'L', 'Z', 'S', 'T', 'O']

class Piece:
    def __init__(self, kind: str):
        self.kind = kind
        self.rotations = SHAPES[kind]
        self.rotation_index = 0
        self.x = COLUMNS // 2 - 2
        self.y = -2  # 从上方进入
        self.color = COLORS[PIECE_ORDER.index(kind)]

    @property
    def blocks(self):
        return self.rotations[self.rotation_index]

    def rotated(self, direction: int):
        nxt = Piece(self.kind)
        nxt.rotation_index = (self.rotation_index + direction) % len(self.rotations)
        nxt.x = self.x
        nxt.y = self.y
        return nxt

class BagRandom:
    """7-袋随机:每个袋子包含7种形状,随机打乱后依次发放。"""
    def __init__(self):
        self.bag = []

    def next_piece(self) -> Piece:
        if not self.bag:
            self.bag = PIECE_ORDER[:]
            random.shuffle(self.bag)
        return Piece(self.bag.pop())

class Game:
    def __init__(self):
        self.board = [[None for _ in range(COLUMNS)] for _ in range(ROWS)]
        self.randomizer = BagRandom()
        self.current: Piece | None = None
        self.hold: Piece | None = None
        self.hold_used = False
        self.queue = []
        self.score = 0
        self.level = 1
        self.lines_cleared = 0
        self.drop_interval_ms = 1000
        self.drop_timer = 0
        self.game_over = False
        self.paused = False
        self.font = None
        self._refill_queue()
        self.spawn()

    def _refill_queue(self):
        while len(self.queue) < 5:
            self.queue.append(self.randomizer.next_piece())

    def spawn(self):
        self.current = self.queue.pop(0)
        self._refill_queue()
        self.hold_used = False
        self.current.x = COLUMNS // 2 - 2
        self.current.y = -2
        if self._collides(self.current, dx=0, dy=0):
            self.game_over = True

    def hard_drop(self):
        if not self.current:
            return
        distance = 0
        while not self._collides(self.current, dy=1):
            self.current.y += 1
            distance += 1
        self._lock_piece()
        self.score += distance * 2

    def soft_drop(self):
        if not self.current or self._collides(self.current, dy=1):
            return False
        self.current.y += 1
        self.score += 1
        return True

    def move(self, dx: int):
        if not self.current:
            return
        if not self._collides(self.current, dx=dx):
            self.current.x += dx

    def rotate(self, direction: int):
        if not self.current:
            return
        rotated = self.current.rotated(direction)
        # 简易墙踢
        for kick_x, kick_y in [(0,0), (1,0), (-1,0), (2,0), (-2,0), (0,-1)]:
            rotated.x = self.current.x + kick_x
            rotated.y = self.current.y + kick_y
            if not self._collides(rotated):
                self.current.rotation_index = rotated.rotation_index
                self.current.x = rotated.x
                self.current.y = rotated.y
                return

    def hold_piece(self):
        if self.hold_used or not self.current:
            return
        if self.hold is None:
            self.hold, self.current = self.current, self.queue.pop(0)
            self._refill_queue()
        else:
            self.hold, self.current = self.current, self.hold
        self.hold_used = True
        self.current.x = COLUMNS // 2 - 2
        self.current.y = -2
        if self._collides(self.current):
            self.game_over = True

    def tick(self, dt_ms: int):
        if self.game_over or self.paused:
            return
        self.drop_timer += dt_ms
        interval = max(100, self.drop_interval_ms - (self.level - 1) * 60)
        if self.drop_timer >= interval:
            self.drop_timer = 0
            if self._collides(self.current, dy=1):
                self._lock_piece()
            else:
                self.current.y += 1

    def _collides(self, piece: Piece, dx=0, dy=0) -> bool:
        for bx, by in piece.blocks:
            x = piece.x + bx + dx
            y = piece.y + by + dy
            if x < 0 or x >= COLUMNS or y >= ROWS:
                if y < 0:
                    # 顶部区域允许未落入的方块继续
                    continue
                return True
            if y >= 0 and self.board[y][x] is not None:
                return True
        return False

    def _lock_piece(self):
        for bx, by in self.current.blocks:
            x = self.current.x + bx
            y = self.current.y + by
            if 0 <= x < COLUMNS and 0 <= y < ROWS:
                self.board[y][x] = self.current.color
        cleared = self._clear_lines()
        self._update_score_level(cleared)
        self.spawn()

    def _clear_lines(self) -> int:
        new_board = [row for row in self.board if any(cell is None for cell in row)]
        cleared = ROWS - len(new_board)
        for _ in range(cleared):
            new_board.insert(0, [None for _ in range(COLUMNS)])
        self.board = new_board
        self.lines_cleared += cleared
        return cleared

    def _update_score_level(self, cleared: int):
        if cleared == 1:
            self.score += 100 * self.level
        elif cleared == 2:
            self.score += 300 * self.level
        elif cleared == 3:
            self.score += 500 * self.level
        elif cleared == 4:
            self.score += 800 * self.level
        self.level = 1 + self.lines_cleared // 10

    # ------------------------------
    # 绘制
    # ------------------------------
    def draw(self, screen: pygame.Surface):
        screen.fill(BLACK)
        # 井框背景
        pygame.draw.rect(screen, DARK, Rect(PLAYFIELD_X-2, PLAYFIELD_Y-2, PLAYFIELD_WIDTH+4, PLAYFIELD_HEIGHT+4), border_radius=6)
        # 网格
        for r in range(ROWS):
            for c in range(COLUMNS):
                x = PLAYFIELD_X + c * CELL_SIZE
                y = PLAYFIELD_Y + r * CELL_SIZE
                pygame.draw.rect(screen, GRAY, Rect(x, y, CELL_SIZE, CELL_SIZE), 1)
        # 固定方块
        for r in range(ROWS):
            for c in range(COLUMNS):
                color = self.board[r][c]
                if color is not None:
                    self._draw_cell(screen, c, r, color)
        # 当前方块
        if self.current:
            for bx, by in self.current.blocks:
                x = self.current.x + bx
                y = self.current.y + by
                if y >= 0:
                    self._draw_cell(screen, x, y, self.current.color)
            # 幽灵影子
            ghost_y = self.current.y
            while not self._collides(self.current, dy=(ghost_y - self.current.y + 1)):
                ghost_y += 1
            for bx, by in self.current.blocks:
                x = self.current.x + bx
                y = ghost_y + by
                if y >= 0:
                    self._draw_cell(screen, x, y, self.current.color, ghost=True)

        # 侧栏
        self._draw_side_panel(screen)

        if self.game_over:
            self._draw_center_text(screen, 'Game Over - R 重开 / Q 退出')
        elif self.paused:
            self._draw_center_text(screen, 'Paused - P 继续')

    def _draw_cell(self, screen: pygame.Surface, grid_x: int, grid_y: int, color, ghost=False):
        x = PLAYFIELD_X + grid_x * CELL_SIZE
        y = PLAYFIELD_Y + grid_y * CELL_SIZE
        rect = Rect(x+1, y+1, CELL_SIZE-2, CELL_SIZE-2)
        if ghost:
            s = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA)
            s.fill((*color, 70))
            screen.blit(s, (rect.x, rect.y))
        else:
            pygame.draw.rect(screen, color, rect, border_radius=4)
            pygame.draw.rect(screen, (0,0,0), rect, 2, border_radius=4)

    def _draw_side_panel(self, screen: pygame.Surface):
        panel_x = PLAYFIELD_X + PLAYFIELD_WIDTH + CELL_SIZE // 2
        panel_w = SIDE_PANEL_W_PX - CELL_SIZE  # 给边距留出一个CELL_SIZE
        pygame.draw.rect(screen, DARK, Rect(panel_x-2, PLAYFIELD_Y-2, panel_w+4, PLAYFIELD_HEIGHT+4), border_radius=6)
        if not self.font:
            self.font = pygame.font.SysFont('consolas', 20)
        title = self.font.render('Next', True, WHITE)
        screen.blit(title, (panel_x, PLAYFIELD_Y))
        # 下一个队列预览(取前3个)
        preview_y = PLAYFIELD_Y + 30
        for idx, piece in enumerate(self.queue[:3]):
            self._draw_mini_piece(screen, piece, panel_x + 10, preview_y + idx * 90)

        # Hold
        hold_title = self.font.render('Hold', True, WHITE)
        screen.blit(hold_title, (panel_x, preview_y + 3 * 90))
        if self.hold:
            self._draw_mini_piece(screen, self.hold, panel_x + 10, preview_y + 3 * 90 + 24)

        # 分数等级
        info_y = preview_y + 3 * 90 + 120
        info_lines = [
            f'Score: {self.score}',
            f'Level: {self.level}',
            f'Lines: {self.lines_cleared}',
        ]
        for i, text in enumerate(info_lines):
            # 根据侧栏宽度自适应缩小字号,避免长数字截断
            max_width = panel_w - 20
            font_size = 20
            while font_size >= 12:
                tmp_font = pygame.font.SysFont('consolas', font_size)
                tmp_surf = tmp_font.render(text, True, WHITE)
                if tmp_surf.get_width() <= max_width:
                    break
                font_size -= 1
            screen.blit(tmp_surf, (panel_x, info_y + i * 24))

    def _draw_mini_piece(self, screen: pygame.Surface, piece: Piece, x: int, y: int):
        # 在 4x4 小矩阵内绘制
        scale = CELL_SIZE // 2
        offset_x = x
        offset_y = y
        for bx, by in piece.blocks:
            rect = Rect(offset_x + bx * scale, offset_y + by * scale, scale-2, scale-2)
            pygame.draw.rect(screen, piece.color, rect, border_radius=3)
            pygame.draw.rect(screen, (0,0,0), rect, 1, border_radius=3)

    def _draw_center_text(self, screen: pygame.Surface, text: str):
        if not self.font:
            self.font = pygame.font.SysFont('consolas', 22)
        surf = self.font.render(text, True, WHITE)
        rect = surf.get_rect(center=(PLAYFIELD_X + PLAYFIELD_WIDTH//2, PLAYFIELD_Y + PLAYFIELD_HEIGHT//2))
        screen.blit(surf, rect)


def main():
    pygame.init()
    pygame.display.set_caption('俄罗斯方块 - Python Pygame')
    
    # 先创建一个暂时窗口以初始化字体测量(某些平台需要窗口存在)
    temp_screen = pygame.display.set_mode((800, 600))
    measure_font = pygame.font.SysFont('consolas', 20)
    # 预估最大文案宽度:"Score: " + 20 位数字(使用 '9' 作为最宽数字)
    sample_text = 'Score: ' + ('9' * 20)
    text_width = measure_font.render(sample_text, True, (255,255,255)).get_width()
    global SIDE_PANEL_W_PX, WIDTH
    SIDE_PANEL_W_PX = max(SIDE_PANEL_MIN_PX, text_width + 20)  # 两侧留 20px 余量
    WIDTH = PLAYFIELD_X + PLAYFIELD_WIDTH + SIDE_PANEL_W_PX + CELL_SIZE  # 右侧再给一点外边距
    
    # 重新设置为目标窗口大小
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()

    game = Game()

    fall_event = pygame.USEREVENT + 1
    pygame.time.set_timer(fall_event, 100)  # 更细粒度的tick,由Game内部节流

    running = True
    while running:
        dt_ms = clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == fall_event:
                game.tick(100)
            elif event.type == pygame.KEYDOWN:
                if event.key in (pygame.K_ESCAPE, pygame.K_q):
                    running = False
                elif event.key == pygame.K_p:
                    game.paused = not game.paused
                elif event.key == pygame.K_r:
                    game.__init__()
                elif not game.game_over and not game.paused:
                    if event.key == pygame.K_LEFT:
                        game.move(-1)
                    elif event.key == pygame.K_RIGHT:
                        game.move(1)
                    elif event.key == pygame.K_DOWN:
                        game.soft_drop()
                    elif event.key == pygame.K_UP:
                        game.rotate(1)
                    elif event.key == pygame.K_z:
                        game.rotate(-1)
                    elif event.key == pygame.K_SPACE:
                        game.hard_drop()
                    elif event.key == pygame.K_c:
                        game.hold_piece()

        # 长按处理(仅软降)
        if not game.game_over and not game.paused:
            keys = pygame.key.get_pressed()
            if keys[pygame.K_DOWN]:
                game.soft_drop()

        game.draw(screen)
        pygame.display.flip()

    pygame.quit()
    sys.exit()


if __name__ == '__main__':
    main()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 「工具协作」:CodeBuddy 助力开发效率提升的真实案例
    • ①腾讯云userdata初始化windows数据盘的需求,用CodeBuddy(我选的GPT5)完美实现,只两三个交互调试就OK了,惊艳!
    • ②用CodeBuddy一句话生成俄罗斯方块游戏,简单几次提修改要求后,达到完美(我只会扫雷、俄罗斯方块这2个简单的游戏,其他的不会玩),结尾附CodeBuddy生成的源码,我一个字母都没改!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档