반응형
반응형

turtle 로 전체화면에서 임의로 선그리기 

 

import turtle
import random

# 화면 설정
def setup_screen():
    """창을 설정하고 전체 화면과 유사하게 최대화합니다."""
    screen = turtle.Screen()
    screen.setup(width=1.0, height=1.0) # 화면 크기를 최대화합니다.
    screen.title("무작위 선 그리기 (전체 화면)")
    screen.colormode(255) # RGB 색상 모드를 0-255로 설정합니다.
    screen.bgcolor("black") # 배경색을 검은색으로 설정합니다.
    screen.tracer(0) # 그리기 속도를 높이기 위해 자동 화면 업데이트를 끕니다.
    return screen

# 거북이 설정
def setup_turtle():
    """선을 그릴 거북이를 설정합니다."""
    t = turtle.Turtle()
    t.hideturtle() # 거북이 아이콘을 숨깁니다.
    t.speed(0) # 최고 속도로 설정합니다.
    t.pensize(2) # 펜 두께를 설정합니다.
    return t

# 무작위 색상 생성
def get_random_color():
    """무작위 RGB 색상 튜플을 반환합니다."""
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    return (r, g, b)

# 메인 그리기 루프
def draw_random_lines(t, screen):
    """화면이 종료될 때까지 무작위 선을 계속 그립니다."""
    while True:
        # 무작위 색상 및 위치 설정
        color = get_random_color()
        t.pencolor(color)
        
        # 펜을 든 상태로 무작위 위치로 이동 (현재 위치에서 그리기 시작)
        t.left(random.randint(-180, 180)) # 무작위로 방향을 돌립니다.
        
        # 무작위 길이만큼 앞으로 이동 (선을 그림)
        distance = random.randint(50, 300)
        t.forward(distance)

        # 화면 가장자리를 벗어났는지 확인하고, 벗어났다면 펜을 들고 중앙 근처로 이동
        # 이 과정이 없으면 거북이가 화면 밖으로 나가버려 그림이 멈춘 것처럼 보일 수 있습니다.
        current_x, current_y = t.position()
        screen_width = screen.window_width()
        screen_height = screen.window_height()
        
        if abs(current_x) > screen_width / 2 or abs(current_y) > screen_height / 2:
            t.penup() # 펜 들기
            t.goto(0, 0) # 중앙으로 이동
            t.left(random.randint(-180, 180)) # 방향을 다시 무작위로 설정
            t.pendown() # 펜 내리기
            
        # 화면 업데이트 (tracer(0)를 사용했으므로 수동으로 업데이트)
        screen.update()

# 프로그램 실행
if __name__ == "__main__":
    screen = setup_screen()
    t = setup_turtle()
    
    try:
        draw_random_lines(t, screen)
    except turtle.Terminator:
        # 창 닫기 버튼을 눌렀을 때 발생하는 예외 처리
        print("프로그램이 종료되었습니다.")
    except Exception as e:
        print(f"예외 발생: {e}")
        
    # 창을 닫을 때까지 프로그램이 대기하도록 함 (실제 draw_random_lines 루프에서는 필요 없음)
    # turtle.done()
반응형
반응형

[python] Code: Turtle Yellow Heart on Black Background

 

import turtle

def draw_heart():
    # Setup the screen
    screen = turtle.Screen()
    screen.bgcolor("black")  # Set background color to black
    screen.title("Yellow Heart")

    # Setup the turtle
    heart = turtle.Turtle()
    heart.shape("turtle")
    heart.speed(10)  # Set drawing speed
    heart.color("yellow")  # Set the pen color to yellow
    heart.fillcolor("yellow")  # Set the fill color to yellow

    # Start drawing the heart
    heart.begin_fill()
    heart.left(50)  # Tilt left to start the heart shape
    heart.forward(133)  # Draw the left curve

    # Left curve
    heart.circle(50, 200)  # Radius 50, 200 degrees

    # Right curve
    heart.right(140)  # Turn right to align for the other half
    heart.circle(50, 200)  # Radius 50, 200 degrees
    heart.forward(133)  # Complete the right curve
    heart.end_fill()  # Fill the shape with the selected color

    # Finish up
    heart.hideturtle()  # Hide the turtle pointer
    screen.mainloop()  # Keep the window open

# Call the function
if __name__ == "__main__":
    draw_heart()

반응형
반응형

https://docs.python.org/ko/3/library/turtle.html

 

turtle — Turtle graphics

Source code: Lib/turtle.py Introduction: Turtle graphics is an implementation of the popular geometric drawing tools introduced in Logo, developed by Wally Feurzeig, Seymour Papert and Cynthia Solo...

docs.python.org

turtle — 터틀 그래픽

소스 코드: Lib/turtle.py


소개

Turtle graphics is an implementation of the popular geometric drawing tools introduced in Logo, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.

Turtle star

turtle은 간단한 움직임을 반복하는 프로그램을 사용하여 복잡한 모양을 그릴 수 있습니다.

In Python, turtle graphics provides a representation of a physical “turtle” (a little robot with a pen) that draws on a sheet of paper on the floor.

It’s an effective and well-proven way for learners to encounter programming concepts and interaction with software, as it provides instant, visible feedback. It also provides convenient access to graphical output in general.

Turtle drawing was originally created as an educational tool, to be used by teachers in the classroom. For the programmer who needs to produce some graphical output it can be a way to do that without the overhead of introducing more complex or external libraries into their work.

Tutorial

New users should start here. In this tutorial we’ll explore some of the basics of turtle drawing.

Starting a turtle environment

In a Python shell, import all the objects of the turtle module:

from turtle import *

If you run into a No module named '_tkinter' error, you’ll have to install the Tk interface package on your system.

Basic drawing

Send the turtle forward 100 steps:

forward(100)

You should see (most likely, in a new window on your display) a line drawn by the turtle, heading East. Change the direction of the turtle, so that it turns 120 degrees left (anti-clockwise):

left(120)

Let’s continue by drawing a triangle:

forward(100)
left(120)
forward(100)

Notice how the turtle, represented by an arrow, points in different directions as you steer it.

Experiment with those commands, and also with backward() and right().

펜 제어

Try changing the color - for example, color('blue') - and width of the line - for example, width(3) - and then drawing again.

You can also move the turtle around without drawing, by lifting up the pen: up() before moving. To start drawing again, use down().

The turtle’s position

Send your turtle back to its starting-point (useful if it has disappeared off-screen):

home()

The home position is at the center of the turtle’s screen. If you ever need to know them, get the turtle’s x-y co-ordinates with:

pos()

Home is at (0, 0).

And after a while, it will probably help to clear the window so we can start anew:

clearscreen()

Making algorithmic patterns

Using loops, it’s possible to build up geometric patterns:

for steps in range(100):
    for c in ('blue', 'red', 'green'):
        color(c)
        forward(steps)
        right(30)

- which of course, are limited only by the imagination!

Let’s draw the star shape at the top of this page. We want red lines, filled in with yellow:

color('red')
fillcolor('yellow')

Just as up() and down() determine whether lines will be drawn, filling can be turned on and off:

begin_fill()

Next we’ll create a loop:

while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break

abs(pos()) < 1 is a good way to know when the turtle is back at its home position.

Finally, complete the filling:

end_fill()

(Note that filling only actually takes place when you give the end_fill() command.)

How to…

This section covers some typical turtle use-cases and approaches.

Get started as quickly as possible

One of the joys of turtle graphics is the immediate, visual feedback that’s available from simple commands - it’s an excellent way to introduce children to programming ideas, with a minimum of overhead (not just children, of course).

The turtle module makes this possible by exposing all its basic functionality as functions, available with from turtle import *. The turtle graphics tutorial covers this approach.

It’s worth noting that many of the turtle commands also have even more terse equivalents, such as fd() for forward(). These are especially useful when working with learners for whom typing is not a skill.

You’ll need to have the Tk interface package installed on your system for turtle graphics to work. Be warned that this is not always straightforward, so check this in advance if you’re planning to use turtle graphics with a learner.

Use the turtle module nam

반응형

+ Recent posts