Facebook
From Algo, 1 Month ago, written in Python.
Embed
Download Paste or View Raw
Hits: 185
  1. from turtle import *
  2. from random import randint
  3.  
  4.  
  5. tsize = 20
  6. s_width = 200
  7. s_height = 180
  8.  
  9.  
  10. class Sprite(Turtle):
  11.    def __init__(self, x, y, step=10, shape='circle', color='black'):
  12.        Turtle.__init__(self)
  13.        self.penup()
  14.        self.speed(0)
  15.        self.goto(x, y)
  16.        self.color(color)
  17.        self.shape(shape)
  18.        self.step = step
  19.        self.points = 0
  20.  
  21.  
  22.    def move_up(self):
  23.        self.goto(self.xcor(), self.ycor() + self.step)
  24.    def move_down(self):
  25.        self.goto(self.xcor(), self.ycor() - self.step)
  26.    def move_left(self):
  27.        self.goto(self.xcor() - self.step, self.ycor())
  28.    def move_right(self):
  29.        self.goto(self.xcor() + self.step, self.ycor())
  30.  
  31.  
  32.    def is_collide(self, sprite):
  33.        dist = self.distance(sprite.xcor(), sprite.ycor())
  34.        if dist < 30:
  35.            return True
  36.        else:
  37.            return False
  38.  
  39.  
  40.    def set_move(self, x_start, y_start, x_end, y_end):
  41.        self.x_start = x_start
  42.        self.y_start = y_start      
  43.        self.x_end = x_end
  44.        self.y_end = y_end
  45.        self.goto(x_start, y_start)
  46.        self.setheading(self.towards(x_end, y_end)) #direction
  47.  
  48.    def make_step(self):
  49.        self.forward(self.step) #direction already present
  50.  
  51.  
  52.        if self.distance(self.x_end, self.y_end) < self.step: #if distance less than half step
  53.            self.set_move(self.x_end, self.y_end, self.x_start, self.y_start) #change direction
  54.  
  55.  
  56. player = Sprite(0, -100, 10, 'circle', 'orange')
  57. enemy1 = Sprite(-s_width, 0, 15, 'square', 'red')
  58. enemy1.set_move(-s_width, 0, s_width, 0)
  59. enemy2 = Sprite(s_width, 70, 15, 'square', 'red')
  60. enemy2.set_move(s_width, 70, -s_width, 70)
  61. goal = Sprite(0, 120, 20, 'triangle', 'green')
  62. #goal.set_move(-s_width, 120, s_width, 0)  
  63.  
  64.  
  65. total_score = 0
  66.  
  67.  
  68. scr = player.getscreen()
  69.  
  70.  
  71. scr.listen()
  72.  
  73.  
  74. scr.onkey(player.move_up, 'Up')
  75. scr.onkey(player.move_left, 'Left')
  76. scr.onkey(player.move_right, 'Right')
  77. scr.onkey(player.move_down, 'Down')
  78.  
  79.  
  80. while total_score < 3:
  81.    enemy1.make_step()
  82.    enemy2.make_step()
  83.    #goal.make_step()
  84.    if player.is_collide(goal):
  85.        total_score += 1
  86.        player.goto(0, -100)
  87.    if player.is_collide(enemy1) or player.is_collide(enemy2):
  88.        goal.hideturtle()
  89.        break
  90.  
  91.  
  92. if total_score == 3:
  93.    enemy1.hideturtle()
  94.    enemy2.hideturtle()
  95.