Pygame 打方块

                                   

import traceback
import random
import pygame
from pygame.locals import *

pygame.display.init()
pygame.font.init()

sizes = {
    "screen" : ( 300, 480 )
}

colors = {
    "font" : ( 138, 69, 252 ),
    "block" : ( 200, 200, 200 ),
    "block_border" : ( 100, 100, 100 ),
    "border" : ( 52, 135, 184 ),
    "background" : ( 255, 255, 255 )
}

fonts = {
    "18" : pygame.font.SysFont( "Times New Roman", 18, bold = True ),
    "24" : pygame.font.SysFont( "Times New Roman", 24, bold = True )
}

screen = pygame.display.set_mode( sizes["screen"], 0, 32 )
clock  = pygame.time.Clock()

LOW    = 1
MIDDLE = 2
HIGH   = 3

class Block( object ):

    def __init__( self, game, col ):
        self.x = game.XS[col] + game.BORDER_WIDTH / 2 + 1
        self.y = -200
        self.height = game.BLOCK_HEIGHT
        self.width  = game.BLOCK_WIDTH
        self.speed  = game.SPEED
        self.column = col

    def draw( self ):
        rect = ( self.x, self.y, self.width, self.height )
        pygame.draw.rect( screen, colors["block"], rect )
        pygame.draw.rect( screen, colors["block_border"], rect, 0  )

    def move( self ):
        self.y += self.speed * 1
        if self.y + self.height >= sizes["screen"][1]:
            return False
        return True

class Game( object ):

    BORDER_WIDTH = 10

    def __init__( self, level ):
        if level == LOW:
            Game.COLUMN_NUM = 4
            Game.BLOCK_HEIGHT = 100
            Game.SPEED = 1
        elif level == MIDDLE:
            Game.COLUMN_NUM = 5
            Game.BLOCK_HEIGHT = 80
            Game.SPEED = 2
        elif level == HIGH:
            Game.COLUMN_NUM = 6
            Game.BLOCK_HEIGHT = 60
            Game.SPEED = 3

        Game.BLOCK_WIDTH, Game.XS = Game.calculate( sizes["screen"][0],
                                                    Game.COLUMN_NUM,
                                                    Game.BORDER_WIDTH )
        self.blocks = []

    def move( self ):
        for block in self.blocks:
            if not block.move():
                return False
        return True

    def create( self ):
        self.can_product = [ True for i in range( Game.COLUMN_NUM ) ]
        added = []
        for col in xrange( Game.COLUMN_NUM ):
            if random.random() < 0.01:
                added.append( Block( self, col ) )
        for block in self.blocks:
            if block.y < 0:
                self.can_product[block.column] = False
        added = filter( lambda x : self.can_product[x.column], added )
        self.blocks.extend( added )

    def draw( self ):
        screen.fill( colors["background"] )
        for x in Game.XS:
            pygame.draw.line( screen, colors["border"],
                              ( x, 0 ),
                              ( x, sizes["screen"][1] ),
                              Game.BORDER_WIDTH )
        for block in self.blocks:
            block.draw()
        pygame.display.update()

    def cin( self ):
        for e in pygame.event.get():
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    return False
            elif e.type == MOUSEBUTTONDOWN:
                if e.button == 1:
                    mouse_position = pygame.mouse.get_pos()
                    for block in self.blocks:
                        if block.x <= mouse_position[0] <= block.x + block.width:
                            if block.y <= mouse_position[1] <= block.y + block.height:
                                self.blocks.remove( block )
                                break
        return True

    def run( self ):
        while True:
            if not self.cin():
                return False
            if not self.move():
                return False
            self.draw()
            self.create()
            clock.tick( 100 )

    @staticmethod
    def calculate( screen_width, column_num, border_width ):
        xs = []
        begin_x = border_width / 2 - 1
        column_width = float( screen_width - ( 1 + column_num ) * border_width ) / column_num
        for i in range( column_num + 1 ):
            xs.append( begin_x + ( column_width + border_width ) * i )
        return column_width + 1, xs

blink = -30

def main( level ):

    def menu_draw():
        global blink
        screen.fill( colors["background"] )
        screen.blit( fonts["24"].render( "A Easy Game", True, colors["font"] ),
                     ( 65, 150 ) )
        if blink < 0:
            screen.blit( fonts["18"].render( "Press Any Key", True, colors["font"] ),
                         ( 80, 200 ) )
        blink += 1
        if blink == 30:
            blink = -30
        pygame.display.update()

    def menu_cin():
        for e in pygame.event.get():
            mouse_pos = pygame.mouse.get_pos()
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    return False
                game = Game( level )
                score = game.run()
                if score == False:
                    return False
        return True 

    pygame.event.set_grab( True )
    while True:
        if not menu_cin():
            break
        menu_draw()
        clock.tick( 60 )
    pygame.event.set_grab( False )
    pygame.quit()

if __name__ == '__main__':
    try:
        level = LOW
        main( level )
    except:
        traceback.print_exc()
        pygame.quit()
        input()
时间: 2024-08-26 12:18:32

Pygame 打方块的相关文章

pygame写贪吃蛇

python小白尝试写游戏.. 学了点pygame不知道那什么练手好,先拿贪吃蛇开刀吧. 一个游戏可以粗略的分为两个部分: 数据(变量) 处理数据(函数,方法) 设计变量 首先预想下,画面的那些部分需要存储在变量里 整个画面上只会有矩形,而且这些矩形整整齐齐,大小相等,原本一个矩形需要四个变量表示位置,这里,只需要两个变量(行数,列数)就能表示方块的位置 蛇头,食物可以用二元元组表示,蛇身的数量不确定,只能用包含数个元组的列表表示 另外设定窗口大小800x600,每个方块都是50x50 impo

Python和Pygame游戏开发 pdf

Python和Pygame游戏开发 目录 第1章 安装Python和Pygame 11.1 预备知识 11.2 下载和安装Python 11.3 Windows下的安装说明 11.4 Mac OS X上的安装说明 21.5 Ubuntu和Linux上的安装说明 21.6 启动Python 21.7 安装Pygame 31.8 如何阅读本书 41.9 特色的程序 41.10 下载图形文件和声音文件 41.11 行号和空格 41.12 图书中的文本折行 51.13 在线检查代码 51.14 配套网站

python pygame做的小游戏(贪吃蛇)

# pygame游戏库,sys操控python运行的环境 import pygame, sys, random # 这个模块包含所有pygame所使用的常亮 from pygame.locals import * # 1,定义颜色变量 # 0-255 0黑色 255白色 redColor = pygame.Color(255, 0, 0) # 背景为黑色 blackColor = pygame.Color(0, 0, 0) # 贪吃蛇为白色 whiteColor = pygame.Color(2

win7/64+pip+pygame=pygame安装

2016/01/09 安装pygame win7/64,之前python版本为3.4 pygame下载地址: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame 因为需要兼容,所以下载pygame-1.9.2a0-cp34-none-win_amd64.whl 适合Python3.4的版本文件名中包含cp34,适合64位操作系统的版本,文件名中包含amd64: 选择开始>运行,输入cmd打开命令提示符,在命令提示符中输入: pip install

windows下python3.6版本安装pygame

参考:http://blog.csdn.net/a380331382/article/details/77063152 首先,进入这个网站:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame ,找到pygame?1.9.3?cp36?cp36m?win_amd64.whl 并下载,将该文件复制到项目文件夹下. windows+R打开运行,打开cmd,切换到项目文件夹下,输入Python -m pip install --user pygame-1.

pygame 练习之 PIE game (以及简单图形训练)

简单的大饼游戏,掌握pygame中直线以及圆弧的画法,以及对输入的响应. 1 import math 2 import pygame, sys 3 from pygame.locals import * 4 pygame.init() 5 screen = pygame.display.set_mode((600, 500)) 6 pygame.display.set_caption("The Pie Game -- Press 1 2 3 4") 7 myfont = pygame.

【python游戏编程之旅】第八篇---pygame游戏开发常用数据结构

本系列博客介绍以python+pygame库进行小游戏的开发.有写的不对之处还望各位海涵. 上一个博客我们一起学习了pygame中冲突检测技术:http://www.cnblogs.com/msxh/p/5027688.html 这次我们来一起学习在pygame游戏里面常用的一些数据结构: 数据,列表,元组,队列,栈. 一.数组与列表 数组可以理解为简化的列表.像我们之前使用的pygame.sprite.Group这样的精灵组,也是一个列表.列表的元素是可变的,它具有添加.删除.搜索.排序等多种

画方块

电脑附件的画图工具里,我们可以在画布上用鼠标随意选取矩形的选区. 自己用js写了一个简单的可以在页面上用鼠标随意画方块的功能. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999

【python游戏编程之旅】第二篇--pygame中的IO、数据

本系列博客介绍以python+pygame库进行小游戏的开发.有写的不对之处还望各位海涵. 在上一篇中,我们介绍了pygame的入门操作http://www.cnblogs.com/msxh/p/4966899.html 这次我们将一起学习pygame中的IO.数据和更多关于字体打印的知识. 一.python输入输出 1.输出 python一次可以打印多个变量,只要用一个逗号将每个变量隔开就可以了.比如: A = 123 B = "ABC" C = 456 D = "DEF&