版权声明:原创不易,本文禁止抄袭、转载,侵权必究!
开发环境:python3.6.4
第三方库:pygame1.9.6
集成开发环境:PyCharm/Sublime Text
游戏初始化
SIZE = 30 # 每个小方格大小
BLOCK_HEIGHT = 25 # 游戏区高度
BLOCK_WIDTH = 10 # 游戏区宽度
BORDER_WIDTH = 4 # 游戏区边框宽度
BORDER_COLOR = (40, 40, 200) # 游戏区边框颜色
SCREEN_WIDTH = SIZE * (BLOCK_WIDTH + 5) # 游戏屏幕的宽
SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT # 游戏屏幕的高
BG_COLOR = (40, 40, 60) # 背景色
BLOCK_COLOR = (20, 128, 200) #
BLACK = (0, 0, 0)
RED = (200, 30, 30) # GAME OVER 的字体颜色
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('俄罗斯方块')
方块定义
# S形方块
S_BLOCK = [Block(['.OO',
'OO.',
'...'], Point(0, 0), Point(2, 1), 'S', 1),
Block(['O..',
'OO.',
'.O.'], Point(0, 0), Point(1, 2), 'S', 0)]
# Z形方块
Z_BLOCK = [Block(['OO.',
'.OO',
'...'], Point(0, 0), Point(2, 1), 'Z', 1),
Block(['.O.',
'OO.',
'O..'], Point(0, 0), Point(1, 2), 'Z', 0)]
判断是否可以旋转,下落,移动
def _judge(pos_x, pos_y, block):
nonlocal game_area
for _i in range(block.start_pos.Y, block.end_pos.Y + 1):
if pos_y + block.end_pos.Y >= BLOCK_HEIGHT:
return False
for _j in range(block.start_pos.X, block.end_pos.X + 1):
if pos_y + _i >= 0 and block.template[_i][_j] != '.' and game_area[pos_y + _i][pos_x + _j] != '.':
return False
return True
方块停靠
def _dock():
nonlocal cur_block, next_block, game_area, cur_pos_x, cur_pos_y, game_over, score, speed
for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
for _j in range(cur_block.start_pos.X, cur_block.end_pos.X + 1):
if cur_block.template[_i][_j] != '.':
game_area[cur_pos_y + _i][cur_pos_x + _j] = '0'
if cur_pos_y + cur_block.start_pos.Y <= 0:
game_over = True
else:
# 计算消除
remove_idxs = []
for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
if all(_x == '0' for _x in game_area[cur_pos_y + _i]):
remove_idxs.append(cur_pos_y + _i)
网格线
def _draw_gridlines(screen):
# 画网格线 竖线
for x in range(BLOCK_WIDTH):
pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1)
# 画网格线 横线
for y in range(BLOCK_HEIGHT):
pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1)
分数
def _draw_info(screen, font, pos_x, font_height, score):
print_text(screen, font, pos_x, 10, f'得分: ')
print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')
print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')
print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')
print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一个:')
点我观看视频,最下面有惊喜!
pygame游戏开发源码下载:
作者:小鸿的摸鱼日常,Goal:让编程更有趣!
原创微信公众号:『小鸿星空科技』,专注于算法、爬虫,网站,游戏开发,数据分析、自然语言处理,AI等,期待你的关注,让我们一起成长、一起Coding!
版权说明:本文禁止抄袭、转载 ,侵权必究!