在visual studio code中用 python写一个飞机大战的程序
时间: 2024-01-12 10:04:15 浏览: 25
好的,以下是一个简单的飞机大战游戏示例代码,可以在 Visual Studio Code 中运行:
```python
import os
import turtle
import math
import random
# 设置窗口
win = turtle.Screen()
win.bgcolor("black")
win.title("飞机大战")
win.bgpic("background.gif")
# 注册形状
turtle.register_shape("player.gif")
turtle.register_shape("enemy.gif")
turtle.register_shape("bullet.gif")
# 添加玩家飞机
player = turtle.Turtle()
player.speed(0)
player.penup()
player.shape("player.gif")
player.color("blue")
player.goto(0, -250)
player.setheading(90)
# 玩家飞机移动速度
player_speed = 15
# 添加敌机列表
enemies = []
# 创建敌机
for i in range(10):
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.speed(0)
enemy.penup()
enemy.shape("enemy.gif")
enemy.color("red")
enemy.goto(random.randint(-200, 200), random.randint(100, 250))
# 敌机移动速度
enemy_speed = 2
# 添加子弹
bullet = turtle.Turtle()
bullet.speed(0)
bullet.penup()
bullet.shape("bullet.gif")
bullet.color("yellow")
bullet.shapesize(0.5, 0.5)
bullet.hideturtle()
bullet.goto(0, -400)
bullet.setheading(90)
bullet_speed = 20
bullet_state = "ready"
# 玩家飞机移动
def move_left():
x = player.xcor()
x -= player_speed
if x < -280:
x = -280
player.setx(x)
def move_right():
x = player.xcor()
x += player_speed
if x > 280:
x = 280
player.setx(x)
def move_up():
y = player.ycor()
y += player_speed
if y > 250:
y = 250
player.sety(y)
def move_down():
y = player.ycor()
y -= player_speed
if y < -250:
y = -250
player.sety(y)
# 发射子弹
def fire_bullet():
global bullet_state
if bullet_state == "ready":
bullet_state = "fire"
x = player.xcor()
y = player.ycor() + 10
bullet.showturtle()
bullet.goto(x, y)
# 检测碰撞
def is_collision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))
if distance < 15:
return True
else:
return False
# 注册键盘事件
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(move_up, "Up")
turtle.onkey(move_down, "Down")
turtle.onkey(fire_bullet, "space")
# 运行主循环
while True:
# 移动敌机
for enemy in enemies:
y = enemy.ycor()
y -= enemy_speed
enemy.sety(y)
# 检测敌机是否撞墙
if y < -300:
enemy.goto(random.randint(-200, 200), random.randint(100, 250))
# 检测敌机是否与玩家飞机相撞
if is_collision(enemy, player):
player.hideturtle()
enemy.hideturtle()
print("Game Over")
break
# 检测敌机是否与子弹相撞
if is_collision(enemy, bullet):
bullet.hideturtle()
bullet_state = "ready"
enemy.goto(random.randint(-200, 200), random.randint(100, 250))
# 移动子弹
if bullet_state == "fire":
y = bullet.ycor()
y += bullet_speed
bullet.sety(y)
# 检测子弹是否撞墙
if y > 300:
bullet.hideturtle()
bullet_state = "ready"
# 检测是否所有敌机被消灭
dead_enemies = [enemy for enemy in enemies if not enemy.isvisible()]
if len(dead_enemies) == len(enemies):
print("You Win!")
break
turtle.mainloop()
```
注意:在运行时需要将三个 .gif 图片放在与代码相同的目录下。