• 12-2 游戏角色


    1. 项目

    找一幅你喜欢的游戏角色位图图像或将一幅图像转换为位图。创建一个类,将该角色绘制到屏幕中央,并将该图像的背景色设置为屏幕背景色,或将屏幕背景色设置为该图像的背景色。

    2. 代码

    •   game_role.py
    import sys
    import pygame
    from settings import Settings
    from ship import Ship
    
    
    def run_game():
        # 初始化pygame、设置和屏幕对象
        pygame.init()
        ai_settings = Settings()
        screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    
        pygame.display.set_caption("Alien Invasion")
        ship = Ship(screen)
    
        # 开始游戏的主循环
        while True:
    
            # 监视键盘和鼠标事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
            # 每次循环时都重绘屏幕
            screen.fill(ai_settings.bg_color)
            ship.blitme()
    
            # 让最近绘制的屏幕可见
            pygame.display.flip()
    
    run_game()
    
    •   settings.py
    class Settings():
        # 存储《外星人入侵》的所有设置的类
    
        def __init__(self):
            """初始化游戏的设置"""
            # 屏幕设置
            self.screen_width = 500
            self.screen_height = 300
            self.bg_color = (0, 0, 255)
    
    •   ship.py 
    import pygame
    
    class Ship():
    
        def __init__(self, screen):
            """初始化飞船并设置其初始位置"""
            self.screen = screen
    
            # 加载飞船图像并获取其外接矩形
            self.image = pygame.image.load('images/myplane2.bmp')
            self.rect = self.image.get_rect()
            self.screen_rect = screen.get_rect()
    
            # 将每艘新飞船放在屏幕底部中央
            self.rect.centerx = self.screen_rect.centerx
            self.rect.bottom = self.screen_rect.bottom
    
        def blitme(self):
            """在指定位置绘制飞船"""
            self.screen.blit(self.image, self.rect)
    

      

    3. 执行结果

      

  • 相关阅读:
    C#学习(二)之基础杂谈
    C#学习(一)之hello,world
    尚硅谷linux教程16-shell变量
    尚硅谷linux教程16-shell变量
    将博客搬至CSDN
    尚硅谷linux教程15 大数据 Shell编程
    linux服务器安装tomcat
    尚硅谷linux教程 javaEE定制篇 jdk安装
    尚硅谷linux教程14 yum
    尚硅谷linux教程13 RPM包管理
  • 原文地址:https://www.cnblogs.com/kevin-hou1991/p/15046626.html
Copyright © 2020-2023  润新知