码迷,mamicode.com
首页 > 编程语言 > 详细

童年的记忆——如何用python写一个俄罗斯方块小游戏!

时间:2021-01-11 10:37:11      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:def   ash   学习python   main   order   oca   分隔线   enum   title   

谈到记忆里的小游戏,俄罗斯方块是大家一定会想到的一款游戏,自己写出来的应该玩起来更有感觉,然后就写了一个俄罗斯方块的游戏
给大家分享一下这个游戏的源码

先用python创建一个py文件

定义这次程序所需要的类

import sys

import time

import pygame

from pygame.localsimport *

import blocks

然后写出它所需要的模块

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 的字体颜色


# 画背景

```python

```python
def _draw_background(screen):
    # 填充背景色
    screen.fill(BG_COLOR)
    # 画游戏区域分隔线
    pygame.draw.line(screen, BORDER_COLOR,
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)

# 画网格线

```python
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_game_area(screen, game_area):
    if game_area:
        for i, row in enumerate(game_area):
            for j, cell in enumerate(row):
                if cell != ‘.‘:
                    pygame.draw.rect(screen, BLOCK_COLOR, (j * SIZE, i * SIZE, SIZE, SIZE), 0)

画单个方块

def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):
    if block:
        for i in range(block.start_pos.Y, block.end_pos.Y + 1):
            for j in range(block.start_pos.X, block.end_pos.X + 1):
                if block.template[i][j] != ‘.‘:
                    pygame.draw.rect(screen, BLOCK_COLOR,
                                     (offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + i) * SIZE, SIZE, SIZE), 0)

画得分等信息

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‘下一个:‘)

if __name__ == ‘__main__‘:
    main()

这样就可以写出来一个十分简单的俄罗斯方块啦,是不是觉得还不错呢!

技术图片
image.png

总结

以上就是俄罗斯方块的源码过程,大家可以写一下玩一玩
我是白白,一个喜欢学习喜欢编程的年轻人
想学习python的可以关注私信我哦~
欢迎小白、萌新、大佬加入我们
小白学习交流基地【(九七四)(七二四)(八九四)】

童年的记忆——如何用python写一个俄罗斯方块小游戏!

标签:def   ash   学习python   main   order   oca   分隔线   enum   title   

原文地址:https://www.cnblogs.com/whitebaibaibaibaibai/p/14247539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!