Python 俄罗斯方块游戏代码示例 - 基于 Pygame 库
以下是一个简单的俄罗斯方块的代码示例,基于 Pygame 库。
import pygame
import random
# 定义常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
FPS = 30
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 初始化pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
class Block(pygame.sprite.Sprite):
def __init__(self, color, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
def update(self):
self.rect.y += BLOCK_SIZE
class Tetris:
def __init__(self):
self.blocks = pygame.sprite.Group()
self.score = 0
self.current_block = None
def create_block(self):
shapes = [
[[1, 1, 1, 1]],
[[1, 1], [1, 1]],
[[1, 1, 0], [0, 1, 1]],
[[0, 1, 1], [1, 1, 0]],
[[1, 1, 1], [0, 1, 0]]
]
shape = random.choice(shapes)
color = random.choice([RED, GREEN, BLUE, YELLOW])
self.current_block = pygame.sprite.Group()
for y in range(len(shape)):
for x in range(len(shape[y])):
if shape[y][x] == 1:
block = Block(color, BLOCK_SIZE, BLOCK_SIZE)
block.rect.x = 4 * BLOCK_SIZE + x * BLOCK_SIZE
block.rect.y = y * BLOCK_SIZE
self.current_block.add(block)
self.blocks.add(block)
def check_collision(self):
for block in self.current_block:
if block.rect.y >= SCREEN_HEIGHT - BLOCK_SIZE:
return True
if pygame.sprite.spritecollide(block, self.blocks, False):
return True
return False
def update_score(self):
self.score += 10
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.current_block.update()
elif keys[pygame.K_RIGHT]:
self.current_block.update()
if self.check_collision():
self.create_block()
self.update_score()
self.blocks.update()
screen.fill(BLACK)
self.blocks.draw(screen)
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
if __name__ == '__main__':
tetris = Tetris()
tetris.run()
在这个游戏中,方块会从上方落下,玩家可以通过键盘的左右方向键控制方块的移动,当方块堆积到一定高度或者碰到其他方块时,会生成新的方块并计分。
原文地址: https://www.cveoy.top/t/topic/o7g5 著作权归作者所有。请勿转载和采集!