机器人
积分排行榜
Scratch
积分排行榜
Python
在线答题
积分排行榜
活跃排行榜
打字练习
Microbit
C++
在线答题
积分排行榜
活跃排行榜
网盘
积分
未登录
未登录
登录学习
作者:
李禹墨
更新时间:
2025-03-30 20:06
浏览:
49次
点赞:
0次
热度:
20
import random from PIL import Image, ImageDraw # 定义六种不同的俄罗斯方块形状 shapes = [ [[1, 1, 1], [1, 1, 1]], # I型 [[1, 1], [1, 1]], # O型 [[1, 1, 1], [0, 1, 0], [1, 1, 1]],# T型 [[1, 1, 1, 1]], # L型(向右下) [[1, 1, 1], [1, 0, 1]], # J型 [[1, 1], [1, 1]] # S型(横向居中) ] # 游戏区域大小 WIDTH = 20 HEIGHT = 30 # 方块颜色 BLOCK_SIZE = 40 BACK_COLOR = (255, 192, 203) BLUE = (0, 0, 255) # 初始化游戏 def __init__(): global BLOCKS, FPS, score BLOCKS = [] for shape in shapes: new_block = [] for row in shape: for cell in row: if cell > 0: new_block.append((cell - 1, cell)) if new_block: BLOCKS.append(new_block) FPS = 2 score = 0 # 创建游戏窗口 def create_window(): win = Image.new('RGB', (WIDTH * BLOCK_SIZE, HEIGHT * BLOCK_SIZE), BACK_COLOR) draw = ImageDraw.Draw(win) return win, draw # 初始化游戏并显示界面 def init_game(): global BLOCKS, FPS, score win, draw = create_window() # 添加初始块 initial_shape = random.choice(shapes) add_block(initial_shape, 0, (WIDTH - len(initial_shape[0])) // 2, win, draw) win.show() win抓住 win_key_up = None # 游戏循环函数 def game_loop(): global score win, draw = create_window() # 添加新的块 new_block = random.choice(shapes) add_block(new_block, 0, (WIDTH - len(new_block[0])) // 2, win, draw) if check_collision(new_block): game_over() while True: # 处理玩家的按键输入 key = get_key press() # 游戏逻辑 if key == '\x07': # 按esc退出 return elif key == ' ': # 按空格暂停/继续 pause() # 主循环:移动块 move_blocks() draw_board(win, draw) score += 1 print("游戏结束,最终得分:" + str(score)) # 添加块到指定位置 def add_block(shape, x, y, win, draw): for row in shape: for col in row: if col > 0: draw.rectangle( (x * BLOCK_SIZE + col * BLOCK_SIZE, y * BLOCK_SIZE + row[0] * BLOCK_SIZE, (x + 1) * BLOCK_SIZE + col * BLOCK_SIZE, (y + 1) * BLOCK_SIZE + row[0] * BLOCK_SIZE), fill=BLUE ) # 检查块是否发生碰撞 def check_collision(block): for row in block: for col in row: if col > 0 and block[row][col] - 1 < 0 or block[row][col] + 1 >= len(block) - row: return True return False # 移动块 def move_blocks(): global BLOCKS while True: for i in range(len(BLOCKS)): if check_collision(BLOCKS[i]): del BLOCKS[i] break new_block = False for shape in shapes: if len(BLOCKS) == 0 or (WIDTH - 1) // 2 >= max(x for block in BLOCKS for x, y in block): new_block = [shape] break if new_block and not check_collision(new_block[0]): BLOCKS.append(new_block) draw_board(win, draw) # 移动块到指定位置 def move_block(x, y): for row in range(len(block)): for col in block[row]: pass # 主函数 if __name__ == "__main__": init_game() game_loop()
点赞成功
分享作品
×