学习Python本领高_Python制作的街机

"""
学习Python本领高.py,本程序操作一个小人上下午左右移动收集Python本领。
"""
import os
import time
import arcade
import random


TOTAL_TIME = 100            # 100秒时间
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "学习Python本领高"

COIN_SCALE = 0.5
COIN_COUNT = 2

MOVEMENT_SPEED = 2         # 移动速度常量

SKILLS = ['自动写作业','游戏开发','网站编程','数据库开发','指挥机器人']
SKILLS.extend(['人脸识别','自动下载','自动点赞','识别假粉丝','自动登陆'])
SKILLS.extend(['自动发帖子','自动买零食','自动点赞','识别假粉丝','自动登陆'])
SKILLS.extend(['数据处理','图形处理','自动控制','科学计算','成批处理文件'])
SKILLS.extend(['自动打怪','软件开发','手机APP制作','大型网站开发','制作搜索引擎'])
SKILLS.extend(['语音识别','自动加密','破解密码','数据采集','远程控制'])
SKILLS.extend(['趣味绘画','无人机控制','数据可视化','远程监控','系统运维'])
SKILLS.extend(['远程登陆','硬件开发','大数据统计','人工智能','教别人编程'])
SKILLS.extend(['音乐谱曲','网络安全','大数据统计','人工智能','教别人编程'])

class Explosion(arcade.Sprite):
    """ 创建可爆炸的角色 """ 

    def __init__(self, texture_list,x,y):
        """texture_list是已经load了的造型列表"""
        super().__init__()

        self.center_x = x
        self.center_y = y
        # 第一帧
        self.current_texture = 0      # 这是造型索引号
        self.textures = texture_list  # 这是每帧图片列表
        self.set_texture(self.current_texture)

    def update(self):

        # 更新每帧的图片,到了最后一帧后就会删除自己。
        self.current_texture += 1
        if self.current_texture < len(self.textures):
            self.set_texture(self.current_texture)
        else:
            self.kill()

class Effect(arcade.Sprite):
    def __init__(self,x,y,sc):
        super().__init__("images/lovely_turtle.png",scale=sc)
        self.alpha = 50
        self.center_x = x
        self.center_y = y
        self.change_y = 2
        
    def update(self):
        super().update()
        if self.bottom > SCREEN_HEIGHT :self.kill()        
    
    
class Coin(arcade.AnimatedTimeSprite):
    def __init__(self):
        super().__init__(scale=0.5)
        
        self.center_x = random.randrange(SCREEN_WIDTH)
        self.center_y = random.randrange(SCREEN_HEIGHT,SCREEN_HEIGHT*2)
        self.change_y = -1                      # 会往下掉
        self.textures = []
        self.textures.append(arcade.load_texture("images/gold_1.png", scale=COIN_SCALE))
        self.textures.append(arcade.load_texture("images/gold_2.png", scale=COIN_SCALE))
        self.textures.append(arcade.load_texture("images/gold_3.png", scale=COIN_SCALE))
        self.textures.append(arcade.load_texture("images/gold_4.png", scale=COIN_SCALE))
        self.textures.append(arcade.load_texture("images/gold_3.png", scale=COIN_SCALE))
        self.textures.append(arcade.load_texture("images/gold_2.png", scale=COIN_SCALE))
        self.cur_texture_index = random.randrange(len(self.textures))

        self.string =   random.choice(SKILLS)  # 金币顶上的字

    def update(self):
        super().update()
        if self.top < 0 :self.kill()        

class MyGame(arcade.Window):
    """ 继承自窗口的Window类. """

    def __init__(self, width, height, title):
        """
        初始化方法
        """
        super().__init__(width, height, title)
        self.frame_counter = 0                    # 帧计数器
        self.counter_down = TOTAL_TIME
        self.coin_sound =  arcade.sound.load_sound("images/recording1.wav")# 金币声
        self.bang_sound = arcade.sound.load_sound("images/explosion.wav")  # 爆炸声
        self.begin_time = time.time()
        self.game_over = False

        # 定义所有角色列表
        self.background = None
        self.all_sprites_list = None
        self.coin_list = None
        self.accepted_coin_list = None
        self.bomb_list = None
        self.play_speed_factor = 1
        self.shooting_coin = None
 
    def setup(self):        
        
        self.explosion_images = []
        for i in range(55):
            # 加载从 explosion0000.png 到 explosion0054.png 的所有图片为敌人的爆炸效果动画帧            
            texture_name = f"enemy_explosion/explosion{i:04d}.png"
            self.explosion_images.append(arcade.load_texture(texture_name))
            
        self.all_sprites_list = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()
        self.bomb_list = arcade.SpriteList()
        self.accepted_coin_list = arcade.SpriteList()

        self.background = arcade.Sprite("images/background.png")
        self.background.left = 0
        self.background.bottom = 0
        

        # 设置玩家相关变量         
        self.score = 0
        
        self.heading = [0,0] # 表示方向的向量
        self.player = arcade.AnimatedWalkingSprite()

        character_scale = 0.75
        self.player.stand_right_textures = []
        self.player.stand_right_textures.append(arcade.load_texture("images/character_sprites/character0.png",
                                                                    scale=character_scale))
        self.player.stand_left_textures = []
        self.player.stand_left_textures.append(arcade.load_texture("images/character_sprites/character0.png",
                                                                   scale=character_scale, mirrored=True))

        self.player.walk_right_textures = []

        self.player.walk_right_textures.append(arcade.load_texture("images/character_sprites/characterw0.png",
                                                                   scale=character_scale))
        self.player.walk_right_textures.append(arcade.load_texture("images/character_sprites/characterw1.png",
                                                                   scale=character_scale)) 

        self.player.walk_left_textures = []

        self.player.walk_left_textures.append(arcade.load_texture("images/character_sprites/characterw0.png",
                                                                  scale=character_scale, mirrored=True))
        self.player.walk_left_textures.append(arcade.load_texture("images/character_sprites/characterw1.png",
                                                                  scale=character_scale, mirrored=True)) 

        self.player.texture_change_distance = 20

        self.player.center_x = SCREEN_WIDTH // 2
        self.player.center_y = SCREEN_HEIGHT // 2 -100
        self.player.scale = 0.5
        self.player.lives = 3            # 还剩下的生命个数
        self.player.status = True        # 生命状态        
        self.player.reborn_time = 160    # 初始复活时间 

        for i in range(COIN_COUNT):
            coin = Coin()                
            self.coin_list.append(coin)
            self.all_sprites_list.append(coin)
            
        # 设置背景颜色
        arcade.set_background_color(arcade.color.AMAZON)

    def on_draw(self):
        """
        渲染屏幕
        """

        # 开始渲染屏幕
        arcade.start_render()

        self.background.draw()
        # 画所有的角色
        self.all_sprites_list.draw()

        beyond_border = self.player.left < 0 or self.player.right > SCREEN_WIDTH
        beyond_border = beyond_border or self.player.top < 0 or self.player.bottom > SCREEN_HEIGHT
        if not beyond_border:self.player.draw()
        
        for coin in self.coin_list:             
            x = coin.center_x -35
            y = coin.center_y + 25            
            arcade.draw_text(coin.string, x, y, arcade.color.WHITE, 14,font_name='simhei')            

        # 画文本在屏幕上
        output = f"当前得分: {int(self.score) }"
        arcade.draw_text(output, SCREEN_WIDTH//2-100, SCREEN_HEIGHT-100, arcade.color.CYAN, 24,font_name='simkai')

        # 画倒计时在屏幕上         
        arcade.draw_text(str(int(self.counter_down)), SCREEN_WIDTH//2, SCREEN_HEIGHT-50, arcade.color.WHITE, 14 )

        # 画游戏结束的字在屏幕上
        if self.game_over :                            
            arcade.draw_text(" 游 戏 结 束 ", SCREEN_WIDTH//2-150, SCREEN_HEIGHT//2, arcade.color.WHITE, 44 ,font_name='simkai')
            

    def on_key_press(self, key, modifiers):
        """
         当按下键盘某键时会调用此函数
        """
        if self.game_over  or not self.player.status: return      # 游戏结束或玩家死了
        
        if key == arcade.key.UP:
            self.player.change_y = MOVEMENT_SPEED * self.play_speed_factor
            self.heading = [0,1]
        elif key == arcade.key.DOWN:
            self.player.change_y = -MOVEMENT_SPEED * self.play_speed_factor
            self.heading = [0,-1]
        elif key == arcade.key.LEFT:
            self.player.change_x = -MOVEMENT_SPEED * self.play_speed_factor
            self.heading = [-1,0]
        elif key == arcade.key.RIGHT:
            self.player.change_x = MOVEMENT_SPEED * self.play_speed_factor
            self.heading = [1,0]
        elif key == arcade.key.SPACE and len(self.accepted_coin_list) > 0: # 发射
             
            self.shooting_coin = self.accepted_coin_list.pop()
            self.shooting_coin.center_x =self.player.center_x  # 把金币放在玩家x坐标
            self.shooting_coin.center_y =self.player.center_y  # 把金币放在玩家y坐标
            
            self.shooting_coin.change_x = self.heading[0] * 5
            self.shooting_coin.change_y = self.heading[1] * 5
  

    def on_key_release(self, key, modifiers):
        """
        当松开按键时会调用这个函数
        """
        
        if self.game_over : return
        
        if key == arcade.key.UP or key == arcade.key.DOWN:
            self.player.change_y = 0
        elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
            self.player.change_x = 0

    def update(self, delta_time):
        """ 移动与更新游戏的代码在这里编写 """

        if random.randint(1,200) == 1 and not self.game_over : 
            bomb = arcade.Sprite("images/bomb.png")
            bomb.alpha = 50
            self.bomb_list.append(bomb)
            self.all_sprites_list.append(bomb)
            bomb.center_x = random.randrange(SCREEN_WIDTH)
            bomb.center_y = random.randrange(SCREEN_HEIGHT)
            if arcade.get_distance_between_sprites(bomb,self.player)< 100 : bomb.kill()           
            
       
        if random.randint(1,200) == 1 and not self.game_over : 
            coin = Coin()                
            self.coin_list.append(coin)
            self.all_sprites_list.append(coin)            

        self.player.update()
        self.player.update_animation()
        self.all_sprites_list.update()
        self.all_sprites_list.update_animation()

        if not self.game_over :  
            self.frame_counter += 1
            if not self.player.status:        # 如果玩家死了
                if self.player.reborn_time >0 :
                    self.player.reborn_time-=1
                elif self.player.reborn_time == 0 :
                    self.player.center_x = SCREEN_WIDTH // 2
                    self.player.center_y = SCREEN_HEIGHT // 2 -100
                    self.player.change_x = 0
                    self.player.change_y = 0                    
                    self.player.reborn_time = 160
                    self.player.status = True
        
            # 创建碰到角色的金币列表
            hit_list = arcade.check_for_collision_with_list(self.player, self.coin_list)
            
            # 遍历碰到的金币,删除它们,并加分
            for coin in hit_list:             
                coin.kill()                               # 从金币列表中移除
                arcade.sound.play_sound(self.coin_sound)
                self.score += 100
                self.play_speed_factor +=0.1
                e = Effect(self.player.center_x,self.player.center_y,self.score/2000) # 效果
                self.all_sprites_list.append(e)
                c = arcade.Sprite("images/gold_1.png", scale=COIN_SCALE)
                c.center_x = -100
                c.center_y = -100
                self.accepted_coin_list.append(c)    # 收到的金币
                self.all_sprites_list.append(c)
                
            # 创建碰到角色的炸弹列表
            hit_list = arcade.check_for_collision_with_list(self.player, self.bomb_list)
            if len(hit_list) > 0 :
                # 玩家被炸死
                arcade.sound.play_sound(self.bang_sound)
                self.player.status = False  # 表示死了
                self.player.lives -= 1                
                self.player.change_x = random.choice([-30,-20,20,30])
                self.player.change_y = random.choice([-30,-20,20,30])         
                
                if self.player.lives < 0 :
                    self.game_over = True
                    
                for bomb in hit_list:                    
                    bomb.kill()
                    e = Explosion(self.explosion_images, bomb.center_x,bomb.center_y)
                    self.all_sprites_list.append(e)
                [bomb.kill() for bomb in self.bomb_list]
                    
            # 创建发射出去的金币和炸弹的碰撞列表
            if self.shooting_coin !=None:
                hit_list = arcade.check_for_collision_with_list(self.shooting_coin, self.bomb_list)
                if len(hit_list) > 0 :                        
                    for bomb in hit_list:
                        arcade.sound.play_sound(self.bang_sound)
                        self.score += 1000                 
                        e = Explosion(self.explosion_images, bomb.center_x,bomb.center_y)
                        self.all_sprites_list.append(e)
                        bomb.kill()
                
            if self.frame_counter % 10 == 0 :
                if self.shooting_coin !=None:
                    if self.shooting_coin.left <0 or self.shooting_coin.right>SCREEN_WIDTH \
                       or self.shooting_coin.top<0 or self.shooting_coin.bottom>SCREEN_HEIGHT:
                           self.shooting_coin.kill()
                string = SCREEN_TITLE + ",生命:" + str(self.player.lives) + ",金币:" + str(len(self.accepted_coin_list))
                self.set_caption(string)
                self.esc_time = time.time() - self.begin_time   # 逝去的时间
                self.counter_down = TOTAL_TIME - self.esc_time  # 还剩的时间
                if self.esc_time > TOTAL_TIME:
                   print("游戏结束")
                   self.player.change_x = 0
                   self.player.change_y = 0
                   self.game_over = True

def main():
    """ 主要函数"""
    window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
     
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()

由于gif截屏软件对图片进行了压缩,所以gif图不怎么漂亮哟。