Ejemplo n.º 1
1
def main():
    ## create compound yellow/blue turtleshape for planets
    global s
    s = Screen()
    s.setup(1120,840)
    s.reset()
    s.tracer(0, 0)
    t = Turtle()
    t.ht()
    t.pu()
    t.fd(6)
    t.lt(90)

    t.begin_poly()
    t.circle(6, 180)
    t.end_poly()
    m1 = t.get_poly()

    t.begin_poly()
    t.circle(6,180)
    t.end_poly()
    m2 = t.get_poly()

    planetshape = Shape("compound")
    planetshape.addcomponent(m1,"orange")
    planetshape.addcomponent(m2,"blue")
    s.register_shape("planet", planetshape)
    #s.tracer(1,0)
    s.update()
    ## setup gravitational system
    gs = GravSys()
    sun = Star(1000000, Vec(-250,0), Vec(0,-0.35), gs, "circle")
    sun.color("yellow")
    sun.pensize(1.8)
    sun.pu()
    earth = Star(5000, Vec(450,0), Vec(0,70), gs, "planet")
    earth.pencolor("green")
    earth.shapesize(0.8)

    rm=12.0583
    vm=(8.0*5000/rm)**.5
    moon = Star(1, Vec(450+rm,0), Vec(0,70+vm), gs, "planet")
    moon.pencolor("blue")
    moon.shapesize(0.5)
    gs.init()
    gs.start()
    return "Done!"
def main():
    global d, SHS, SF, A
    A = 42 # answer to the ultimate question ... (you know)
    SHS = A / 20.
    SF = 1.0
    DSF = 1.0038582416
    s = Screen()
    s.setup(800, 600)
    s.reset()
    s.tracer(0)
    d = Turtle(visible=False)
    for i in range(6):
        d.fd(500)
        d.bk(500)
        d.left(60)   

    triangles = []
    for c in range(-5,6,2):
        if abs(c) != 1:
            triangles.append(TriTurtle(c, 1, 1))
            triangles.append(TriTurtle(c, -1, 2))
    for c in range(-4,5,2):
        if c != 0:
            triangles.append(TriTurtle(c, 2, 2))
            triangles.append(TriTurtle(c, -2, 1))
        triangles.append(TriTurtle(c, -4, 2))
        triangles.append(TriTurtle(c, 4, 1))
    for c in range(-3,4,2):
        triangles.append(TriTurtle(c, 5, 2))
        triangles.append(TriTurtle(c, -5, 1))
        triangles.append(TriTurtle(c, -7, 2))
        triangles.append(TriTurtle(c, 7, 1))
    for c in range(-2,3,2):
        triangles.append(TriTurtle(c, 8, 2))
        triangles.append(TriTurtle(c, -8, 1))
    for c in (-1, 1):
        triangles.append(TriTurtle(c, 1, 1))
        triangles.append(TriTurtle(c, -1, 2))
    triangles.append(TriTurtle(0, 2, 2))
    triangles.append(TriTurtle(0, -2, 1))
    s.tracer(1)
                         
    for phi in range(1,361):
        SF = SF*DSF
        s.tracer(0)
        for t in triangles:
            t.setturn(phi)
        #s.tracer(1)
        s.update()
    return "DONE!"
Ejemplo n.º 3
0
    if game_over:
        scoreboard.game_over()
        replay = screen.textinput("You have Squished our turtle friend", "Enter 1 to restart, 2 to continue 3 to quit:")

        if replay == "1":
            car.done()
            scoreboard.restart()
            MOVE_INCREMENT = 10
            car.create_cars()
            turtle.restart()
            screen.listen()

        elif replay == "2":
            turtle.restart()
            scoreboard.game_on()
            screen.listen()

        else:
            turtle.bye()

    if turtle.ycor() > 250:
        scoreboard.lx_score()
        car.create_cars()
        turtle.restart()
        MOVE_INCREMENT += 3
        time.sleep(0.01)

    screen.update()

screen.exitonclick()
Ejemplo n.º 4
0
    separater_turtle = Turtle()
    separater_turtle.color("white")
    separater_turtle.penup()
    separater_turtle.hideturtle()
    separater_turtle.setpos((0, -280))
    separater_turtle.setheading(90)
    separater_turtle.pensize(5)

    while separater_turtle.ycor() < 280:
        separater_turtle.pendown()
        separater_turtle.forward(10)
        separater_turtle.penup()
        separater_turtle.forward(20)


pong_screen.update()
separate_screen()
players.append(Goalkeeper(1))
players.append(Goalkeeper(2))
ball = Ball()

#move the human player up and down
pong_screen.onkey(key="Up", fun=players[0].up)
pong_screen.onkey(key="Down", fun=players[0].down)

pong_screen.onkey(key="W", fun=players[1].up)
pong_screen.onkey(key="S", fun=players[1].down)

is_game_on = True

while is_game_on:
Ejemplo n.º 5
0
myscreen.setup(width=600, height=600)

myplayer = Player()
myscreen.listen()
myscreen.onkey(myplayer.move, "Up")

car = CarManager()
scoreboard = Scoreboard()

game_is_on = True
counter = 0
while game_is_on:
    time.sleep(0.1)
    car.move()
    counter += 1
    myscreen.update()
    if myplayer.ycor() > 280:
        myplayer.start()
        scoreboard.point()
        car.level_up()

    if counter % 6 == 0:
        car.create_cars()
        counter = 0

    for i in car.allcars:
        if i.distance(myplayer) < 20:
            game_is_on = False
            scoreboard.game_over()

Ejemplo n.º 6
0
time.sleep(2)
playground.listen()
playground.onkey(fun=right.go_up, key="Up")
playground.onkey(fun=right.go_down, key="Down")
playground.onkey(fun=left.go_up, key="w")
playground.onkey(fun=left.go_down, key="s")

counter = 0
bouncey = Ball()
bouncey.ball_start()
announcer.clear()
playground.tracer(0)
game_continues = True
while game_continues:
    upper_drawer.score = bouncey.score[0]
    bottom_drawer.score = bouncey.score[1]
    upper_drawer.display_score(upper_drawer.score)
    bottom_drawer.display_score(bottom_drawer.score)
    playground.update()
    bouncey.move(score_left=bouncey.score[0], score_right=bouncey.score[1])
    bouncey.bounce(left, right)
    playground.update()
    time.sleep(0.01)
    if upper_drawer.score >= 25 or bottom_drawer.score >= 25:
        game_continues = False

announcer.write(arg="The game is over as 25 balls were missed",
                font=("Verdana", 25, "bold"))

playground.exitonclick()
screen.title("Snake game")
screen.tracer(0)

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(fun=snake.up, key="Up")
screen.onkey(fun=snake.down, key="Down")
screen.onkey(fun=snake.left, key="Left")
screen.onkey(fun=snake.right, key="Right")

game_is_on = True
while game_is_on:
    screen.update()  #making the snake to move continously
    time.sleep(0.1)
    snake.move()

    #detect collision with food
    if snake.head.distance(food) < 15:
        food.refresh()
        snake.extend()
        scoreboard.increase_score()

    #detect collision with wall
    if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor(
    ) > 280 or snake.head.ycor() < -280:
        game_is_on = False
        scoreboard.game_over()
Ejemplo n.º 8
0
            elif collision(
                    enemy, player
            ):  #if the player and one of the enemies collide then the game is over.
                bullet.hideturtle()
                player.hideturtle()
                for enemy in enemies:
                    enemy.hideturtle()
                pen.clear()
                pen.setposition(-300, -50)
                pen.write("Game Over!", font=("Courier", 80, "bold"))
                pen.setposition(-300, -100)
                pen.write("Score: ", font=("Courier", 65, "bold"))
                pen.setposition(50, -100)
                pen.write(score, font=("Courier", 65, "bold"))
                TheGameIsRunning = False
            if enemy_speed > 20:
                enemy_speed = 20
            if enemy.ycor() < 420 and enemy.ycor() > 300:
                enemy.sety(1000)
    if num_enemies == 0:  #if all the enemies are dead then the player wins.
        bullet.hideturtle()
        player.hideturtle()
        for enemy in enemies:
            enemy.hideturtle()
        pen.clear()
        pen.setposition(-300, -50)
        time.sleep(0.02)
        pen.write("You Win!", font=("Courier", 80, "bold"))
        TheGameIsRunning = False
    screen.update()  #updates the scree
Ejemplo n.º 9
0
r_paddle = Paddle(350, 0)
l_paddle = Paddle(-350, 0)
scoreboard = Scoreboard()
# p = Paddle(282,250)

s.listen()
s.onkey(r_paddle.go_up, "Up")
s.onkey(r_paddle.go_down, "Down")

s.onkey(l_paddle.go_up, "w")
s.onkey(l_paddle.go_down, "s")

game_is_on = True
while game_is_on:
    time.sleep(ball.move_speed)
    s.update()
    ball.move()
    if ball.ycor() > 300 or ball.ycor() < -300:
        ball.collide_wall()

    if (ball.distance(r_paddle) < 50 and ball.xcor() > 340) or (ball.distance(l_paddle) < 50 and ball.xcor() < -340):
        ball.collide_paddle()

    # Detects if the right paddle missies the ball
    if ball.xcor() > 380:
        ball.reset_position()
        scoreboard.l_point()

    # Detects if the left paddle missies the ball
    if ball.xcor() < -380:
        ball.reset_position()
Ejemplo n.º 10
0
l_paddle = Paddle((-350, 0))
r_paddle = Paddle((350, 0))
ball = Ball()
scoreboard = ScoreBoard()

screen.onkeypress(l_paddle.move_up, "w")
screen.onkeypress(l_paddle.move_down, "s")
screen.onkeypress(r_paddle.move_up, "Up")
screen.onkeypress(r_paddle.move_down, "Down")

game_is_on = True

while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()  # manually animate
    ball.move()

    # top and bottom collision
    if ball.ycor() < -280 or ball.ycor() > 280:
        ball.bounce_y()

    # paddle-ball collision - additional checks to check ball hitting the paddle edge
    if (ball.distance(r_paddle) < 50
            and ball.xcor() > 320) or (ball.distance(l_paddle) < 50
                                       and ball.xcor() < -320):
        ball.bounce_x()

    # right paddle misses the ball
    if ball.xcor() > 380:
        ball.reset_position()
Ejemplo n.º 11
0
# the tracer function will not show the animation
screen.tracer(0)

snake = Snake()  # there is no need to write snake.create_snake()
food = Food()
scoreboard = ScoreBoard()

screen.listen()
screen.onkey(snake.up, 'Up')
screen.onkey(snake.down, 'Down')
screen.onkey(snake.right, 'Right')
screen.onkey(snake.left, 'Left')

game_is_on = True
while game_is_on:
    screen.update()  # the update function shows the animation
    time.sleep(0.1)  # making the snake's tail to head of snake
    snake.move()

    # detect collision with food
    if snake.head.distance(food) < 15:
        food.refresh()
        snake.extend()
        scoreboard.increase_score()

    wall_collision = [
        snake.head.xcor() > 290,
        snake.head.xcor() < -290,
        snake.head.ycor() > 290,
        snake.head.ycor() < -290,
    ]
Ejemplo n.º 12
0
    def make_snake(self):

        for position in STARTING_POSITIONS:
            self.add_segment(position)
        screen = Screen()
        screen.update()
Ejemplo n.º 13
0
scoreboard = Scoreboard()

# Control snake
screen.listen()  # starting listening for keystroke: up, down, left, right
screen.onkey(snake.up,
             "Up")  # bind Up from keyboard to snake object function up
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

# move Snake: tail will follow head
game_is_on = True
while game_is_on:
    # only update screen when all segments move forward
    # screen is updating every 0.1 sec, delay 0.1 sec and refresh screen
    screen.update(
    )  # animation is updated, we can see snake move to next position.
    time.sleep(
        0.1)  # sleep by 1 sec, add 1 sec delay after each segment moves.
    snake.move()

    # Detect collision with food
    if snake.head.distance(
            food
    ) < 15:  # if detect collision with food, food size is 10 x 10 pixel, 15 pixel is a number after trying many time
        food.refresh()  # food should move to new random position
        snake.extend()
        scoreboard.increase_score()  # increase score on scoreboard

    # Detect collision with wall
    if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor(
    ) > 280 or snake.head.ycor() < -280:
Ejemplo n.º 14
0
from turtle import Turtle, Screen


def drawSquare(turtle):
    turtle.goto(100, 0)
    turtle.goto(100, 100)
    turtle.goto(0, 100)
    turtle.goto(0, 0)


screen = Screen()

screen.tracer(0, 0)

screen.onclick(lambda x, y: screen.update())

turtle = Turtle()

drawSquare(turtle)

screen.mainloop()
Ejemplo n.º 15
0
class MazeGraphics(object):
    def __init__(self, config):
        self.width = config.getValueAsInt("maze", "maze_size")
        self.height = config.getValueAsInt("maze", "maze_size")
        self.bg_color = config.getValue("maze", "bg_color")
        self.line_color = config.getValue("maze", "line_color")
        self.line_centroid_color = config.getValue("maze", "line_centroid_color")
        self.forward_centroid_color = config.getValue("maze", "forward_centroid_color")
        self.reverse_centroid_color = config.getValue("maze", "reverse_centroid_color")
        self.path_color = config.getValue("maze", "path_color")
        self.screen = Screen()
        self.setupTurtle(self.width, self.height)

    def setupTurtle(self, width, height):
        self.screen.tracer(False)
        self.screen.screensize(width, height)
        # some basic turtle settings
        self.screen.setworldcoordinates(-1, -1, width + 1, height + 1)
        self.screen.title("Random Turtle Maze")
        self.screen.bgcolor(self.bg_color)
        self.screen.delay(None)
        self.designer = Turtle(visible=False)

    def drawGrid(self):
        for i in xrange(0, self.width + 1):
            self.drawXLines(i, self.width, self.line_color)
        for i in xrange(0, self.height + 1):
            self.drawYLines(i, self.width, self.line_color)
        self.screen.update()

    def drawXLines(self, position, width, color):
        self.drawLines(position, 0, width, color, 90)

    def drawYLines(self, position, width, color):
        self.drawLines(0, position, width, color, 0)

    def drawLines(self, xPosition, yPosition, width, color, heading):
        self.designer.up()
        self.designer.setposition(xPosition, yPosition)
        self.designer.color(color)
        self.designer.down()
        self.designer.setheading(heading)
        self.designer.forward(width)
        self.designer.up()

    def drawCentroid(self, cell, color):
        """
        Draw a centroid for animation purposes but then overwrite it.
        """
        self.designer.setposition(cell.centroid)
        self.designer.dot(5, color)
        self.screen.update()
        self.designer.dot(5, self.bg_color)

    def removeWall(self, posx, posy, heading, color):
        """
            We tear down walls to build the maze
        """
        self.designer.up()
        self.designer.setposition(posx, posy)
        self.designer.down()
        self.designer.color(color)
        self.designer.setheading(heading)
        self.designer.forward(1)
        self.designer.up()
        self.screen.update()

    def drawPath(self, cell1, cell2):
        """
            This draws a line for the solution as it's worked out.
        """
        self.designer.setposition(cell1.centroid)
        self.designer.color(self.path_color)
        direction = self.getDirection(cell1, cell2)
        if direction == "N":
            self.designer.setheading(90)
            self.designer.down()
            self.designer.forward(1)
            self.designer.up()
        elif direction == "S":
            self.designer.setheading(270)
            self.designer.down()
            self.designer.forward(1)
            self.designer.up()
        elif direction == "W":
            self.designer.setheading(0)
            self.designer.down()
            self.designer.forward(1)
            self.designer.up()
        elif direction == "E":
            self.designer.setheading(0)
            self.designer.down()
            self.designer.backward(1)
            self.designer.up()
        self.drawCentroid(cell2, self.line_centroid_color)
        self.screen.update()

    def getDirection(self, currCell, nextCell):
        direction = None
        if nextCell.x < currCell.x:
            direction = "E"
        elif nextCell.x > currCell.x:
            direction = "W"
        elif nextCell.y < currCell.y:
            direction = "S"
        elif nextCell.y > currCell.y:
            direction = "N"
        return direction
Ejemplo n.º 16
0
score = create_shape(0,260,1,1)
score.hideturtle()
score.write(f"{player_1.p_name} : {player_1.score}\t\t{player_2.p_name} : {player_2.score}",
            align="center", font=("Arial", 24, "bold"))
wind.listen()
wind.onkeypress(player_1.up, "s")
wind.onkeypress(player_1.down, "w")

wind.onkeypress(player_2.up, "Up")
wind.onkeypress(player_2.down, "Down")
wind.cv._rootwindow.resizable(False, False)

player_1.dy = -1
while True:
    try:
        wind.update()

        if game_type == "1":
            player_1.sety(player_1.ycor() + player_1.dy)
            if player_1.ycor() > 250:
                player_1.dy *= -1
            if player_1.ycor() < -250:
                player_1.dy *= -1

        if player_1.score == 10 or player_2.score == 10:
            winner = create_shape(-200, 200, 1, 1)
            winner.color("orange")
            winner.hideturtle()
            w = player_1 if player_1.score > player_2.score else player_2
            winner.write(f"{w.p_name} Win :)", align="center", font=("Arial", 36, "bold"))
            res = messagebox.askokcancel("Play Again", "do you want to play again")
class Game():
    """Make the game loop into a class.
    Responsible for drawing and updating all our objects"""
    def __init__(self):
        # Set up the screen
        self.screen = Screen()
        self.screen.bgcolor("black")
        self.screen.setup(width=650, height=700)
        self.screen.title("Space Invaders")
        self.screen.bgpic("assets\\sprites\\space_invaders_background.gif")

        # Register the shapes
        self.screen.register_shape("assets\\sprites\\invader.gif")
        self.screen.register_shape("assets\\sprites\\player.gif")

        # initial objects
        self.player = Player()
        self.bullet = Bullet(self.player)
        self.score = Score()
        self.border = Border()
        self.game_over = False

        # Create invaders
        self.number_of_enemies = 5
        self.enemies = []
        for i in range(self.number_of_enemies):
            self.enemies.append(Invader())

        # Create keyboard bindings
        self.screen.listen()
        self.screen.onkey(self.player.move_left, "Left")
        self.screen.onkey(self.player.move_right, "Right")
        self.screen.onkey(self.bullet.fire_bullet, "space")

    def play_sound(self, filename):
        winsound.PlaySound("assets\\sounds\\{}".format(filename),
                           winsound.SND_ASYNC)

    def run(self):
        """Make the game loop a function."""

        while True:
            # When game_over is set, stop updating objects
            if not self.game_over:

                # for each enemy
                for invader in self.enemies:

                    # Move the enemy left/right
                    invader.move_left_right()

                    # get the enemy back and down
                    if (invader.xcor() < -280 or invader.xcor() > 280):
                        # Move all enemies down
                        for enemy in self.enemies:
                            enemy.move_down()
                            # Change enemy direction
                            enemy.invader_speed *= -1

                    if invader.ycor() < -250:
                        self.game_over = True
                        print("Game Over")

                    if is_collision(self.bullet, invader) == True:
                        self.play_sound("explosion.wav")
                        self.bullet.reset_positon()
                        self.score.change_score(10)
                        invader.reset_positon()

                    if is_collision(self.player, invader) == True:
                        self.player.hideturtle()
                        invader.hideturtle()
                        self.game_over = True
                        print("Game Over")

                # Move the bullet
                if self.bullet.state == "fire":
                    self.bullet.move_up()

                # Check to see if bullet has gone to the top
                if self.bullet.ycor() > 275:
                    self.bullet.reset_positon()

                # Display the screen.
                self.screen.update()

            else:
                break
        # pause game
        input("Press enter to finish")
Ejemplo n.º 18
0
class NCSimVisualizer:
    def __init__(self, cfg_os):
        # Create Screen Object
        self.screen = Screen()

        # Add app icon
        LOGO_PATH = "assets/favicon.ico"
        # do not forget "@" symbol and .xbm format for Ubuntu
        LOGO_LINUX_PATH = "@assets/favicon_linux.xbm"

        # Use the same Tk root with turtle:
        # noinspection PyProtectedMember
        # assert isinstance(self.screen._root, tk.Tk)  # True
        # noinspection PyProtectedMember
        self.root = self.screen.getcanvas().winfo_toplevel()
        self.root.title("Network Coding Simulator")

        if cfg_os.lower() == "linux":
            self.root.iconbitmap(LOGO_LINUX_PATH)
        else:
            self.root.iconbitmap(LOGO_PATH)

        # tkinter use same root
        self.controls = tk.Frame(self.root)

        # Create Screen Layout Cursor
        self.layout_cursor = Turtle()
        self.layout_cursor.ht()
        self.layout_cursor.penup()
        self.layout_cursor.pensize(3)
        self.layout_cursor.color("slate grey")

        # Create Screen Message Cursor
        self.msg_cursor = Turtle()
        self.msg_cursor.ht()
        self.msg_cursor.penup()
        self.msg_cursor.color("midnight blue")

        # Create Screen coverage Cursor
        self.coverage_cursor = Turtle()
        self.coverage_cursor.ht()
        self.coverage_cursor.penup()
        self.coverage_cursor.pensize(2)
        self.coverage_cursor.color("saddle brown")

        # Create Screen Send Packet Cursor
        self.snd_pckt = Turtle()
        self.snd_pckt.ht()
        self.snd_pckt.penup()
        self.snd_pckt.pensize(2)
        self.snd_pckt.color("saddle brown")

        # Call Screen Init Method
        self.screen_init()

    def screen_init(self):
        # Set Screen Dimensions and Coloring
        self.screen.setup(TOTAL_WIDTH, TOTAL_HEIGHT)
        self.screen.bgcolor(SCREEN_BGCOLOR)

        self.layout_cursor.color("slate grey")
        self.layout_cursor.setposition(-((TOTAL_WIDTH / 2) - SCREEN_MARGIN),
                                       -((TOTAL_HEIGHT / 2) - SCREEN_MARGIN))

        self.layout_cursor.speed(8)
        self.layout_cursor.pendown()
        self.layout_cursor.fd(SCREEN_WIDTH)
        self.layout_cursor.rt(-90)
        self.layout_cursor.fd(SCREEN_HEIGHT)
        self.layout_cursor.rt(-90)
        self.layout_cursor.fd(SCREEN_WIDTH)
        self.layout_cursor.rt(-90)
        self.layout_cursor.fd(SCREEN_HEIGHT)
        self.layout_cursor.setheading(90)
        self.layout_cursor.fd(MESSAGE_MARGIN)
        self.layout_cursor.setheading(0)
        self.layout_cursor.fd(SCREEN_WIDTH)

        self.layout_cursor.penup()
        self.layout_cursor.speed("fastest")
        self.layout_cursor.color("midnight blue")

        x_cor = 0
        y_cor = int((TOTAL_HEIGHT / 2) - (3 / 4 * HEAD_MARGIN))
        self.layout_cursor.setposition(x_cor, y_cor)
        self.layout_cursor.write(f"{SCREEN_HEADER}",
                                 align="Center",
                                 font=("Calibri", HEADER_FONT_SIZE, "bold"))

        x_cor = 20 - (int(SCREEN_WIDTH / 2))
        y_cor = (int(TOTAL_HEIGHT / 2)) - (HEAD_MARGIN + 40)
        self.layout_cursor.setposition(x_cor, y_cor)
        self.layout_cursor.write(f"Topology: {TOPOLOGY_TYPE.title()}",
                                 align="Left",
                                 font=("Calibri", TEXT_FONT_SIZE, "bold"))

        x_cor = (int(SCREEN_WIDTH / 2)) - 20
        y_cor = (int(TOTAL_HEIGHT / 2)) - (HEAD_MARGIN + 40)
        self.layout_cursor.setposition(x_cor, y_cor)
        self.layout_cursor.write(f"Nodes: {NUM_OF_NODES}",
                                 align="Right",
                                 font=("Calibri", TEXT_FONT_SIZE, "bold"))

        self.visual_output_msg("This where the text message appears")

        # Stop Auto-update Screen changes
        self.screen.tracer(0)

    def visual_output_msg(self, message):
        x_cor = 20 - (int(SCREEN_WIDTH / 2))
        y_cor = (SCREEN_MARGIN + 15) - (int(TOTAL_HEIGHT / 2))
        self.msg_cursor.setposition(x_cor, y_cor)
        self.msg_cursor.clear()
        self.msg_cursor.write(f"{message}",
                              align="Left",
                              font=("Calibri", TEXT_FONT_SIZE, "bold"))

    def visual_send_packet(self, tx_node, rx_nodes):
        # draw arrow for all neighbors
        for rx_node in rx_nodes:
            self.snd_pckt.setposition(tx_node.pos())
            self.snd_pckt.pendown()
            self.snd_pckt.setheading(self.snd_pckt.towards(rx_node.pos()))
            self.snd_pckt.setposition(rx_node.pos())
            self.snd_pckt.bk(11)

            # Drawing arrow head
            self.snd_pckt.left(45)
            self.snd_pckt.backward(10)
            self.snd_pckt.forward(10)
            self.snd_pckt.right(90)
            self.snd_pckt.backward(10)
            self.snd_pckt.penup()

    def clear_send_packets(self):
        self.snd_pckt.pd()
        self.snd_pckt.clear()
        self.snd_pckt.pu()

    def show_coverage(self, node):
        self.coverage_cursor.goto(node.xcor(), node.ycor() - node.coverage)
        self.coverage_cursor.pendown()
        self.coverage_cursor.circle(node.coverage)
        self.coverage_cursor.penup()
        self.coverage_cursor.goto(node.pos())

    def hide_coverage(self):
        self.coverage_cursor.pendown()
        self.coverage_cursor.clear()
        self.coverage_cursor.penup()

    def screen_refresh(self):
        self.screen.update()

    def mainloop(self):
        while True:
            try:
                self.root.update()
                self.root.update_idletasks()
            except Exception as exp:
                print(exp)
                print("bye")
                break
Ejemplo n.º 19
0
def main():
    screen = Screen()
    screen.setup(width=800, height=600)
    screen.bgcolor('black')
    screen.title('Pong Game')
    screen.tracer(0)
    score_board = ScoreBoard()
    score_board.display_score()
    CenterLine()
    player1 = Paddle((350, 0))
    player2 = Paddle((-350, 0))
    ball = Ball()
    screen.onkey(player1.move_up, 'Up')
    screen.onkey(player1.move_down, 'Down')
    screen.onkey(player2.move_up, 'w')
    screen.onkey(player2.move_down, 's')
    screen.listen()

    def game_continue():
        if messagebox.askretrycancel("Game Over!!", "Wanna play again? "):
            screen.clear()
            main()

    running = True
    while running:
        time.sleep(0.05)
        screen.update()
        if score_board.check_win():
            score_board.final_result()
            ball.hideturtle()
            break
        if ball.ispoint_wait:
            if ball.point_wait < 50:
                ball.point_wait += 1
                continue
            else:
                ball.ispoint_wait = False
                ball.point_wait = 1
        screen.update()
        ball.move()
        # for not repeating collision if the distance is small
        if player1.is_collided:
            if player1.safe_count < 5:
                player1.safe_count += 1
            else:
                player1.is_collided = False
                player1.safe_count = 1
        elif player2.is_collided:
            if player2.safe_count < 5:
                player2.safe_count += 1
            else:
                player2.is_collided = False
                player2.safe_count = 1

        if ball.ycor() > 265 or ball.ycor() < -270:
            ball.wall_collision()

        if ball.xcor() < 370 and ball.distance(
                player1) < 45 and not player1.is_collided:
            ball.paddle_collision()
            ball.hit_count += 1
            ball.hit = True
            player1.is_collided = True
        elif ball.xcor() > -370 and ball.distance(
                player2) < 45 and not player2.is_collided:
            ball.paddle_collision()
            ball.hit_count += 1
            ball.hit = True
            player2.is_collided = True

        if ball.hit_count % 2 == 0 and ball.hit_count != 0 and ball.hit:
            if ball.bounce_speed < 0:
                ball.bounce_speed -= 1.5
            else:
                ball.bounce_speed += 1.5
            ball.bounce_x = ball.bounce_speed
            ball.hit = False

        if ball.xcor() > 380:
            score_board.clear()
            score_board.score1 += 1
            score_board.display_score()
            ball.ispoint_wait = True
            ball.ball_reset()

        elif ball.xcor() < -380:
            score_board.clear()
            score_board.score2 += 1
            score_board.display_score()
            ball.ispoint_wait = True
            ball.ball_reset()

    screen.update()
    time.sleep(1)
    game_continue()
    screen.bye()
    screen.exitonclick()
starting_positions = [(0, 0), (-20, 0), (-40, 0)]

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True
while game_is_on:
    screen.update()  # 每個方塊都移動完再 update 視窗
    time.sleep(0.1)  # 控制每次 update 視窗的間隔時間
    snake.move()

    # Detect collision with food
    if snake.head.distance(food) < 15:
        food.refresh()
        snake.extend()
        scoreboard.increase_score()

    # Detect collision with wall
    if snake.head.xcor() > 300 or snake.head.xcor() < -300 or snake.head.ycor(
    ) > 300 or snake.head.ycor() < -300:
        # game_is_on = False
        # scoreboard.game_over()
        scoreboard.reset()
Ejemplo n.º 21
0
ball = Ball()
#Create scoreboard from scoreboard class
scoreboard = Scoreboard()
scoreboard.update_scoreboard()

game_is_on = True #Boolean to keep game running

#Functions to control the two paddles from the listen function
screen.onkey(fun=paddle_r.move_up, key="Up")
screen.onkey(fun=paddle_r.move_down, key="Down")
screen.onkey(fun=paddle_l.move_up, key="w")
screen.onkey(fun=paddle_l.move_down, key="s")

while game_is_on: #Loop to keep updating screen
    time.sleep(0.1) #Timer to slow down loop
    screen.update() #Manually update screen since tracer function disabled the updating
    ball.start_moving() #Function from ball class to move the ball

    # Detect wall collision
    if ball.ycor() > 290 or ball.ycor() < -290: #If ball hits the top and bottom of screen it will bounce off
        ball.y_bounce()

    # Detect collision with right paddle
    if ball.distance(paddle_r) < 50 and ball.xcor() > 320 or ball.distance(paddle_l) < 50 and ball.xcor() < -320:
        ball.x_bounce() #If ball hits one of the paddles it will bounce off and pick up speed
        ball.increase_speed()

    # Detect back wall collision
    if ball.xcor() > 380:
        ball.reset_ball() #If ball hits right wall behind the paddle the ball resets and the left player gets a point
        scoreboard.l_point()
Ejemplo n.º 22
0
# Enemy ships movement control variables
index_movement = 0
enemy_movement = [10, 10, -10, -10,
                  -10, -10, 10, 10]  # The enemy ships can only move left (- negative values) or right (positive values)
# by the following values

# player lives
lives = 3
points = 0
score = Scoreboard(lives, points)

game_is_on = True
while game_is_on:
    time.sleep(0.02)
    game_screen.update()
    player_ship_x_position = player_ship.xcor()

    # check if player bullet reach end of screen and delete them if so
    for bullet in player_bullets:
        if bullet.ycor() >= Y_WALL:
            player_bullets.remove(bullet)
        else:
            bullet.bullet_moving()

    # shoot enemy bullets and move the ships
    if (time.time() - timer) > difference:
        if number_bullets >= len(enemy.ships_list):
            number_bullets = len(enemy.ships_list)
        shot_bullet_enemy(enemy.ships_list, number_bullets)
        enemy.moving(enemy_movement[index_movement])
Ejemplo n.º 23
0
paddle_2 = Paddle((-360, 0))
ball = Ball()
scoreboard = Scoreboard()

# game input controls
screen.listen()
screen.onkey(paddle_1.go_up, "Up")
screen.onkey(paddle_1.go_down, "Down")

screen.onkey(paddle_2.go_up, "a")
screen.onkey(paddle_2.go_down, "z")

# game loop
while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()  # removes starting animations
    ball.move()
    # detect collision with floor or ceiling
    if ball.ycor() > 280 or ball.ycor() < -280:
        ball.bounce_y()
    # detect collision with paddles
    if ball.distance(paddle_1) < 50 and ball.xcor() > 320 or ball.distance(
            paddle_2) < 50 and ball.xcor() < -330:
        ball.bounce_x()
    # detect collision with back walls
    if ball.xcor() > 380:
        ball.move_speed = 0.1
        time.sleep(0.3)
        ball.goto(0, 0)
        ball.x_move *= -1
        scoreboard.player_2_point()
Ejemplo n.º 24
0
pantalla.tracer(0)

serpiente = Serpientes()
comida = Comida()
puntaje = Puntaje()

pantalla.listen()
pantalla.onkey(serpiente.arriba, "Up")
pantalla.onkey(serpiente.abajo, "Down")
pantalla.onkey(serpiente.izquierda, "Left")
pantalla.onkey(serpiente.derecha, "Right")

juego_encendido = True

while juego_encendido:
    pantalla.update()
    time.sleep(0.1)
    serpiente.movimiento()

    #Detectar contacto con la comida
    if serpiente.head.distance(comida) < 15:
        comida.refrescar()
        serpiente.extender()
        puntaje.mostrar_puntaje()

    #Detectar contacto con paredes (Game over)
    if serpiente.head.xcor() > 290 or serpiente.head.xcor(
    ) < -290 or serpiente.head.ycor() > 290 or serpiente.head.ycor() < -290:
        juego_encendido = False
        puntaje.juego_terminado()
Ejemplo n.º 25
0
class Application:
    def __init__(self, apptitle):
        # Constants
        self.task_list = [
            "1",  # Draw the UK Flag
            "2",  # Draw the Australia flag
            "3",  # Exit
        ]

        # Variable initializations
        self.task = ""
        self.apptitle = apptitle

    # Initialize Turtle graphic engine
    def __init_gui__(self):
        # Screen initializations
        self.win = Screen()
        self.win.title(self.apptitle)
        self.win.bgcolor(bgcolor)
        self.win.tracer(
            0
        )  # Turn off turtle animation for instant rendering, to be used with win.update()

        # Pen initializations
        self.pen = Turtle()
        self.pen.hideturtle()

    # Main loop
    def main(self):
        # Menu loop: Display a console menu in this format:
        #
        #       ***************************
        #       1. Draw UK flag
        #       2. Draw Australia flag
        #       3. Exit
        #       Enter an option (1/2/3):
        #
        # Then execute the task according to user input, display an error message if user input is invalid
        while self.task not in self.task_list:
            print(
                "***************************\n1. Draw UK flag\n2. Draw Australia flag\n3. Exit"
            )
            self.task = input("Enter an option (1/2/3): ")
            if self.task == self.task_list[0]:
                self.__init_gui__()
                self.win.title("United Kingdoms Flag")
                flag = UKFlag(self.pen)
                flag.draw()
                self.win.update()
                self.win.exitonclick()
            elif self.task == self.task_list[1]:
                self.__init_gui__()
                self.win.title("Australia Flag")
                flag = AustraliaFlag(self.pen)
                flag.draw()
                self.win.update()
                self.win.exitonclick()
            elif self.task == self.task_list[2]:
                print("Program exits. Have a nice day!")
            else:
                print("Invalid option")
Ejemplo n.º 26
0
           
            
            #This ends the game when a player has a score of 100, and announces the winner. 
            if self.score > 95:
                self.pen.goto(0,0)
                self.pen.color('black')
                self.pen.fillcolor('black')
                self.pen.shapesize(outline=20)
                self.pen.write('Player {}  is the winner!'.format(self.player), align='center', font=('courier', 40, 'bold'))
                wn.mainloop()
          
#Creates two player instances
player1 = Snake((-30,30), 'red', '1', -200, 360)
player2 = Snake((30,30), 'blue', '2', 200, 360)

#creates the game loop that calls the functions on the instances. 
while True:
    player1.move('a', 'd', 'w', 's')
    player1.border_c()
    player1.turn()
    player1.scores()

    player2.move('j', 'l', 'i', 'k')
    player2.turn()
    player2.border_c()
    player2.scores()

    wn.update()

wn.mainloop()
Ejemplo n.º 27
0
class Game():
    def __init__(self):
        self.gameRunns = True
        self.gamePaused = True

        self.screen = Screen()
        self.screen.setup(width=SCREEN_WIDTH, height=SCREEN_HIGHT)
        self.screen.bgcolor("black")
        self.screen.tracer(0)
        self.screen.title("...SnAkE....")
        self.screen.onkeypress(self.pauseMode, "space")
        self.screen.onkeypress(self.exitGame, "Escape")

    def pauseMode(self):
        self.gamePaused = not self.gamePaused

    def exitGame(self):
        print("closing")
        self.gameRunns = False

    def play(self):
        GameBoard(SCREEN_WIDTH)

        snake = Snake(3)
        snake.registerKeyListener(self.screen)

        food = Food()

        scoreBoard = ScoreBoard()

        while self.gameRunns:
            start = time.time()

            if not self.gamePaused:
                scoreBoard.update_scoreboard()
                snake.show()
                food.show()

                snake.move()

                if self.recognize_collision(snake, food, scoreBoard):
                    snake.hide()
                    food.hide()
                    scoreBoard.game_over()
                    snake.reset()

            else:
                scoreBoard.pause()
                snake.hide()
                food.hide()

            self.screen.update()
            time.sleep(max(1.0 / snake.speed - (time.time() - start), 0))

        self.screen.exitonclick()

    def recognize_collision(self, snake, food, scoreBoard):

        game_over = False
        if snake.head.distance(food) < COLLISION_DISTANCE:
            snake.extend()
            food.refresh()
            scoreBoard.increase_score()

        if snake.head.xcor() > 298 or snake.head.xcor(
        ) < -298 or snake.head.ycor() > 298 or snake.head.ycor() < -298:
            return True

        for segment in snake.snake[1:]:
            if snake.head.distance(segment) < COLLISION_DISTANCE:
                return True
Ejemplo n.º 28
0
scr.tracer(0)
scr.listen()

game_end = False

player_1 = Paddle("Player_1")
player_2 = Paddle("Player_2")
field = Field()
score = ScoreBoard()
ball = Ball()


def is_game_over():
    global game_end
    game_end = True


while not game_end:
    scr.update()

    scr.onkeypress(fun=is_game_over, key="e")
    scr.onkeypress(fun=player_1.move_up, key="Up")
    scr.onkeypress(fun=player_1.move_down, key="Down")

    scr.onkeypress(fun=player_2.move_up, key="w")
    scr.onkeypress(fun=player_2.move_down, key="s")

    ball.move(player_1, player_2, score)

    t.sleep(0.001)
Ejemplo n.º 29
0
class Game:
    def __init__(self):
        self.screen = Screen()
        self.artist = Turtle(visible=False)
        self.artist.up()
        self.artist.speed("slowest")

        self.snake = Snake()
        self.food = Food(100, 0)
        self.counter = 0
        self.commandpending = False #command pending
        self.screen.tracer(0)

        self.screen.listen()
        self.screen.onkey(self.snakedown, "Down")
        self.screen.onkey(self.snakeup, "Up")
        self.screen.onkey(self.snakeleft, "Left")
        self.screen.onkey(self.snakeright, "Right")

    def snakeup(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveup()
            self.commandpending = False

    def snakedown(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.movedown()
            self.commandpending = False

    def snakeleft(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveleft()
            self.commandpending = False

    def snakeright(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveright()
            self.commandpending = False

    def nextFrame(self):
        self.artist.clear()
        if (self.snake.nextposition[0], self.snake.nextposition[1]) == (self.food.x, self.food.y):
            self.snake.eatFood()
            self.food.changelocation()
        else:
            self.snake.moveOneStep()

        if self.counter == 10:
            self.food.changestate()
            self.counter = 0
        else:
            self.counter += 1

        self.food.drawself(self.artist)  # show the food and snake
        self.snake.drawself(self.artist)
        self.screen.update()
        self.screen.ontimer(lambda: self.nextFrame(), 100)
Ejemplo n.º 30
0

snake = Snake()
food = Food()
scores = ScoreBoard()


sc.listen()
sc.onkey(snake.up, "Up")
sc.onkey(snake.down, "Down")
sc.onkey(snake.left, "Left")
sc.onkey(snake.right, "Right")

game = True
while game:
    sc.update()
    time.sleep(0.1)
    snake.move()

    if snake.head.distance(food) < 15:
        food.refresh()
        snake.extend()
        scores.update_score()

    if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
        game = False
        scores.game_over()

    for segments in snake.turtle_list[1:]:
        if snake.head.distance(segments) < 10:
            game = False
Ejemplo n.º 31
0
class Window:
    def __init__(self, size):
        # Some basic stuff.
        self.window = Screen()
        self.window.title("Pong Game for AGH")
        self.window.bgcolor("white")
        self.window.setup(
            width=size[0], height=size[1]
        )  # Set size from file. (It is converted to tuple before).
        self.window.tracer(0)  # Allow draw things immediately.
        self.vertical_margin = 60  # Margin for area.
        self.horizontal_margin = 20
        # Setting our game area - place where ball is moving and paddles.
        self.top = self.window.window_height() / 2 - self.vertical_margin
        self.bottom = -self.window.window_height() / 2 + self.vertical_margin
        self.left = -self.window.window_width() / 2 + self.horizontal_margin
        self.right = self.window.window_width() / 2 - self.horizontal_margin
        # Making (drawing) area.
        self.area = Turtle()
        self.area.hideturtle()  # Hide turtle on the screen.
        self.area.penup()  # No drawing when moving.
        self.area.goto(self.right, self.top)
        self.area.pendown()  # Pull the pen down - start drawing.
        self.area.goto(self.left, self.top)
        self.area.goto(self.left, self.bottom)
        self.area.goto(self.right, self.bottom)
        self.area.goto(self.right, self.top)
        # Initialization of score writing and pause text.
        self.score_turtle = Turtle()
        self.score_turtle.penup()
        self.score_turtle.hideturtle()
        self.pause_text = Turtle()
        self.pause_text.hideturtle()

    def update(self):  # Update method for main.
        self.window.update()

    def add_shape(self, shape, str):  # Add shape to window.
        self.window.register_shape(str, shape)

    def get_area(self):  # Return area size. (Needed for ball and paddles)
        area = []
        area.append(self.top)
        area.append(self.bottom)
        area.append(self.left)
        area.append(self.right)
        return area

    def write_scores(self, score):
        self.score_turtle.clear()
        # Go to above and below paddles and write score.
        self.score_turtle.goto(
            0,
            self.window.window_height() / 2 - self.vertical_margin)
        self.score_turtle.write(score[0],
                                align="center",
                                font=("Arial", 32, "bold"))
        self.score_turtle.goto(
            0, -self.window.window_height() / 2 + self.vertical_margin / 6)
        self.score_turtle.write(score[1],
                                align="center",
                                font=("Arial", 32, "bold"))

    def write_pause(self, pause):
        if pause == True:
            self.pause_text.penup()  # No drawing when moving.
            self.pause_text.goto(0, 0)  # Go to middle of the screen and write.
            self.pause_text.write("PAUSE. CLICK P AGAIN TO RESUME",
                                  align="center",
                                  font=("Arial", 18, "bold"))
        if pause == False:
            self.pause_text.undo()  # Undo previously written text.
Ejemplo n.º 32
0
class Game:
    def __init__(self):
        # game object has a screen, a turtle, a basic snake and a food
        self.screen = Screen()
        self.artist = Turtle(visible=False)
        self.artist.up()
        self.artist.speed("slowest")

        self.snake = Snake()
        self.food = Food(100, 0)
        self.counter = 0  # this will be used later
        self.commandpending = False  # as will this

        self.screen.tracer(0)  # follow it so far?

        self.screen.listen()
        self.screen.onkey(self.snakedown, "Down")
        self.screen.onkey(self.snakeup, "Up")
        self.screen.onkey(self.snakeleft, "Left")
        self.screen.onkey(self.snakeright, "Right")

    def nextFrame(self):
        self.artist.clear()

        if (self.snake.nextposition[0],
                self.snake.nextposition[1]) == (self.food.x, self.food.y):
            self.snake.eatFood()
            self.food.changelocation()
        else:
            self.snake.moveOneStep()

        if self.counter == 10:
            self.food.changestate()  # makes the food flash slowly
            self.counter = 0
        else:
            self.counter += 1

        self.food.drawself(self.artist)  # show the food and snake
        self.snake.drawself(self.artist)
        self.screen.update()
        self.screen.ontimer(lambda: self.nextFrame(), 100)

    def snakeup(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveup()
            self.commandpending = False

    def snakedown(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.movedown()
            self.commandpending = False

    def snakeleft(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveleft()
            self.commandpending = False

    def snakeright(self):
        if not self.commandpending:
            self.commandpending = True
            self.snake.moveright()
            self.commandpending = False
Ejemplo n.º 33
0
tileSize = 32
number_of_initial_live_tiles = 100

numberOfTiles = [map_size, map_size]
screenSize = [
    numberOfTiles[0] * (tileSize + 1) - 1,
    numberOfTiles[1] * (tileSize + 1) - 1
]

screen = Screen()
screen.setup(screenSize[0], screenSize[1])
screen.setworldcoordinates(-10, -20 - screenSize[1], 20 + screenSize[0], 10)
screen.bgcolor("black")
screen.tracer(0, 0)  #for making drawing instant

screen.onclick(close)

game = Gameboard(numberOfTiles, tileSize, screenSize, screen)
sim = Simulation(game)

random_tuples = np.random.randint(0, map_size,
                                  (number_of_initial_live_tiles, 2)).tolist()
for tpl in random_tuples:
    sim.add_live_cell(tpl)

while not shutdown:
    sim.update_state()
    screen.update()  #for making drawing instant
    sleep(0.1)

screen.mainloop()