game_class,熟悉sprite的使用

http://programarcadegames.com/python_examples/show_file.php?file=game_class_example.py


game_class_example.py

# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://programarcadegames.com/
# http://simpson.edu/computer-science/
 
# Explanation video: http://youtu.be/O4Y5KrNgP_c
 
import pygame
import random
 
#--- Global constants ---
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)
 
SCREEN_WIDTH  = 700
SCREEN_HEIGHT = 500
 
# --- Classes ---
 
# This class represents a simple block the player collects
class Block(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) 
        self.image = pygame.Surface([20,20])
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
 
    # Called when the block is 'collected' or falls off
    # the screen
    def reset_pos(self):
        self.rect.y = random.randrange(-300, -20)
        self.rect.x = random.randrange(SCREEN_WIDTH)        
 
    # Automatically called when we need to move the block
    def update(self):
        self.rect.y += 1
         
        if self.rect.y > SCREEN_HEIGHT + self.rect.height:
            self.reset_pos()
 
# This class represents the player
class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) 
        self.image = pygame.Surface([20,20])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
 
    def update(self):
        pos = pygame.mouse.get_pos()
        self.rect.x = pos[0]
        self.rect.y = pos[1]        
         
# This class represents an instance of the game. If we need to
# reset the game we'd just need to create a new instance of this
# class.
class Game():
    # --- Class attributes. 
    # In this case, all the data we need 
    # to run our game.
     
    # Sprite lists
    block_list = None
    all_sprites_list = None
    player = None
     
    # Other data    
    game_over = False
    score = 0
     
    # --- Class methods
    # Set up the game
    def __init__(self):
        self.score = 0
        self.game_over = False
         
        # Create sprite lists
        self.block_list = pygame.sprite.Group()
        self.all_sprites_list = pygame.sprite.Group()
         
        # Create the block sprites
        for i in range(50):
            block = Block()
         
            block.rect.x = random.randrange(SCREEN_WIDTH)
            block.rect.y = random.randrange(-300,SCREEN_HEIGHT)
             
            self.block_list.add(block)
            self.all_sprites_list.add(block)
         
        # Create the player
        self.player = Player()
        self.all_sprites_list.add(self.player)
 
    # Process all of the events. Return a "True" if we need
    # to close the window.
    def process_events(self):
 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.game_over:
                    self.__init__()
         
        return False
 
    # This method is run each time through the frame. It
    # updates positions and checks for collisions.
    def run_logic(self):
         
        if not self.game_over:
            # Move all the sprites
            self.all_sprites_list.update()
             
            # See if the player block has collided with anything.
            blocks_hit_list = pygame.sprite.spritecollide(self.player, self.block_list, True)  
          
            # Check the list of collisions.
            for block in blocks_hit_list:
                self.score +=1
                print( self.score )
                 
            if len(self.block_list) == 0:
                self.game_over = True
                 
           
             
    # Display everything to the screen for the game.
    def display_frame(self, screen):
 
        screen.fill(WHITE)
         
        if self.game_over:
            #font = pygame.font.Font("Serif", 25)
            font = pygame.font.SysFont("serif", 25)
            text = font.render("Game Over, click to restart", True, BLACK)
            x = (SCREEN_WIDTH // 2) - (text.get_width() // 2)
            y = (SCREEN_HEIGHT // 2) - (text.get_height() // 2)
            screen.blit(text, [x, y])
         
        if not self.game_over:
            self.all_sprites_list.draw(screen)
             
        pygame.display.flip()
     
         
# --- Main Function ---
def main():
     
    # Initialize Pygame and set up the window
    pygame.init()
      
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
     
    pygame.display.set_caption("My Game")
    pygame.mouse.set_visible(False)
     
    # Create our objects and set the data
    done = False
    clock = pygame.time.Clock()
     
    # Create an instance of the Game class
    game = Game()
 
    # Main game loop
    while not done:
         
        # Process events (keystrokes, mouse clicks, etc)
        done = game.process_events()
         
        # Update object positions, check for collisions
        game.run_logic()
         
        # Draw the current frame
        game.display_frame(screen)
         
        # Pause for the next frame
        clock.tick(60)
         
    # Close window and exit    
    pygame.quit()
 
# Call the main function, start up the game
if __name__ == "__main__":
    main()

import pygame from game_items import * from game_hud import * from game_music import * class Game(object): """游戏类""" def __init__(self): self.main_window=pygame.display.set_mode(SCREEN_RECT.size) pygame.display.set_caption("Aircraft battle") self.is_game_over=False self.is_pause=False self.all_group = pygame.sprite.Group() self.enemies_group = pygame.sprite.Group() self.supplies_group = pygame.sprite.Group() GameSprite("background.png", 1, self.all_group) hero = GameSprite("mel.png", 0, self.all_group) hero.rect.center = SCREEN_RECT.center self.main_window = pygame.display.set_mode(SCREEN_RECT.size) pygame.display.set_caption("Aircraft battle") self.all_group.add(Background(False), Background(True)) def reset_game(self): """game restarts""" self.is_game_over=False self.is_pause=False def envent_handler(self): """如果监听到推出事件,返还Ture,否则返还False""" for event in pygame.event.get(): if event.type==pygame.QUIT: return True elif event.type==pygame.KEYDOWN and event.key==pygame.K_SPACE: if self.is_game_over: self.reset_game() else: self.is_pause=not self.is_pause def start(self): """strat game""" clock=pygame.time.Clock() while True: if self.envent_handler(): return if self.is_game_over: print("游戏已经结束,请按空格键继续游戏。**********") elif self.is_pause: print("游戏已经暂停,请按空格键继续游戏,**********") else: self.all_group.update() self.all_group.draw(self.main_window) pygame.display.update() clock.tick(60) if __name__ =='__main__': pygame.init() Game().start() pygame.quit()
07-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值