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 s, sun
    s = Screen()
    s.setup(800, 600, 50, 50)
    s.screensize(750, 550)
    createPlanetShape()
    ## setup gravitational system
    s.setworldcoordinates(-hfw*4/3, -hfw, hfw*4/3, hfw)
    gs = GravSys()
    sun = Star(mS, Vec2D(0.,0.), Vec2D(0.,0.), gs, "circle")
    sun.color("yellow")
    sun.turtlesize(1.8)
    sun.pu()
    earth = Star(mE, Vec2D(rE,0.), Vec2D(0.,vE), gs, "planet")
    earth.pencolor("green")
    earth.shapesize(0.8)
    mercury = Star(mME, Vec2D(0., perihelME), Vec2D(-perihelvME, 0),
                                                        gs, "planet")
    mercury.pencolor("blue")
    mercury.shapesize(0.5)
    venus = Star(mVE, Vec2D(-rVE, 0.), Vec2D(0., -vVE), gs, "planet")
    venus.pencolor("blue")
    venus.shapesize(0.65)
    mars = Star(mMA, Vec2D(0., -rMA), Vec2D(vMA, 0.), gs, "planet")
    mars.pencolor("blue")
    mars.shapesize(0.45)
    gs.init()
    gs.start()
    return "Done!"
class World(object):
    def __init__(self, index, size_x, size_y):
        self.index = index
        self.canvas = Screen()
        self.canvas.setup(size_x, size_y)

    def show_world(self):
        #self.canvas.ontimer(god.slowly_kill_humans(), 100)
        self.canvas.exitonclick()
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!"
Example #5
0
class MHManager(Turtle):
    """Special Turtle, perform the task to manage the Moorhuhn-GUI.
    """
    def __init__(self, w, h):
        Turtle.__init__(self, visible=False)
        self.screen = Screen()
        self.screen.setup(w, h)
        self.speed(0)
        self.penup()
        self.goto(-WINWIDTH//2 + 50, -WINHEIGHT//2 + 20)
        self.pencolor("yellow")
    def message(self, txt):
        """Output text to graphics window.
        """
        self.clear()
        self.write(txt, font=("Courier", 18, "bold"))
Example #6
0
def main():
    global s, sun
    s = Screen()
    s.setup(800, 600)
    s.screensize(750, 550)
    createPlanetShape()
    ## setup gravitational system
    s.setworldcoordinates(-4.e11, -3.e11, 4.e11, 3.e11)
    gs = GravSys()
    sun = Star(mS, Vec2D(0.,0.), Vec2D(0.,0.), gs, "circle")
    sun.color("yellow")
    sun.turtlesize(1.2)
    sun.pu()
    earth = Star(mE, Vec2D(rE,0.), Vec2D(0.,vE), gs, "planet")
    earth.pencolor("green")
    gs.init()
    gs.start()
    return "Done!"
def principal():
    janela = Screen()
    janela.setup(800,600)
    janela.title('Digimon, digitais, Digimon são campeões!')
    janela.bgcolor('white')
    carregaimagens('personagens', janela)
    carregaimagens ('digimons', janela)
    carregaimagens('digimonftowners', janela)
    carregaimagens('fundos', janela)
    cria_personagens()
    abertura(janela)
    ato2(janela)
    ato3(janela)
    ato4(janela)
    ato5(janela)
    ato6(janela)
    ato7(janela)
    ato8(janela)
    #finale(janela)
    fechamento(janela)
    debora_animacao(janela)
Example #8
0
        offsetX[color] = randoms
        turtles[color].goto(x=randoms, y=offsetY[color])


def stats():
    key_max = max(offsetX, key=offsetX.get)
    if offsetX[key_max] >= 225:
        return False
    else:
        return True


def winner(win, bet):
    if win.capitalize() == str(bet).capitalize():
        print(f"Congrats {win} turtle win the game, You win")
    else:
        print(f"You lose, Winner is {win}  turtle")


screen = Screen()
screen.setup(height=400, width=500)
user_bet = screen.textinput(title="Put Your Bet", prompt="Choose the color")
start()
while stats():
    move()

key = max(offsetX, key=offsetX.get)

winner(key, user_bet)
screen.exitonclick()
from turtle import Turtle, Screen
import random

# setting up the screen and the user guess
screen = Screen()
screen.setup(500, 400)
user_bet = screen.textinput(
    title='Make your bets',
    prompt='Which turtle will win the race? Enter a color: ')
colors = ['red', 'blue', 'green', 'yellow', 'orange', 'purple']
y_position = [-100, -60, -20, 20, 60, 100]
all_turtles = []

# creating the racers
for x in range(0, 6):
    new_turtle = Turtle(shape='turtle')
    new_turtle.penup()
    new_turtle.color(colors[x])
    new_turtle.goto(x=-230, y=y_position[x])
    all_turtles.append(new_turtle)

if user_bet:
    is_race_on = True

# sets up the running of the race
while is_race_on:

    for turtle in all_turtles:
        if turtle.xcor() > 230:
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
Example #10
0
def main():
    # TODO 1: Configure screen
    screen = Screen()
    screen.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
    screen.bgcolor(SCREEN_BACKGROUND_COLOR)
    screen.tracer(0)

    # Add borders
    border = Border()
    border.createBorder()

    # TODO 2: Configure initial snake
    snake = Snake()
    food = Food()
    scoreboard = Scoreboard()

    # TODO 3: Move the snake
    screen.listen()
    screen.onkey(snake.up, "Up")
    screen.onkey(snake.down, "Down")
    screen.onkey(snake.left, "Left")
    screen.onkey(snake.right, "Right")

    #global paused

    #def unpause():
    #    global paused
    #    paused = not paused

    #screen.onkey(unpause, "p")

    game_is_on = True
    while game_is_on:
        #while paused:
        #    sleep(0.2)
        screen.update()
        sleep(SLEEP_TIME)
        snake.move()

        # TODO 4: Detect collision with food
        snake_food_collision_distance = (
            food.width() + snake.head.width()) / 2 - COLLISION_ERROR
        if snake.head.distance(food) < snake_food_collision_distance:
            scoreboard.score += 1
            snake.add_segment()
            food.refresh()
            for segment in snake.tail:
                while segment.position() == food.position():
                    food.clear()
                    food.refresh()
            scoreboard.refresh()

        # TODO 5: Detect collision with walls
        pass_x_wall = (
            snake.head.xcor() < -SCREEN_WIDTH / 2 + snake.head.width()
            or snake.head.xcor() > SCREEN_WIDTH / 2 - snake.head.width())
        pass_y_wall = (
            snake.head.ycor() < -SCREEN_HEIGHT / 2 + snake.head.width()
            or snake.head.ycor() > SCREEN_HEIGHT / 2 - snake.head.width())
        wall_collision = pass_x_wall or pass_y_wall
        if wall_collision:
            scoreboard.resetHighestScore()
            snake.resetSnake()

        # TODO 6: Detect collision with tail
        tail_head_collision_distance = snake.head.width() - COLLISION_ERROR
        for segment in snake.tail[1:]:
            if segment.distance(snake.head) < tail_head_collision_distance:
                scoreboard.resetHighestScore()
                snake.resetSnake()

    screen.exitonclick()
Example #11
0
from turtle import Turtle, Screen
import datetime

# get the current time and convert to the hand's angles
wn = Screen()
wn.title("Clock")
wn.bgcolor("saddlebrown")
wn.setup(width=1000, height=800)
currentDT = datetime.datetime.now()

# output current time
currentHour = currentDT.hour
if currentHour > 12:
    currentHour = currentHour - 12
currentMinute = currentDT.minute
if currentMinute < 10:
    print("Time logged in at - " + str(currentHour) + ":0" +
          str(currentMinute))
else:
    print("Time logged in at - " + str(currentHour) + ":" + str(currentMinute))

# outside circle
circle = Turtle()
circle.penup()
circle.pencolor("black")
circle.speed(0)
circle.hideturtle()
circle.goto(0, -370)
circle.pendown()
circle.fillcolor("gold")
circle.begin_fill()
Example #12
0
File: main.py Project: sjk39/pong
from turtle import Screen
from scoreboard import Scoreboard
from ball import Ball
from pitch import Pitch
from paddle import Paddle
import time

sc = Screen()
sc.setup(width=1000, height=600)
p = Pitch()
sc.bgcolor("black")
sc.title("Pong")
sc.listen()
paddle_one = Paddle()
paddle_one.position(1)
paddle_two = Paddle()
paddle_two.position(2)
ball = Ball()
scoreboard = Scoreboard()
sc.onkey(paddle_one.up, "Up")
sc.onkey(paddle_one.down, "Down")

game_on = True
while game_on:
    sc.update()
    #time.sleep(0.001)

    if ball.distance(paddle_one.pos()) < 40 or ball.distance(
            paddle_two.pos()) < 40:
        ball.move(1)
        #prevents ball getting 'stuck' to paddle
Example #13
0
from turtle import Screen, Turtle
from yilan import Yilan
from yiyecek import Yiyecek
from skortahtasi import SkorTahtasi
import time

ekran = Screen()
ekran.setup(width=600, height=600)
ekran.bgcolor("black")

yilan = Yilan()

yemek = Yiyecek()
skorTahtasi = SkorTahtasi()

ekran.listen()
'''
ekran.onkey(yilan.sol, "Left")
ekran.onkey(yilan.sag, "Right")
ekran.onkey(yilan.yukari, "Up")
ekran.onkey(yilan.asagi, "Down")
'''
ekran.onkey(yilan.sol, "a")
ekran.onkey(yilan.sag, "d")
ekran.onkey(yilan.yukari, "w")
ekran.onkey(yilan.asagi, "s")

while True:
    yilan.hareket_et()
    time.sleep(0.1)
Example #14
0
class SpaceShip(GameItem):
    "This class defines a Space Ship and its properties"

    # Constructor
    def __init__(self, param_color="White"):
        Turtle.__init__(self)
        #self.color(param_color)

    #pass
    #self.shape("Triangle")


### MAIN ###
window = Screen()
window.setup(0.5, 0.75, 0, 0)
window.screensize(WINSIZE_WIDTH, WINSIZE_HEIGHT, "White")
window.setworldcoordinates(0, 0, WINSIZE_WIDTH, WINSIZE_HEIGHT)
window.title("Chasers")

spaceShip = SpaceShip()

window.onkeypress(spaceShip.turnLeft, "Left")
window.onkeypress(spaceShip.turnRight, "Right")
window.onkeypress(spaceShip.increaseSpeed, "Up")
window.onkeypress(spaceShip.decreaseSpeed, "Down")
window.listen()

spaceShip.setpos(GAMEMARGIN_WIDTH, GAMESIZE_HEIGHT)
while True:
    spaceShip.move()
Example #15
0
                    List[Opposite(i)][1] = List[Opposite(i)][1] - int(
                        min(List[Opposite(i)][1], Gtime / 2))
                    time.sleep(Gtime * 2)

                Yellow(i + 1)
                Yellow(Right(i) + 1)
                if (MidInitial == 0):
                    Yellow(Left(i) + 1)
                Yellow(Opposite(i) + 1)
                time.sleep(2)

                Red(i + 1)
                Red(Right(i) + 1)
                if (MidInitial == 0):
                    Red(Left(i) + 1)
                Red(Opposite(i) + 1)


# def ExtendedCongestionTraffic(List):

screen = Screen()
screen.setup(1000, 1000)
Base()
Pole()
Back()
HeadText()
ExtendedNormalTraffic([[6, 6, 3], [3, 5, 2], [2, 6, 3], [3, 3, 3]])

Reset()
screen.mainloop()
Example #16
0
    def ejercicio141():
        # CONFIGURACIÓN INICIAL DE LA VENTANA EMERGENTE CON SUS RESPECTIVAS PROPIEDADES
        pantalla = Screen()
        pantalla.setup(1020, 1025)
        pantalla.screensize(1000, 1000)
        pantalla.setworldcoordinates(-500, -500, 500, 500)
        pantalla.delay(0)

        # VALORES NECESARIOS PARA CADA UNO DE LOS CUERPOS
        x1 = -200
        y1 = -200
        velocidad_x1 = -0.1
        velocidad_y1 = 0
        m1 = 20

        # VALORES NECESARIOS PARA EL SEGUNDO CUERPO
        x2 = 200
        y2 = 200
        velocidad_x2 = -0.1
        velocidad_y2 = 0
        m2 = 20

        # CARACTERÍSTICAS RESPECTIVAS PARA EL PRIMER CUERPO
        cuerpo1 = Turtle('circle')
        cuerpo1.color('red')
        cuerpo1.speed(0)
        cuerpo1.penup()
        cuerpo1.goto(x1, y1)
        cuerpo1.pendown()

        # CARACTERÍSTICAS RESPECTIVAS PARA EL SEGUNDO CUERPO
        cuerpo2 = Turtle('circle')
        cuerpo2.color('blue')
        cuerpo2.speed(0)
        cuerpo2.penup()
        cuerpo2.goto(x2, y2)
        cuerpo2.pendown()

        # CICLO QUE PERMITE LA EJECUCIÓN DE LAS PROPIEDADES EN LA VENTANA EMERGENTE
        for t in range(10000):
            # PROPIEDAD PARA EL RADIO
            r = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

            # PROPIEDADES PARA SU RESPECTIVCA ACELERACIÓN
            aceleracion_x1 = m2 * (x2 - x1) / r ** 3
            aceleracion_y1 = m2 * (y2 - y1) / r ** 3
            aceleracion_x2 = m1 * (x1 - x2) / r ** 3
            aceleracion_y2 = m1 * (y1 - y2) / r ** 3

            # PROPIEDAD PARA SU RESPECTIVA VELOCIDAD
            velocidad_x1 += aceleracion_x1
            velocidad_y1 += aceleracion_y1
            velocidad_x2 += aceleracion_x2
            velocidad_y2 += aceleracion_y2

            # PROPIEDAD PARA LAS COORDENADAS
            x1 = velocidad_x1
            y1 = velocidad_y1
            x2 = velocidad_x2
            y2 = velocidad_y2

            # PROPIEDAD PARA LOS CUERPOS.
            cuerpo1.goto(x1, y1)
            cuerpo2.goto(x2, y2)
Example #17
0
from turtle import Turtle, Screen
from crossing_classes import WIDTH, HEIGHT, Map, Chicken, Scoreboard, Cars

image = "chicken.gif"
screen = Screen()
screen.setup(WIDTH * 2, HEIGHT * 2)
screen.bgcolor('lightgray')
screen.tracer(0)
screen.addshape(image)

print(screen.getshapes())

streets = Map()
scoreboard = Scoreboard()
chicken = Chicken()
chicken.shape(image)
cars = Cars()

screen.listen()
screen.onkeypress(chicken.move_up, 'Up')
screen.onkeypress(chicken.move_down, 'Down')
screen.onkeypress(chicken.move_left, 'Left')
screen.onkeypress(chicken.move_right, 'Right')

game_on = True
while game_on:
    screen.update()
    cars.move()

    if chicken.ycor() >= HEIGHT:
        scoreboard.update_score()
Example #18
0
from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=800, height=800)
colors = ["red", 'blue', 'green', 'orange', 'purple', 'violet']


def turtle_gen():
    turtle_dict = {}
    for i in colors:
        x = i
        i = Turtle()
        i.shape('turtle')
        i.color(x)
        i.penup()
        turtle_dict[x] = i
    return turtle_dict


def lineup(turtle_dict):
    contestants = len(turtle_dict)
    separation = 200 / contestants
    y = (-100)
    count = 0
    for i in turtle_dict.values():
        i.goto(-350, y)
        y = y + separation


def race(turtle_dict):
    for i in turtle_dict.values():
Example #19
0
                    print("Notable")
                else:
                    if media >= 9:
                        print("Sobresaliente!")


Examen(2, 9)

#//////////////////////////////////////////

import turtle

from turtle import Screen, Turtle

pantalla = Screen()
pantalla.setup(425, 225)
pantalla.screensize(400, 200)

dibuja = Turtle()
dibuja.forward(100)
dibuja.write("A \n\n")
dibuja.forward(130)
dibuja.write("B \n\n")
dibuja.forward(140)
dibuja.write("C \n\n")
dibuja.forward(140)
dibuja.write("D \n\n")
dibuja.forward(140)

pantalla.exitonclick()
Example #20
0
        self.hideturtle()
        self.score = 0
        self.update_scoreboard()

    def update_scoreboard(self):
        text = f"SCORE: {self.score}"
        self.write(text, move=False, align=ALIGN, font=FONT)

    def game_over(self):
        text = f"GAME OVER"
        self.setposition(0, 0)
        self.write(text, move=False, align=ALIGN, font=FONT)

    def add_to_score(self):
        self.score += 1
        self.clear()
        self.update_scoreboard()


if __name__ == "__main__":
    from turtle import Screen
    from time import sleep
    screen = Screen()
    screen.setup(height=600, width=600)
    screen.bgcolor("black")
    screen.tracer(0)
    score = Scoreboard()
    sleep(3)
    score.add_to_score()
    screen.exitonclick()
Example #21
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

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

screen = Screen()
screen.setup(width=snake.size_width, height=snake.size_width)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

screen.listen()
screen.onkey(snake.key_up, "Up")
screen.onkey(snake.key_down, "Down")
screen.onkey(snake.key_left, "Left")
screen.onkey(snake.key_right, "Right")

Game_On = True

snake.create_snake()

while Game_On:
    screen.update()
    time.sleep(0.075)
    snake.move_snake()
Example #22
0
from turtle import Screen, Turtle
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
import time
screen = Screen()
screen.setup(800, 600)
screen.bgcolor('black')
screen.title('Ping-Pong')
screen.tracer(0)
r_paddle = Paddle((350, 0))
l_paddle = Paddle((-350, 0))
ball = Ball()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(r_paddle.go_up, 'Up')
screen.onkey(r_paddle.go_down, 'Down')
screen.onkey(l_paddle.go_up, 'w')
screen.onkey(l_paddle.go_down, 's')

game_is_on = True
while game_is_on:
    time.sleep(ball.move_speed)
    screen.update()
    ball.move()

    if ball.ycor() > 280 or ball.ycor() < -280:
        ball.bounce_y()

    if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(
Example #23
0
#import turtle package
import turtle
from turtle import Turtle, Screen

#screen setup
screen = Screen()
screen.setup(500, 500)


#move forward
def up():
    turtle.forward(100)


#move backward
def back():
    turtle.backward(100)


#turn left
def left():
    turtle.left(40)


#turn right
def right():
    turtle.right(40)


#handle keypresses
turtle.Screen().onkeypress(up, 'Up')
Example #24
0
from turtle import Turtle, Screen
import random

is_race_on=False
tim=Turtle()
screen=Screen()
screen.setup(width=500,height=400)

user_bet=screen.textinput(title="Make your bet", prompt="Whick tutle will win the race? Enter a color:")
y_positions=[-70,-40,-10,20,50,80]
all_turtles=[]
colors=["red","orange","yellow","green","blue","purple"]

for turtle_index in range(0,6):
    tim=Turtle(shape="turtle")
    tim.color(colors[turtle_index])
    tim.penup()
    tim.goto(x=-230,y=y_positions[turtle_index])
    all_turtles.append(tim)

if user_bet:
    is_race_on=True

while is_race_on:
    for turtle in all_turtles:
        if turtle.xcor() > 230:
            is_race_on=False
            winning_color=turtle.pencolor()
            if winning_color==user_bet:
                print(f"You've won! The {winning_color} turtle is the winner!")
            else:
Example #25
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

theScreen = Screen()
theScreen.setup(width=600, height=600)
theScreen.bgcolor("black")
theScreen.title("The Snake Game")
theScreen.tracer(0)

theSnake = Snake()
theFood = Food()
theScore = Scoreboard()

theScreen.listen()
theScreen.onkeypress(theSnake.up, "Up")
theScreen.onkeypress(theSnake.down, "Down")
theScreen.onkeypress(theSnake.left, "Left")
theScreen.onkeypress(theSnake.right, "Right")

keepPlaying = True

while keepPlaying:
    theScreen.update()
    time.sleep(0.1)

    theSnake.move()
    theScore.showScore()
Example #26
0
from turtle import Screen
from snake import Snake
import time
from apple import Apple
from scoreboard import Scoreboard

scr = Screen()
scr.setup(width=600, height=600)
scr.bgcolor("black")
scr.title("SNAKE")
scr.tracer(0)

snake = Snake()
apple = Apple()
scoreboard = Scoreboard()

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


end = False
while not end:
    scr.update()
    time.sleep(0.1)
    snake.move()

    # Eat apple
    for segment in snake.segments:
Example #27
0
class TetrisBoard(object):
    def __init__(self, cols, rows):
        self.cols, self.rows = cols, rows
        self.screen = Screen()
        self.screen.screensize(BLOCKWIDTH*cols-50, BLOCKWIDTH*rows-50)
        self.screen.setup(BLOCKWIDTH*cols+12, BLOCKWIDTH*rows+12)
        self.screen.title("Turtle Tetris")
        self.screen.bgcolor("black")
        self.writer = Turtle()
        self.writer.ht()        
        self.label = None
        self.grid = {}
        self.screen.tracer(False)
        for row in range(rows):
            for col in range(cols):
                self.grid[(col, row)] = TetrisTurtle(col, row)
        self.screen.tracer(True)
        self.brick = TetrisBrick(self)
        self.result = 0
        self.LEVEL = 0.6
        self.keybuffer = KeyBuffer(self.screen,
                            ["Right", "Left", "Up", "Down", "space", "Escape"])
        self.reset()
        self.screen.listen()
        self.t1 = time()
        
    def reset(self):
        self.result = 0
        self.LEVEL = 0.600
        self.screen.tracer(False)
        self.writer.clear()
        if self.label:
            self.writer.clearstamp(self.label)
        for x in range(COLUMNS):
            for y in range(ROWS):
                self.grid[(x,y)].fillcolor("")
        self.screen.tracer(True)
        self.state = "NEWBRICK"
        
    def blink(self, y, n=1):
        for _ in range(n):
            for color in ("white", "black"):
                self.screen.tracer(False)
                for x in range(COLUMNS):
                    self.grid[(x,y)].pencolor(color)
                    sleep(self.LEVEL/10.0)
                self.screen.tracer(True)
            
    def display_result(self):
        tb = self
        tb.writer.color("white", "gray20")
        tb.writer.shape("square")
        tb.writer.shapesize(5, 15)
        tb.writer.goto(-4 ,0)
        self.label = tb.writer.stamp()
        tb.writer.goto(-2,3)
        tb.writer.write(str(tb.result) + " rows!",
                        align="center", font = ("Courier", 24, "bold") )
        tb.writer.goto(-2,-22)
        tb.writer.write("New game : <spacebar>",
                        align="center", font = ("Courier", 16, "bold") )
        tb.writer.goto(-2,-42)
        tb.writer.write("Quit : <escape>",
                        align="center", font = ("Courier", 16, "bold") )
        
    def getcolor(self, col, row):
        return self.grid[(col, row)].fillcolor()
    def setcolor(self, col, row, color):
        return self.grid[(col, row)].fillcolor(color)
    def rowfree(self, row):
        return not any([self.getcolor(col, row) for col in range(COLUMNS)])
    def rowfull(self, row):
        return all([self.getcolor(col, row) for col in range(COLUMNS)])

    def cleanup(self, shp):
        try:
            ymax = max([y for (x,y) in shp])
        except ValueError:
            self.state = "FINIS"
            return
        currenty = ymax
        while currenty > 0:
            if self.rowfull(currenty):
                self.blink(currenty, 2)
                self.result += 1
                if self.result == 8:
                    self.LEVEL = 0.4
                elif self.result == 20:
                    self.LEVEL = 0.25
                y = currenty
                while True:
                    self.screen.tracer(False)
                    for c in range(COLUMNS):
                        self.setcolor(c, y, self.getcolor(c, y-1))
                    self.screen.tracer(True)
                    if self.rowfree(y):
                        break
                    else:
                        y -= 1
            else:
                currenty -= 1
        tetris.state = "NEWBRICK"

    def run(self):
        tb = self
        b = self.brick
        ### actions to be done unconditionally
        if tb.state == "NEWBRICK":
            if b.reset():
                self.t1 = time()
                tb.state = "FALL"
            else:
                tb.state = "FINIS"
        t2 = time()
        if tb.state == "FALL" and t2 - self.t1 > self.LEVEL:
            b.down()
            b.apply("Step")
            self.t1 = t2
        ### actions bound to key events
        key = self.keybuffer.getkey()
        if key:
            if tb.state == "FALL":
                if key == "Left":
                    b.shiftleft()
                elif key == "Right":
                    b.shiftright()
                elif key == "Down":
                    b.drop()
                    tb.state = "CLEANUP"
                elif key == "Up":
                    b.turn()
                elif key == "space":
                    tb.state = "BREAK"
                b.apply(key)
            elif tb.state == "BREAK":
                if key == "space":
                    tb.state = "FALL"
            elif tb.state == "ADE":
                if key == "space":
                    tb.reset()
                    tb.state = "NEWBRICK"
                elif key == "Escape":
                    tb.screen.bye()
                
        if tb.state == "CLEANUP":
            tb.cleanup(b.shape1)
        if tb.state == "FINIS":
            tb.display_result()
            tb.state = "ADE"
        self.screen.ontimer(self.run, 100)    
Example #28
0
from turtle import Screen, Turtle
from food import Food
import time
from snake import Snake
from scoreboard import Scoreboard
score = Scoreboard()
snake = Snake()
food = Food()
screen = Screen()

screen.setup(600, 600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

game = 1
while game:
    screen.update()
    time.sleep(.1)
    snake.move()
    screen.listen()
    screen.onkey(snake.up, "Up")

    screen.onkey(snake.down, "Down")
    screen.onkey(snake.right, "Right")
    screen.onkey(snake.left, "Left")
    if snake.head.distance(food) < 15:
        food.refresh()
        score.increase_scoe()
        snake.extend()
        screen.update()
Example #29
0
class PongGame:
    def __init__(self):
        # Create the Screen Object
        self.screen = Screen()
        self.screen.setup(SCREEN_XCOR, SCREEN_YCOR)
        self.screen.bgcolor("black")
        # Create Screen Cursor; Draw Pong Game Layout
        self.screen_cursor = Turtle()
        self.screen_cursor.ht()
        self.establish_game_layout()
        self.ball_speed = 0.07
        self.screen.tracer(0)

        # Create Score Cursor; Visualize and Update the Score
        self.score_cursor = Turtle()
        self.score_cursor.ht()
        self.score_cursor.color("white")
        self.score_cursor.speed("fastest")
        self.score_cursor.pu()
        self.scores = [0, 0]
        self.update_players_score()

        # Create Paddles Objects
        self.rt_paddle = Turtle()
        self.lt_paddle = Turtle()
        self.init_paddle(LT_PADDLE_POSITION, RT_PADDLE_POSITION)

        # Create Ball Object
        self.ball = Turtle()
        self.x_move = 10
        self.y_move = 10
        self.init_ball()

    def establish_game_layout(self):
        self.screen.title("Pong Game")
        self.screen_cursor.color("white")
        self.screen_cursor.pensize(3)
        self.screen_cursor.penup()
        self.screen_cursor.speed("fastest")
        # Type Game Title
        self.screen_cursor.setposition(x=0, y=(SCREEN_YCOR/2 - Y_MARGIN/1.3))
        self.screen_cursor.write("- Pong Game -", move=False, align="center", font=("Calibri", 30, "bold"))
        # Draw the Pong Table Margins
        self.screen_cursor.setposition((-GAME_XCOR/2), (GAME_YCOR/2))
        self.screen_cursor.pd()
        self.screen_cursor.fd(GAME_XCOR)
        self.screen_cursor.rt(90)
        self.screen_cursor.fd(GAME_YCOR)
        self.screen_cursor.rt(90)
        self.screen_cursor.fd(GAME_XCOR)
        self.screen_cursor.rt(90)
        self.screen_cursor.fd(GAME_YCOR)
        # Draw Dotted line
        self.screen_cursor.pu()
        self.screen_cursor.pensize(1)
        self.screen_cursor.setposition(0, (GAME_YCOR/2))
        self.screen_cursor.setheading(270)
        for i in range(int(GAME_YCOR/10)):
            if i % 2 == 0:
                self.screen_cursor.pd()
            else:
                self.screen_cursor.pu()
            self.screen_cursor.fd(10)

    def update_players_score(self, index=None):
        if index is not None:
            self.scores[index] += 1
        self.score_cursor.clear()
        self.score_cursor.setposition(-50, (GAME_YCOR/2)-70)
        self.score_cursor.write(f"{self.scores[LT_PLAYER]}", move=False, align="center", font=("Courier", 40, "bold"))
        self.score_cursor.setposition(50, (GAME_YCOR/2)-70)
        self.score_cursor.write(f"{self.scores[RT_PLAYER]}", move=False, align="center", font=("Courier", 40, "bold"))

    def init_paddle(self, lt_paddle_position, rt_paddle_position):
        self.lt_paddle.shape("square")
        self.lt_paddle.pu()
        self.lt_paddle.setheading(90)
        self.lt_paddle.shapesize(1, 6)
        self.lt_paddle.color("white")
        self.lt_paddle.setposition(lt_paddle_position)
        self.rt_paddle.shape("square")
        self.rt_paddle.pu()
        self.rt_paddle.setheading(90)
        self.rt_paddle.shapesize(1, 6)
        self.rt_paddle.color("white")
        self.rt_paddle.setposition(rt_paddle_position)

    def init_ball(self):
        self.ball.shape("circle")
        self.ball.pu()
        self.ball.shapesize(1.5, 1.5)
        self.ball.color("lime")

    def move_rt_paddle_up(self):
        if self.rt_paddle.ycor() <= (GAME_YCOR/2 - 80):
            self.rt_paddle.forward(20)

    def move_rt_paddle_down(self):
        if self.rt_paddle.ycor() >= -(GAME_YCOR/2 - 80):
            self.rt_paddle.backward(20)

    def move_lt_paddle_up(self):
        if self.lt_paddle.ycor() <= (GAME_YCOR/2 - 80):
            self.lt_paddle.forward(20)

    def move_lt_paddle_down(self):
        if self.lt_paddle.ycor() >= -(GAME_YCOR/2 - 80):
            self.lt_paddle.backward(20)

    def move_ball(self):
        self.ball.goto((self.ball.xcor()+self.x_move), (self.ball.ycor()+self.y_move))

    def bounce_ball_yAxis(self):
        self.y_move *= -1

    def bounce_ball_xAxis(self):
        self.x_move *= -1

    def reset_ball_position(self):
        # Reverse Ball Direction
        self.x_move *= -1
        # Reset Ball Position and Speed
        self.ball.setposition(0, 0)
        self.ball_speed = 0.12

    def check_hit_wall(self):
        if self.ball.xcor() >= (GAME_XCOR/2 - 10):
            return LT_PLAYER
        elif self.ball.xcor() <= -(GAME_XCOR/2 - 10):
            return RT_PLAYER

        if self.ball.ycor() >= (GAME_YCOR/2 - 30) or \
                self.ball.ycor() <= -(GAME_YCOR/2 - 30):
            self.bounce_ball_yAxis()
            return None

    def check_hit_paddle(self):
        if self.ball.distance(self.rt_paddle) < 60 and self.ball.xcor() > 340 or \
                self.ball.distance(self.lt_paddle) < 60 and self.ball.xcor() < -340:
            # Make Ball move Faster
            self.ball_speed *= 0.9
            # Reverse Ball Direction
            self.bounce_ball_xAxis()
Example #30
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(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")

is_game_on = True
while is_game_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    #Detect collision with food
    if snake.head.distance(food) < 15:
        food.refresh()
Example #31
0
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700
X_LIMIT = int(SCREEN_WIDTH / 2 - 5)
Y_LIMIT = int(SCREEN_HEIGHT / 2 - 5)

GAME_MODE = {"easy": 0.5, "normal": 0.2, "hard": 0.1, "super": 0.05}

# Create a screen
screen = Screen()
screen.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
screen.bgcolor("black")
screen.tracer(0)
screen.title("Snake Game")

# Create a snake and a food
snake = Snake()
food = Food()
score = Scoreboard()
screen.update()

# Game mode selection by user
user_choice = screen.textinput(title="Choose a game mode", prompt="Input 'EASY', 'NORMAL', 'HARD', 'SUPER'").lower()
if user_choice in GAME_MODE.keys():
    game_mode = GAME_MODE[user_choice]
else:
Example #32
0
from turtle import Screen, Turtle
import pandas

screen = Screen()
screen.setup(width=1200)
screen.title("US States")
image = 'blank_states_img.gif'
screen.addshape(image)

tim = Turtle(image)

writer = Turtle()
writer.hideturtle()
is_game_on = True

data = pandas.read_csv('50_states.csv')
states = data['state'].tolist()
answered_state = []
unanswered_state = []
count = 1
while is_game_on:
    state = screen.textinput(f"Name of State [{len(answered_state)}/50]",
                             "Name of state:").title()

    if state == 'Exit':
        unanswered_state = [s for s in states if s not in answered_state]
        break
    if state in states and state not in answered_state:
        state_data = data[data['state'] == state]
        x_cor = int(state_data['x'])
        y_cor = int(state_data['y'])
Example #33
0
doubles = None
wsls = None
DATABASE_NAME = 'system/stats.db'

# # # Game states ####
# 0 - choose game play
# 50 - choose game type
# 100 - choose game size
# 150 - choose players
# 200 - in game

# window screen set up
window = Screen()
window.title("Table tennis scoreboard")
window.bgcolor("black")
window.setup(width=1024, height=600)
window.delay(0)
window.tracer(False)

# turtle set up
pen = Turtle()
pen.speed(0)
pen.color("white")
pen.hideturtle()
pen.penup()

# definitions of game functions


def database_update_singles():
    global player2_id, player1_id, playerNames, match_duration, leftScore, rightScore
def right():
    global step

    if step == fight:
        combat()
    step += 1
    turtle.seth(0)
    turtle.forward(10)


def combat():
    enemy = Turtle()
    enemy.up()
    eHealth = randint(20, 100)
    eDamage = randint(10, 20)


screen = Screen()
screen.setup(500, 350)  # visible portion of screen area
screen.screensize(600, 600)  # scrollable extent of screen area
turtle = Turtle()
turtle.up()

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

screen.mainloop()
Example #35
0
def week__3(myChar):

    import turtle , random
    from turtle import Turtle, Screen

    print(''' Django 볼을 획득하라!
    노란색 Django볼을 획득하면 Mission clear 됩니다.''')
    screen = Screen()
    screen.setup(1200, 500)
    Django = Turtle()
    Django.shape('circle')
    Django.color('yellow')
    Django.up()
    point_x = random.randint(-500,500)
    point_y = random.randint(-250,250) 
    Django.goto(point_x,point_y)
    player = Turtle()
    player.speed('fastest')
    PlayerY = 0
    PlayerX = 0
    
    def play():
        if player.distance(Django) < 25:
            turtle.clear()
            turtle.write("Mission Clear",False,"center",font=("Arial",50,"normal"))
            myChar.controlPiro(5)
            myChar.controlCoding(10)

        
        if player.distance(Django) > 25:
            turtle.clear()
            turtle.write("Game Over",False,"center",font=("Arial",50,"normal"))
            myChar.controlPiro(5)
            myChar.controlMoney(-2)

    def moveX():
        nonlocal PlayerX
        screen.onkeypress(None, "Right") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerX += 10
        screen.onkeypress(moveX, "Right") 
        
    def moveY():
        nonlocal PlayerY
        screen.onkeypress(None, "Up") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerY += 10
        screen.onkeypress(moveY, "Up")

    def move_X():
        nonlocal PlayerX
        screen.onkeypress(None, "Left") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerX -= 10
        screen.onkeypress(move_X, "Left")

    def move_Y():
        nonlocal PlayerY
        screen.onkeypress(None, "Down") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerY -= 10
        screen.onkeypress(move_Y, "Down")

    screen.listen()
    turtle.ontimer(play, 9000)
    moveY()
    moveX()
    move_X()
    move_Y()

    screen.mainloop()
Example #36
0
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=650, height=650)
screen.title("Crossy Turtle")
screen.tracer(0)

car = CarManager()
scoreboard = Scoreboard()
player = Player()

screen.listen()
screen.onkey(player.move, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.2)
    screen.update()
    car.create_cars()
    car.move()
    # Detect end of road
    if player.ycor() > 280:
        player.reset_position()
        scoreboard.increase_score()
        scoreboard.update_scoreboard()

    #Detect Car collision
Example #37
0
from turtle import Screen, Turtle

radio = 300

pantalla = Screen()
pantalla.setup(620, 420)
pantalla.screensize(600, 400)
pantalla.setworldcoordinates(-50, -150, 350, 250)

tortuga = Turtle()
tortuga.pensize(6)
tortuga.pencolor("green")
"""
tortuga.left(180)
tortuga.forward(130)
tortuga.right(90)
tortuga.forward(20)
tortuga.right(90)
tortuga.circle(15)
tortuga.forward(40)
tortuga.left(90)
tortuga.forward(70)
tortuga.right(90)
tortuga.forward(55)
tortuga.right(90)
tortuga.forward(70)
tortuga.left(90)
tortuga.forward(40)
tortuga.right(90)
tortuga.forward(20)
tortuga.write("pitooperrooo")
Example #38
0
from life_turtle import Life
from turtle import Screen
import datetime
import math

screen = Screen()
screen.setup(height=500, width=950)
screen.title("Life in Weeks:")
screen.tracer(0)

years = screen.textinput(title="Average age of human 79 years", prompt="For different age enter age: ")
if len(years)==0:
    years = 79

format_not_right = True
while format_not_right:
    birthday = screen.textinput(title="Your birthday", prompt="Please enter in format: day,month,year:")
    birthday = birthday.split(",")
    if len(birthday)==3:
        format_not_right = False

# week calculation
age_date = str(datetime.date(int(birthday[2]),int(birthday[1]),int(birthday[0])))
age_date = datetime.datetime.strptime(age_date, "%Y-%m-%d").date()
today = datetime.datetime.strptime(str(datetime.date.today()), "%Y-%m-%d").date()
days = (today- age_date).days

# week rounding
age = math.ceil(days/7)

# creating weeks and fill those for the age out
Example #39
0
from turtle import Screen, Turtle
from random import randint

s = Screen()
s.setup(560,560)
s.title("A drunken turtle collecting ...")

s.tracer(False)
writer = Turtle(visible=False)
writer.penup()
writer.goto(0, -275)

coins = []
for i in range(-4,5):
  for j in range(-4, 5):
      if i == j == 0:
          continue
      c = Turtle(shape="circle")
      c.color("", "orange")
      c.shapesize(0.5)
      c.goto(40*i, 40*j)
      coins.append(c)
s.tracer(True)

DRUNKENNESS = 45       
t = Turtle(shape="turtle")
t.color("black","")
points = 0
while abs(t.xcor()) < 200 and abs(t.ycor()) < 200:
  t.forward(5)
  t.right(randint(-DRUNKENNESS, DRUNKENNESS))