python制作飞机大战代码_python游戏编程系列-飞机大战

继续介绍python游戏编程,仍然是基于pgzero。关于该软件包的基础使用技巧可参考本人专栏文章:

老娄:python游戏编程之pgzero使用介绍​zhuanlan.zhihu.com
a1eb432295a94e5ef91ada677664244e.png

本篇咱们来实现经典小游戏——飞机大战,要求战机在移动过程中摧毁敌方战机。

思考

  • 关于移动。根据此前本系列中练习过的技能,咱们对于常规的角色移动就可以通过x,y这样的坐标变化来实现。但通常游戏中的角色如果能够实现移动中的“缓动”——速度会有变化,可以从快到慢或者由慢到快,轨迹也可以是直线或曲线,那么视觉效果会更好。pgzero提供了一个animate()来实现这样的效果。

代码

import pgzrun
import pgzero
import random
import math

WIDTH = 800
HEIGHT = 800

background0 = Actor("earth_background")
background0.topleft = (0,0)
background1 = Actor("earth_background")
background1.midbottom = background0.midtop
backgrounds = []
backgrounds.append(background0)
backgrounds.append(background1)

plane = Actor("plane")
plane.midbottom = (int(WIDTH/2),HEIGHT)
plane.power = False

bullets = [] #子弹列表
enemy_planes = []  #敌机列表
power_bags = []  #增强包

global FINISH
FINISH = False
global SCORE
SCORE = 0

#缓动效果
tweens = ["linear","accelerate","decelerate","accel_decel",
          "in_elastic","out_elastic","in_out_elastic","bounce_end",
          "bounce_start","bounce_start_end"]

def create_enemy_plane():
    enemy_pics = ["enemyplane0","enemyplane1"]
    enemy_plane = Actor(random.choice(enemy_pics))
    enemy_plane.topleft = (random.randint(0,WIDTH),0)
    enemy_planes.append(enemy_plane)
    animate(enemy_plane,
            tween = random.choice(tweens), 
            duration = random.randint(5,15), 
            topleft = (random.randint(0,WIDTH), HEIGHT)
            )

clock.schedule_interval(create_enemy_plane, 1.5)

def update():
    if FINISH:
        clock.unschedule(create_enemy_plane)
    update_background()
    update_plane()
    update_power_bag()
    update_bullet()
    update_enemy_plane()

def draw():
    # screen.fill((255, 255, 255))
    screen.draw.text("SCORE: %d" % SCORE, topleft = (20, 100), color="green", fontsize=60)
    if FINISH:
        screen.draw.text("GAME OVER!", (20, 300), color="red", fontsize=80)
        return

    for b in backgrounds:
        b.draw()
    plane.draw()
    for p in power_bags:
        p.draw()
    for b in bullets:
        b.draw()

    for e in enemy_planes:
        e.draw()



def update_plane():
    global FINISH

    speed = 3
    if keyboard.LEFT:
        plane.x -= speed
    elif keyboard.RIGHT:
        plane.x += speed
    elif keyboard.UP:
        plane.y -= speed
    elif keyboard.DOWN:
        plane.y += speed
    else:
        pass

    if plane.left < 0:
        plane.left = 0
    if plane.right > WIDTH:
        plane.right = WIDTH
    if plane.bottom > HEIGHT:
        plane.bottom = HEIGHT
    if plane.top < 0:
        plane.top = 0


    #当按下空格键时,增加一枚子弹
    if keyboard.SPACE:
        clock.schedule_unique(shoot,0.1)

    for e in enemy_planes:
        if e.colliderect(plane):
            FINISH = True
            return

def shoot():
    bullet = Actor("bullet")
    bullet.midbottom = plane.midtop
    bullets.append(bullet)
    #如果获得了增强包,额外增加两排子弹
    if plane.power:
        leftbullet = Actor("bullet")
        leftbullet.midbottom = plane.midtop
        leftbullet.angle = 15
        bullets.append(leftbullet)
        rightbullet = Actor("bullet")
        rightbullet.midbottom = plane.midtop
        rightbullet.angle = -15
        bullets.append(rightbullet)

def update_bullet():
    for b in bullets:
        theta = math.radians(b.angle) + 90
        b.x += 10*math.cos(theta)
        b.y -= 10*math.sin(theta)
        if b.bottom < 0:
            bullets.remove(b)

def update_background():
    for b in backgrounds:
        b.y += 1
        if b.top > HEIGHT:
            b.bottom = 0

def update_enemy_plane():
    global SCORE
    if FINISH:
        return
    if len(enemy_planes) == 0:
        return
    for e in enemy_planes:
        if e.top > HEIGHT:
            enemy_planes.remove(e)
            continue
        n = e.collidelist(bullets)
        if n != -1:
            enemy_planes.remove(e)
            SCORE += 100

def update_power_bag():
    for p in power_bags:
        p.y += 2
        if p.bottom > HEIGHT:
            power_bags.remove(p)
        if p.colliderect(plane):
            plane.power = True
            power_bags.remove(p)
            clock.schedule(power_down,5.0)
    if random.randint(0,800) < 5:
        power_bag = Actor('warplanes_powerup')
        power_bag.topleft = (random.randint(0,WIDTH),100)
        power_bags.append(power_bag)


def power_down():
    plane.power = False
pgzrun.go()

效果

知乎视频​www.zhihu.com

参考资料

《趣学python游戏编程》何青 著

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Chapter 2 Magic coins example. magic_coins1.py Chapter 3 Favourite sports. favourite_sports.py Furniture placeholder. furniture_placeholder.py A list of lists. list_of_lists.py A letter from Malcolm Dithering dithering_letter.py Escaping quotes quote_escaping.py The Wizard List wizard_list.py Chapter 4 The turtle draws a square. turtle1.py The turtle draws two parallel lines. turtle2.py Chapter 5 If statements if_statements.py Conditions in if-statements. conditions.py Else-if (elif) statements. elif_statements.py Strings and numbers. strings_and_numbers.py Chapter 6 Five Hellos. five_hellos.py Huge hairy pants (example 1). huge_hairy_pants1.py Huge hairy pants (example 2). huge_hairy_pants2.py Magic coins (example 2). magic_coins2.py A while-loop with multiple conditions. while_loop_multiple_conditions.py Looping through the wizard list. wizard_list_loop.py Chapter 7 A function to calculate your savings. savings.py Building a spaceship. spaceship_building.py Test function (example 1). test_function1.py Test function (example 2). test_function2.py Your age function. your_age.py Chapter 8 Giraffes (example 1). giraffes1.py Giraffes (example 2). giraffes2.py Three turtles. three_turtles.py Chapter 9 Using the abs (absolute) function. abs_function.py Using the exec (execute) function. exec_function.py Using the len (length) function. len_function.py Using the max and min functions. max_and_min.py Using the range function. range_function.py Using the sum function. range_function.py Opening a file. opening_a_file.py Writing to a file. writing_to_a_file.py Chapter 10 Copying objects (example 1). copying_objects1.py Copying objects (example 2). copying_objects1.py Guess a random number. guess_a_number.py Random desserts. random_desserts.py Using the time module. timing_lots_of_numbers.py Using pickle to save information. pickle_saving.py Using pickle to load information. pickle_loading.py Chapter 11 Drawing an eight point star. eight_point_star.py Drawing a many point star. many_point_star.py Drawing a spiral star. spiral_star.py Drawing a nine point star. nine_point_star.py Drawing a car. car.py Drawing a yellow circle. yellow_circle.py Drawing a filled green circle. green_circle.py Drawing a dark-green circle. dark_green_circle.py Drawing squares using a function. square_function.py Drawing filled and unfilled squares. filled_squares.py Drawing stars using a function. star_function.py Chapter 12 Clickable button (example 1). clickable_button1.py Clickable button (example 2). clickable_button2.py Drawing a diagonal line. diagonal_line.py Drawing a square. square.py Drawing a horizontal rectangle. horizonal_rectangle.py Drawing a vertical rectangle. horizonal_rectangle.py Drawing random rectangles. random_rectangles.py Drawing coloured rectangles. coloured_rectangles.py Using the color chooser. rectangle_colorchooser.py Drawing arcs. drawing_arcs.py Drawing polygons. drawing_polygons.py Drawing text. drawing_text.py Drawing images. drawing_images.py Basic animation (example 1). basic_animation1.py Basic animation (example 2). basic_animation2.py Using events (example 1). using_events1.py Using events (example 2). using_events1.py Using the move function. using_move.py Using the itemconfig function. using_itemconfig.py Chapter 13 Bounce (example 1) - this one doesn't do anything when it's run. bounce1.py Bounce (example 2) - stationary ball. bounce2.py Bounce (example 3) - ball moving upwards. bounce3.py Bounce (example 4) - ball moving up and down. bounce4.py Bounce (example 5) - ball moving around the screen. bounce5.py Chapter 14 Bounce (example 6) - adding the paddle. bounce6.py Bounce (example 7) - moving paddle. bounce6.py Bounce (example 8) - bouncing the ball when it hits the paddle. bounce6.py Bounce (example 9) - ending the game when the ball hits the floor. bounce6.py Chapter 15 Transparent Image - 27 by 30 pixels. transparent-image.gif 6 Stick Figure Images - left and right. stickfigure.zip 3 Platform images. platform.zip 2 Door images. door.zip Background image. background.gif Chapter 16 Stickman Game, version 1 - displaying the background. stickmangame1.py Stickman Game, version 2 - adding the within functions. stickmangame2.py Stickman Game, version 3 - adding the platform. stickmangame3.py Stickman Game, version 4 - adding lots of platforms. stickmangame4.py Chapter 17 Stick figure sprite class. stickfiguresprite.py Stickman Game, version 5 - adding the stick figure. stickmangame5.py Chapter 18 Stickman Game, version 6 - animating the stick figure. stickmangame6.py Stickman Game, version 6 - adding the door sprite. stickmangame7.py Afterword Pygame2 example. pygame-example.py Hello World Java example. HelloWorld.java Hello World C example. helloworld.c Hello World C++ example. helloworld.cpp Hello World C# example. helloworld.cs Hello World PHP example. helloworld.php Hello World Objective-C example. helloworld.m Hello World Perl example. helloworld.pl Hello World Ruby example. helloworld.rb Hello World Javascript example. helloworld.js Hello World Javascript Browser example. helloworld-js.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值