这是一个简单的俄罗斯方块游戏,它可以在命令行中运行。您可以使用箭头键来移动块,空格键来快速下降块,R键来旋转块。游戏将在碰撞或填满一行时结束。
import random
class Tetris:
def __init__(self):
self.width = 10
self.height = 20
self.board = [[0 for x in range(self.width)] for y in range(self.height)]
self.score = 0
self.piece = None
self.piece_x = 0
self.piece_y = 0
self.piece_rotation = 0
self.piece_types = [
[[1, 1, 1], [0, 1, 0]],
[[0, 2, 2], [2, 2, 0]],
[[3, 3, 0], [0, 3, 3]],
[[4, 0, 0], [4, 4, 4]],
[[0, 0, 5], [5, 5, 5]],
[[6, 6], [6, 6]]
]
self.new_piece()
def new_piece(self):
self.piece = random.choice(self.piece_types)
self.piece_x = self.width // 2 - len(self.piece[0]) // 2
self.piece_y = 0
self.piece_rotation = 0
def rotate_piece(self):
old_rotation = self.piece_rotation
self.piece_rotation = (self.piece_rotation + 1) % 4
if self.collides():
self.piece_rotation = old_rotation
def move_piece(self, dx):
old_x = self.piece_x
self.piece_x += dx
if self.collides():
self.piece_x = old_x
def drop_piece(self):
while not self.collides():
self.piece_y += 1
self.piece_y -= 1
self.lock_piece()
def lock_piece(self):
for y in range(len(self.piece)):
for x in range(len(self.piece[y])):
if self.piece[y][x] != 0:
self.board[self.piece_y + y][self.piece_x + x] = self.piece[y][x]
self.new_piece()
def collides(self):
for y in range(len(self.piece)):
for x in range(len(self.piece[y])):
if self.piece[y][x] != 0:
board_x = self.piece_x + x
board_y = self.piece_y + y
if board_x < 0 or board_x >= self.width or board_y < 0 or board_y >= self.height or self.board[board_y][board_x] != 0:
return True
return False
def clear_lines(self):
lines_cleared = 0
for y in range(self.height):
if all(self.board[y]):
self.board.pop(y)
self.board.insert(0, [0 for x in range(self.width)])
lines_cleared += 1
self.score += lines_cleared ** 2
def print_board(self):
for y in range(len(self.board)):
for x in range(len(self.board[y])):
if self.board[y][x] == 0:
print('.', end='')
else:
print('#', end='')
print()
def run(self):
while True:
self.print_board()
print('Score:', self.score)
print('Use arrow keys to move, space to drop, and R to rotate')
command = input()
if command == 'left':
self.move_piece(-1)
elif command == 'right':
self.move_piece(1)
elif command == 'down':
self.drop_piece()
elif command == 'rotate':
self.rotate_piece()
elif command == 'quit':
break
self.clear_lines()
if self.collides():
print('Game over!')
break
if __name__ == '__main__':
game = Tetris()
game.run()