python星际赛车 turtle star race arcade game

"""这是用Python的海龟画图模块制作的赛车小游戏"""

from turtle import Turtle,Screen
from random import randint,choice
from time import sleep
from car import *                           # 导入Car小汽车类

__author__ = "李兴球"
__date__ = "2018/11/26"
__company__ = "风火轮编程"

class ScrollBackground():
    """定义一个滚动背景类,它由两个海龟对象组成,不断地轮换"""
    def __init__(self,image,screen):
        self.bg1 = Turtle(shape=image)       # 生成海龟1    
        self.bg1.penup()
        self.bg2 = Turtle(shape=image)       # 生成海龟2
        self.bg2.penup()
        self.screen = screen                 # 定义screen属性
        self.alt = 1        
 
    def move(self):
        """移动角色"""
        self.bg1.sety(self.bg1.ycor() -10)   # y坐标减去10,这样可以向下移
        if self.bg1.ycor()<-360 :            # 小于-360,就把移动360
           self.bg1.sety(360)
           self.alt  =   -1
        if self.bg1.ycor()<0 and self.bg1.ycor()>-360:
            self.alt =  1
 
        self.bg2.sety(self.bg1.ycor() + self.alt * 360)
        self.screen.ontimer(self.move,10)
    
            
class Coin(Turtle):
    def __init__(self,images,sprite,sound):
        Turtle.__init__(self,visible=False)
        self.images = images             
        self.sprite = sprite
        self.sound = sound
        self.penup()                          # 抬笔        
        self.goto_up()                        # 到上边        
        
    def goto_up(self):
        """到上边随机的一个位置"""
        self.hideturtle()                    # 隐藏自己
        self.shape(self.images[0])           # 索引为0的造型      
        self.dead = False
        self.goto( 40 * randint(-2,2),randint(300,600))
        self.showturtle()
        self.move()
        
    def move(self):
        if not self.sprite.dead:                                # 如果主角没死

            self.sety(self.ycor() - 3)
            self.check_collision()
            if self.sprite.hp < 0 : return
            if self.ycor() > - 180 and not self.dead:
                self.screen.ontimer(self.move,10)
            else:
                
                self.goto_up()
            
    def check_collision(self):
        """以后再改成坐标判断"""
        carleft = self.xcor() - 15
        carright = self.xcor() + 15
        cartop = self.ycor() + 30
        carbottom = self.ycor() - 30
        spriteleft = self.sprite.xcor() - 15
        spriteright  = self.sprite.xcor() + 15
        spritetop  = self.sprite.ycor() + 30
        spritebottom = self.sprite.ycor() - 30
        "没有碰的逻辑"
        nocollision = carleft > spriteright or carright < spriteleft or cartop < spritebottom or carbottom > spritetop
        if not  nocollision:
            "并不是没有碰到,那么就换造型,并且播放接到金币的声音"
            self.shape(self.images[1])
            self.play()
            self.dead = True
            self.sprite.hp = self.sprite.hp + 1            # 接到一枚金币加hp为1
            self.sprite.score = self.sprite.score + 10     # 接到一枚金币加10分
            self.screen.title("得分:" + str(self.sprite.score) + ",血量:" + str(self.sprite.hp)) 
            
    def play(self):
        try:
            self.sound.play()
        except:
            pass


        
def move_left():
    if main_sprite.xcor()>-80 and main_sprite.hp >= 0:   # 主角x坐标大于-80并且血大于等于0就能向左移动
        main_sprite.setx(main_sprite.xcor() - 40)
    
def move_right():
    if main_sprite.xcor()< 80 and main_sprite.hp >= 0:   # x坐标小于80并且血大于等于0就能向右移动
        main_sprite.setx(main_sprite.xcor() + 40)

def init_audio(music,collision_sound,coin_sound):
    """初始化音频"""
    metal_sound = None                            # 金属声
    try:
        import pygame                             # 导入pygame模块,无此模块本游戏不会发声
        pygame.mixer.init()                       # 初始化混音器
        pygame.mixer.music.load(music)            # 加载背景音乐
        pygame.mixer.music.play(-1,0)             # 循环播放背景音乐
        metal_sound = pygame.mixer.Sound(collision_sound) # 加载金属碰撞声
        coin_sound = pygame.mixer.Sound(coin_sound)       #加载金币声
         
    except:
        pass
    return metal_sound,coin_sound

def init_screen(background_image,sport_car_image):
    """初始化屏幕"""
    screen = Screen()                            # 新建屏幕对象
    screen.delay(0)                              # 屏幕绘画延时为0
    screen.setup(480,360)                        # 设置屏幕canvas大小
    screen.bgcolor("black")                      # 背景色为黑色
    screen.bgpic("封面2.png")                    # 显示封面
    screen.title("Python星际赛车_作者:李兴球_风火轮少儿编程")
       
    screen.addshape(background_image)            # 增加背景的gif图 
    screen.addshape(sport_car_image)             # 增加小汽车的gif图
    [screen.addshape(car) for car in car_images] # 注册到形状字典
    [screen.addshape(coin) for coin in coin_images] # 注册到形状字典
    
    return screen

def make_mainsprite(screen):
    global main_sprite
    main_sprite = Turtle(shape = sport_car_image)
    main_sprite.score = 0                        #新增自定义属性,得分
    main_sprite.hp = 100                         #新增自定义属性,血量
    main_sprite.dead = False                     #新增死亡属性,表示是否死亡
    main_sprite.penup()
    main_sprite.sety(-110)
    screen.onkeypress(move_left,"Left")
    screen.onkeypress(move_right,"Right")
    return main_sprite
    
def begin_game():
    """开始游戏"""
    screen.onkeypress(None,"Return")             #取消回车键的按键绑定
    screen.bgpic("rode480.png")                  #背景图书片
    scrollbg = ScrollBackground(background_image,screen) #新建可滚动背景
    scrollbg.move()                              #背景移动
    main_sprite = make_mainsprite(screen)        #新建主角,也就是按左右键操作的跑车
    [ Car(car_images,main_sprite,metal_sound) for i in range(5) ]   #生成5辆小汽车
    [ Coin(coin_images,main_sprite,coin_sound) for i in range(3) ]  #生成3个金币
    
    
if __name__ == "__main__":

    main_sprite = None
    
    music = "Chiptune.wav"
    collision_sound = "1.wav"
    coin_sound = "接金币.wav"
    metal_sound,coin_sound = init_audio(music,collision_sound,coin_sound)    

    background_image = "rode480.gif"
    sport_car_image = "跑车.gif"
    car_images = ["car" + str(i) + ".gif" for i in range(5)]
    coin_images = ["Coin_Normal.gif","Coin_Picked.gif"]
    screen = init_screen(background_image,sport_car_image)
    
    "按回车开始游戏"
    screen.onkeypress(begin_game,"Return")     #绑定回车键到begin_game函数
    screen.listen()
        
        
    screen.mainloop()
        
        
    

星际赛车_python赛车游戏