Python学習実践一

19567 ワード

へび遊び
pycharm——pygame
game.py
import pygame  #   
from game_items import *  #      

class Game(object):  #    object ,    /   。
    def __init__(self):
        self.main_window = pygame.display.set_mode((640, 480))
        self.main_name = pygame.display.set_caption('   ')

        self.score_label = Label()  #     

        self.tip_label = Label(24, False)  #   &       

        self.is_game_over = True  #       
        self.is_pause = False  #       

        self.food = Food()

        self.snake = Snake()

    def start(self):
        clock = pygame.time.Clock()  #     

        while True:
            self.main_window.fill(BACKGROUND_COLOR)

            #     
            for event in pygame.event.get():
                if event.type == pygame.QUIT:  #   
                    return
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        return

                    elif event.key == pygame.K_SPACE:
                        if self.is_game_over:
                            self.reset_game()
                        else:
                            self.is_pause = not self.is_pause
                if not self.is_pause and not self.is_game_over:
                    if event.type == FOOD_UPDATE_EVENT:
                        self.food.random_rect()
                    elif event.type == SNAKE_UPDATE_EVENT:
                        self.is_game_over = not self.snake.update()
                    elif event.type == pygame.KEYDOWN:
                        if event.key in (pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT, pygame.K_UP):
                            self.snake.change_dir(event.key)

            #       
            self.score_label.draw('  : %d' % self.snake.score, self.main_window)
            #     &      
            if self.is_game_over:
                self.tip_label.draw('    ,         。', self.main_window)
            elif self.is_pause:
                self.tip_label.draw('    ,      。', self.main_window)
            #        (    )
            else:
                if self.snake.has_eat(self.food):
                    self.food.random_rect()

            self.food.draw(self.main_window)

            self.snake.draw(self.main_window)

            pygame.display.update()
            clock.tick(60)  #     (  )

    def reset_game(self):
        """      """

        self.is_pause = False
        self.is_game_over = False

        self.snake.reset_snake()
        self.food.random_rect()

if __name__ == '__main__':

    pygame.init()  #    pygame  

    #    
    Game().start()

    pygame.quit()  #   pygame  

game_items.py
import pygame
import random

BACKGROUND_COLOR = (232, 232, 232)
SCORE_TEXT_COLOR = (192, 192, 192)
TIP_TEXT_COLOR = (64, 64, 64)
SCREEN_RECT = pygame.Rect(0, 0, 640, 480)
RECT_SIZE = 20
FOOD_UPDATE_EVENT = pygame.USEREVENT  #       
SNAKE_UPDATE_EVENT = pygame.USEREVENT + 1  #      

class Label(object):
    def __init__(self, size=48, is_score=True):
        """
           
        :param is_score         
        """
        self.fond = pygame.font.SysFont('simhei', size)  #     fond  
        self.is_score = is_score

    def draw(self, text, window):
        #     
        color =SCORE_TEXT_COLOR if self.is_score else TIP_TEXT_COLOR
        text_surface = self.fond.render(text, True, color)  # self.fond   __init__       self.fond
        #          
        # text_rect = text_surface.get_rect()  #   get_rect        
        # window_rect = window.get_rect()
        # text_rect.y = window_rect.height - text_rect.height
        # text_rect.x = window_rect.width - text_rect.width
        #          
        text_rect = text_surface.get_rect()
        window_rect = window.get_rect()
        if self.is_score:
            text_rect.bottomleft = window_rect.bottomleft  # mid+  /top+  /bottom+  
        else:
            text_rect.center = window_rect.center
        #          
        window.blit(text_surface, text_rect)

class Food(object):
    def __init__(self):
        self.color = (255, 0, 0)
        self.score = 10
        self.rect = (0, 0, RECT_SIZE, RECT_SIZE)  #

        self.random_rect()

    def draw(self, window):
        pygame.draw.rect(window, self.color, self.rect)

        if self.rect.w < RECT_SIZE:  #     
            self.rect.inflate_ip(2, 2)

    def random_rect(self):
        col = SCREEN_RECT.w / RECT_SIZE - 1
        row = SCREEN_RECT.h / RECT_SIZE - 1

        x = random.randint(0, col) * RECT_SIZE
        y = random.randint(0, row) * RECT_SIZE

        self.rect = pygame.Rect(x, y, RECT_SIZE, RECT_SIZE)

        self.rect.inflate_ip(-RECT_SIZE, -RECT_SIZE)  #       

        pygame.time.set_timer(FOOD_UPDATE_EVENT, 30000)

class Snake(object):
    def __init__(self):
        """     """
        self.dir = pygame.K_RIGHT
        self.score = 0
        self.time_interval = 500
        self.color = (64, 64, 64)
        self.body_list = []

        self.reset_snake()

    def reset_snake(self):
        self.dir = pygame.K_RIGHT
        self.score = 0
        self.time_interval = 500

        self.body_list.clear()
        for _ in range(3):
            self.add_node()

    def add_node(self):
        if self.body_list:
            head = self.body_list[0].copy()
        else:
            head = pygame.Rect(-RECT_SIZE, 0, RECT_SIZE, RECT_SIZE)

        if self.dir == pygame.K_LEFT:
            head.x -= 20
        elif self.dir == pygame.K_RIGHT:
            head.x += 20
        elif self.dir == pygame.K_UP:
            head.y -= 20
        elif self.dir == pygame.K_DOWN:
            head.y += 20

        self.body_list.insert(0, head)

        pygame.time.set_timer(SNAKE_UPDATE_EVENT, self.time_interval)

    def draw(self, window):
        for idx, rect in enumerate(self.body_list):
            #   idx      idx==0  True    1;   False     
            #
            pygame.draw.rect(window, self.color, rect.inflate(-2, -2), idx == 0)
    #        ,       ,      

    def update(self):
        #      
        body_list_copy = self.body_list.copy()
        #     
        self.add_node()
        self.body_list.pop()  #         
        #     
        if self.is_dead():
            self.body_list = body_list_copy
            return False

        return True


    def change_dir(self, to_dir):
        hor_dirs = (pygame.K_LEFT, pygame.K_RIGHT)
        var_dirs = (pygame.K_UP, pygame.K_DOWN)
        if ((self.dir in hor_dirs and to_dir not in hor_dirs) or
                (self.dir in var_dirs and to_dir not in var_dirs)):

            self.dir = to_dir

    def has_eat(self, food):
        if self.body_list[0].contains(food.rect):
            self.score += food.score
            if self.time_interval > 100:
                self.time_interval -= 50
            self.add_node()

            return True
        return False

    def is_dead(self):
        head = self.body_list[0]

        if not SCREEN_RECT.contains(head):
            return True

        for body in self.body_list[1:]:
            if head.contains(body):
                return True
        return False

主にpygame内の操作を勉強します
ウィンドウ操作、テキストの描画、イメージのレンダリング、配置
イベントの傍受、画面のリフレッシュと表示、フィードバック操作
不足がありましたら、よろしくお愿いします.