pygame2D我的世界简单版

import random
import pygame
from pygame.locals import *
form player import Player    # 导入Player玩家类

TILE_SIZE = 30
STEVE_SPEED = 30
SIZE = SCREEN_WIDTH,SCREEN_HEIGHT = 900,750
TRAY_HEIGHT = 120
ROWS = SCREEN_HEIGHT // TILE_SIZE
COLS = SCREEN_WIDTH // TILE_SIZE

# 图片加载字典
block_images = {
             'DIRT':pygame.image.load('blocks/dirt.png'),
             'GRASS':pygame.image.load('blocks/grass.png'),
             'COAL':pygame.image.load('blocks/coal.png'),
             'WOOD' : pygame.image.load('blocks/wood.png'),
             'SAND' : pygame.image.load('blocks/sand.png'),
             'ROCK' : pygame.image.load('blocks/rock.png'),
             'HEAD' : pygame.image.load('blocks/head.png'),
             'FACE' : pygame.image.load('blocks/face.png'),
             'BODY' : pygame.image.load('blocks/body.png'),
             'LEG' : pygame.image.load('blocks/leg.png'),
             'FOOT' : pygame.image.load('blocks/foot.png'),
             'WATER' : pygame.image.load('blocks/water.png')
            }

animal_images = {  
             'spide':pygame.image.load('spide.png')
             
             }
# 爆炸图像表
explosion_images = [pygame.image.load(f'explosion/{i}.gif') for i in range(6)]
              

class Block(pygame.sprite.Sprite):
    """方块类"""
    cors = []                             # 所有方块坐标表
    def __init__(self,master,group):
        pygame.sprite.Sprite.__init__(self)
        self.image_index = random.choice(list(block_images.keys()))
        self.image = block_images[self.image_index]                 
        self.rect = self.image.get_rect()        
        # 产生不同的坐标点,防止产生相同的,所以用了类变量
        # 如果有相同的则再次产生
        while True:
            x = TILE_SIZE * random.randint(0,COLS)
            y = TILE_SIZE * random.randint(0,ROWS-1)
            if (x,y) in Block.cors:continue
            Block.cors.append((x,y))
            self.rect.left = x
            self.rect.top = y
            break
        self.group = group
        self.group.add(self)               # 把自己加入到组中
        
class Spide(pygame.sprite.Sprite):
    """蜘蛛类,它一生成会自动攻击史蒂夫,给蜘蛛加上碰到边缘就反弹等AI行为"""
    def __init__(self,position,image,group):
        """image:蜘蛛的surface"""
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.topleft = position
        self.dx = random.randint(-5,5)
        self.dy = random.randint(-5,5)
        group.add(self)                  # 添加到蜘蛛组
        
    def update(self):
        if random.randint(1,30):
            self.dx = random.randint(-5,5)
            self.dy = random.randint(-5,5)
            self.rect.move_ip(self.dx,self.dy)
        

class Explosion(pygame.sprite.Sprite):
    """爆炸类"""
    def __init__(self,position,screen,group):
       """参数说明:
       position:爆炸的位置
       images:surface对象列表
       group:所在的组
       screen:在这个面上渲染
       """
       pygame.sprite.Sprite.__init__(self)
       self.screen = screen                     # 能访问屏幕
       self.group = group
       group.add(self)                          # 把自己加到组里面去
       self.images = explosion_images           # 造型,已经用pygame.image.load转换成surface有
       self.index = 0
       self.amounts = len(self.images)              
       self.rects = [image.get_rect() for image in self.images]  # 矩形对象列表        
       for rect in self.rects: rect.center = position
       self.interval = 2                         # 切换造型延时
       self.counter = 0                          # 切换造型延时计数器
      
    def draw(self):
        """在screen上渲染""" 
        if self.index < self.amounts:
           self.screen.blit(self.images[self.index],self.rects[self.index]) # 在screen上渲染自己
           if self.counter < self.interval:      # 起到时间间隔作用                                      
              self.counter += 1
           else:            
              self.counter = 0
              self.index = self.index + 1        # 超过则索引加1,下一帧图则会显示       
        else:
           
           self.group.remove(self)
    
class Bullet(pygame.sprite.Sprite):
    """子弹类,史蒂夫按空格会发射子弹"""
    def __init__(self,master):
        """master:史蒂夫"""
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10,10))
        self.rect = self.image.get_rect()
        self.direction = master.direction
        self.rect.center = master.rect.center
        
        

class House(pygame.sprite.Sprite):    
    pass
  

def make_background():
    """画格子,做为背景,返回一个surface"""
    color = (25,95,12)
    surface = pygame.Surface(SIZE)
    surface.fill((25,105,0))
    # 画横线
    for n in range(1,1+SCREEN_HEIGHT//TILE_SIZE):
        y =  n * TILE_SIZE
        start_pos = (0,y)
        end_pos = (SCREEN_WIDTH,y)
        pygame.draw.line(surface, color, start_pos, end_pos)
    # 画竖线 
    for n in range(1,1+SCREEN_WIDTH//TILE_SIZE ):
        x =  n * TILE_SIZE
        start_pos = (x,0)
        end_pos = (x,SCREEN_HEIGHT)
        pygame.draw.line(surface, color, start_pos, end_pos)
        
    return surface       
        

def main():

    
    house_images = ["house/house_open.png","house/house_close.png"] 
    steve_images = ["player/player_up.png","player/player_down.png","player/player_left.png","player/player_right.png"]
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT+TRAY_HEIGHT))
    pygame.display.set_caption("pygame我的世界简单版")

    block_group = pygame.sprite.Group()    # 方块组
    spide_group = pygame.sprite.Group()    # 蜘蛛组
    explosion_group = pygame.sprite.Group()    # 爆炸组
    
    background = make_background()         # 产生背景图
    tip_tray = pygame.image.load("tray.png")
    keyimage = pygame.image.load("key.png")

    # 新建房子,有两个造型
    house_images = [pygame.image.load(image) for image in house_images]    
    house = House(house_images)

    steve_position = 2 * TILE_SIZE, SCREEN_HEIGHT - 2 * TILE_SIZE
    steve_images = [pygame.image.load(image).convert_alpha() for image in steve_images]    
    steve = Player(steve_images,steve_position,house,screen,block_group,spide_group,explosion_group)
    
    [Block(steve,block_group)for i in range(100)] # 生成一百个方块

    clock = pygame.time.Clock()
    running = True
    
    while running:                          # 尽量缩短while循环体长度
        event = pygame.event.poll()         # 从队列取一个事件
        if event.type == QUIT:running = False
        if event.type == KEYDOWN:
            steve.keypress_check(event)      # 按键检测会调用update更新坐标等            
            steve.house_detect()             # 是否在房子里外检测         

        spide_group.update()
        
        screen.blit(background,(0,0))        # 画背景
        screen.blit(tip_tray,(0,SCREEN_HEIGHT))
        block_group.draw(screen)             # 画所有方块 
        screen.blit(house.image,house.rect)  # 画房子
        spide_group.draw(screen)             # 画所有蜘蛛
        screen.blit(steve.image,steve.rect)  # 画史蒂夫
        
        [bomb.draw()  for bomb in  explosion_group] # 这里不用group的draw方法,因为它要切换造型
              
        
        if steve.key ==  3 :  screen.blit(keyimage,(SCREEN_WIDTH-100,SCREEN_HEIGHT+30))
        
        pygame.display.update()
        clock.tick(60)
        
    pygame.quit()
        

if __name__ == "__main__":

    main()
        















    
    

pygame2D我的世界简单版