# setting up the screen
import turtle
import math
wn = turtle.Screen()
wn.bgcolor('black')
wn.title('S')
# draw a border
bp = turtle.Turtle()
bp.speed(0)
bp.color('white')
bp.penup()
bp.setposition(-300, -300)
bp.pendown()
bp.pensize(3)
bp.hideturtle()
for lll in range(4):
bp.forward(600)
bp.left(90)
# mr.TIM
tim = turtle.Turtle()
tim.speed(0)
tim.setposition(0, -250)
tim.setheading(90)
tim.penup()
tim.color('red')
tim.shape('arrow')
# Bad guys
enemy = turtle.Turtle()
enemy.color('red')
enemy.shape('turtle')
enemy.speed(0)
enemy.penup()
enemy.setposition(0, 200)
enemy.setheading(270)
enemy_speed = 2
# Bullet
bullet = turtle.Turtle()
bullet.penup()
bullet.color('gold')
bullet.shape('triangle')
bullet.shapesize(0.5, 0.5)
bullet.speed(0)
bullet.setposition(0, 0)
bullet.setheading(90)
bullet.hideturtle()
bullet_speed = 20
# bullet states
bullet_state = 'ready'
# ready to fire
# fire
# move tim
poi_speed = 15
def move_left():
x = tim.xcor()
x -= poi_speed
tim.setx(x)
if x < -280:
x = + 280
tim.setx(x)
def move_right():
x = tim.xcor()
x += poi_speed
tim.setx(x)
if x > +280:
x = - 280
tim.setx(x)
# show bullet
def fire_bullet():
global bullet_state
if bullet_state == 'ready':
bullet_state = 'fire'
x = tim.xcor()
tt = tim.ycor() + 10
bullet.setposition(x, tt)
bullet.showturtle()
def iscollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcore()-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(fire_bullet, 'space')
# move the enemy + game mainloop
while True:
# Move the enemy left and right
c = enemy.xcor()
c += enemy_speed
enemy.setx(c)
if enemy.xcor() > 280:
v = enemy.ycor()
v -= 40
enemy.sety(v)
enemy_speed *= -1
if enemy.xcor() < -280:
v = enemy.ycor()
v -= 40
enemy.sety(v)
enemy_speed *= -1
# move bullet
if bullet_state == 'fire':
y = bullet.ycor()
y += bullet_speed
bullet.sety(y)
# stop the bullet and make it ready to fire again
if bullet.ycor() > 275:
bullet.hideturtle()
bullet_state = 'ready'
# game over for enemy
if iscollision(bullet, enemy):
# reset bullet
bullet_state = 'ready'
bullet.setposition(0, -400)
# reset enemy
enemy.setposition(-200, 250)