Beispiel #1
0
def start():
    screen = Screen()
    screen.setup(width=600, height=600)
    screen.bgcolor('black')
    screen.title('Snake Game')
    create_board()
    screen.tracer(0)
    game_speed = screen.numinput(
        'Game Speed',
        'How fast is this game? 1 - 20 (lowest number is slowest')
    snake = Snake(game_speed)
    food = Food()
    score = Score()
    screen.listen()
    screen.onkey(snake.turn_up, 'w')
    screen.onkey(snake.turn_left, 'a')
    screen.onkey(snake.turn_down, 's')
    screen.onkey(snake.turn_right, 'd')

    game_on = True

    while game_on:
        snake.move()
        screen.update()
        time.sleep(.20)

        if snake.head.distance(food) < 15:
            food.move_food()
            snake.grow()
            score.gain_point()
            print(score.amount)

        if snake.head.xcor() <= -260 or snake.head.xcor(
        ) >= 260 or snake.head.ycor() >= 260 or snake.head.ycor() <= -260:
            score.reset()
            snake.reset()

        for segment in snake.snake_body[1:]:
            if snake.head.distance(segment) < 10:
                score.reset()
                snake.reset()

    screen.exitonclick()
Beispiel #2
0
def play():
    ''' Plays game '''

    screen = Screen()
    set_up_screen(screen)

    snake = Snake()
    food = Food()
    score = Score()
    screen.update()

    screen.listen()
    screen.onkey(partial(snake.set_direction, "Up"), key="Up")
    screen.onkey(partial(snake.set_direction, "Down"), key="Down")
    screen.onkey(partial(snake.set_direction, "Left"), key="Left")
    screen.onkey(partial(snake.set_direction, "Right"), key="Right")

    wall_limit = HALF_SCREEN - 40

    keep_playing = True

    while keep_playing:

        game_over = False
        while not game_over:

            snake.move()
            screen.update()

            # Eat food
            if snake.head.distance(food) < 15:
                score.update()
                food.move()
                snake.extend()

            # Hit wall
            if snake.head.xcor() > wall_limit or snake.head.xcor(
            ) < -wall_limit - 20:
                game_over = True
            if snake.head.ycor() > wall_limit or snake.head.ycor(
            ) < -wall_limit:
                game_over = True

            # Hit tail
            for segment in snake.tail:
                if snake.head.distance(segment) < 10:
                    game_over = True

            time.sleep(0.1)

        score.update_highscore()

        user_choice = screen.numinput(
            "Game over",
            f"Your score: {score.score}\nInput 1 to play again or 2 to exit.",
            1,
            minval=1,
            maxval=2)
        if user_choice == 2:
            keep_playing = False
        else:
            food.move()
            snake.delete_snake()
            snake.create_snake()
            score.reset()
            screen.update()
            screen.listen()
Beispiel #3
0
#Hilda Rocio Martin - 06/13/19 - Exercise 7.4 (spiral.py).
# Write a script that asks the user to enter an angle. Then use turtle to draw 128 lines, each line is separated by the given angle
# and each line is slightly bigger than the last.
#modulo
import turtle
from turtle import Turtle, Screen
# Program inputs
screen = Screen()
angle = None
# This loop opens a gui that ask the user for input
while not angle:
    angle = screen.numinput('Select Angle', 'Enter an angle:', minval=1)
# declaring objects
obj = turtle.Turtle()
obj.speed(50)


# Function to draw the spiral at a given angle
def drawspiral():
    for x in range(128):  # The program draws 128 lines
        obj.forward(x)  # Moves the object forward
        obj.right(angle)  # To the right at an angle


drawspiral()
turtle.done()
Beispiel #4
0
def main():
    # initialize screen
    screen = Screen()
    screen.title("Snake")
    screen.tracer(0)

    # ask for user inputs for window size and snake speed
    chosen_grid = screen.textinput(
        "Welcome to Snake!", "Choose a window size (small/medium/big): ")
    insane_choice = screen.textinput("Welcome to Snake!",
                                     "Insane mode? (yes/no)")

    if insane_choice == "yes":
        speed = 1
        insane_mode = True
    else:
        speed = screen.numinput("Welcome to Snake!",
                                f"Choose a speed (1-{len(speeds)}): ")
        insane_mode = False

    # initialize food, snake and scoreboard
    chosen_size = grids[chosen_grid]["size"]
    food = Food(grids[chosen_grid]["grid"])
    snake = Snake(chosen_size)
    scoreboard = ScoreBoard(chosen_size)

    if insane_mode:
        insane_writer = InsaneMode(chosen_size)

    # setup screen of the chosen size, color, title
    width = height = grids[chosen_grid]["size"]
    screen.setup(width=width, height=height)
    screen.bgcolor("black")
    screen.title("Snake")

    # updates screen to show snake, first food piece and scoreboard
    screen.update()

    # main loop
    # stops when snake collides with itself or obstacles
    while snake.is_alive():

        # checks for collision with food and updates food position if necessary
        # also increments scoreboard score according to difficulty
        if snake.head.distance(food) < 15:
            snake.lenght += 1
            food.update()
            scoreboard.score += int(grids[chosen_grid]["multiplier"] * speed)

            # increments difficulty on insane mode
            if insane_mode and speed < 12:
                speed += 1
                insane_writer.level += 1

        # listen to user key presses
        screen.listen()
        screen.onkey(fun=snake.turnUp, key="Up")
        screen.onkey(fun=snake.turnDown, key="Down")
        screen.onkey(fun=snake.turnLeft, key="Left")
        screen.onkey(fun=snake.turnRight, key="Right")
        screen.onkey(fun=screen.bye, key="Escape")

        # update snake, scoreboard, insane lvl and screen
        snake.update()
        scoreboard.update()
        screen.update()
        if insane_mode:
            insane_writer.update()

        # loop delay / speed control
        time.sleep(speeds_dict[speed])

    # game over screen
    scoreboard.game_over()
    screen.textinput("Game Over", "Press any key to play again")
    snake.reset()
    scoreboard.reset()
    screen.clear()
    main()
Beispiel #5
0
import turtle
from turtle import Screen

my_turtle = turtle.Turtle()
window_size = turtle.Screen()
screen = Screen()  # To open a window for the user.
user_input = screen.numinput('Select Depth',
                             'Enter a desired depth:',
                             minval=1)


def draw_cesaro(turtle, depth, w):
    """This function takes in the turtle,draw fractal of order 2.4 and width w.
    It is cesaro torn line fractal using recursive call of the function.
    """

    if depth == 0:
        turtle.forward(w)  # Cesaro fractal of a width w.
    else:
        draw_cesaro(turtle, depth - 1, w / 2.4)
        turtle.right(80)
        draw_cesaro(turtle, depth - 1, w / 2.4)
        turtle.left(160)
        draw_cesaro(turtle, depth - 1, w / 2.4)
        turtle.right(80)
        draw_cesaro(turtle, depth - 1, w / 2.4)


def main():
    '''This is the main function. here the turtle turns 85 degrees right
    and then the turtle turns 160 degrees left and then 80 degrees
Beispiel #6
0
    for i in range(seconds, -1, -1):
        t.color('black')
        writeAtB(t, i, screenwidth / 2 - 100, screenheight / 2 - 100, 'black',
                 40)
        time.sleep(1)
        t.clear()


def disappear(t):
    t.hideturtle()
    t.penup()


numpeople = s.numinput('Generate people',
                       "How many people are in the city?",
                       default=20,
                       minval=20,
                       maxval=150)
while numpeople is None or int(numpeople) != numpeople:
    numpeople = s.numinput('Generate people',
                           "How many people are in the city?",
                           default=20,
                           minval=20,
                           maxval=150)
numpeople = int(numpeople)
names = []
generateNames(names, numpeople)
windowsizex = 290
windowsizey = 290

i = 0
Beispiel #7
0
screen = Screen()
screen.bgcolor("lightgreen")

turtle1 = Turtle(shape='turtle')
turtle1.color('red')
turtle1.speed(10)
turtle1.penup()

turtle2 = Turtle(shape='turtle')
turtle2.color('blue')
turtle2.speed(0.1)
turtle2.penup()

perimeter = screen.numinput("Track Perimeter",
                            "Please enter the perimeter:",
                            default=2000,
                            minval=500,
                            maxval=3000)


def full_track_crawl(turtle, shortside, longside):
    speed = turtle.speed()
    turtle.pendown()

    for j in range(2):
        for i in range(0, int(shortside), 0.1):
            turtle.forward(0.1)
            yield (0)
        turtle.left(90)
        for i in range(0, int(longside), 0.1):
            turtle.forward(0.1)
Beispiel #8
0
import turtle
from turtle import Turtle, Screen
import random

colorlist = ["blue", "green", "yellow", "black", "red", "purple", "orange"]
turtlelist = {}

screen = Screen()

screen.setup(width=500, height=400)

numplayers = round(
    screen.numinput("How many challengers?", "Enter the num of turtles"))

for i in range(numplayers):
    tname = screen.textinput("wtfthisdo", "input name:")
    turtlelist[tname] = None

for turtle in turtlelist.keys():
    turtlelist[turtle] = Turtle(shape="turtle")
    turtlelist[turtle].color(colorlist.pop())

print(turtlelist)

# put turtles in racing position

# have to make the finish line


def turtle_lineup(turtlelist):
    valy = 180
Beispiel #9
0
def right():
    mouse.right(45)
    checkbound()

def quitTurtles():
    window.bye()


window.onkeypress(up, "Up")
window.onkeypress(back, "Down")
window.onkeypress(left, "Left")
window.onkeypress(right, "Right")
window.onkeypress(quitTurtles, "Escape")

difficulty = window.numinput("Difficulty",
                             "Enter a difficulty from easy (1), for hard (5)",
                             minval=1, maxval=5)

window.listen()

while not caught:
    cat.setheading(cat.towards(mouse))
    cat.forward(8+difficulty)
    score = score+1
    if cat.distance(mouse) < 5:
        caught = True
    sleep(0.2 - difficulty * 0.01)

window.textinput("GAME OVER", "Well done. Your score:"
                 + str(score*difficulty))
Beispiel #10
0
def play_game(user_bank):
    screen = Screen()
    screen.setup(width=500, height=400)

    is_race_on = False

    turtles = []

    pos_y = -100
    color_index = 0

    for turtle_index in range(0, 6):
        odds_move = random.randint(5, 15)
        odds_money = round(20/odds_move, 2)
        new_turtle = Turtle("turtle")
        new_turtle.color(colors[color_index])
        new_turtle.penup()
        new_turtle.goto(-230, pos_y)
        pos_y += 50
        color_index += 1
        turtles.append((new_turtle, odds_money, odds_move))

    bet_prompt = f"Who is going to win? Odds:\n" \
             f"Red: {turtles[0][1]}\n" \
             f"Blue: {turtles[1][1]}\n" \
             f"Yellow: {turtles[2][1]}\n" \
             f"Green: {turtles[3][1]}\n" \
             f"Purple: {turtles[4][1]}\n" \
             f"Orange: {turtles[5][1]}\n"

    money_prompt = f"You currently have ${user_bank}, How much would you like to bet?"

    user_bet_horse = screen.textinput(title="Make your bet", prompt=bet_prompt).lower()
    user_bet_money = int(screen.numinput(title="How much?", prompt=money_prompt))

    if user_bet_horse:
        is_race_on = True

    while is_race_on:
        for turtle in turtles:
            if turtle[0].xcor() > 230:
                is_race_on = False
                win_color = turtle[0].fillcolor()
                odds_money = turtle[1]
                odds_move = turtle[2]
                if win_color == user_bet_horse:
                    user_bank += (user_bet_money * odds_money)
                    win_prompt = f"You won ${user_bet_money * (20 - odds_money)}! The {win_color} turtle with odds of" \
                                 f" {odds_money} won!\nWould you like to place another bet? Yes or No\n"
                    if screen.textinput(title="YOU WON :)", prompt=win_prompt).lower() == "yes":
                        screen.clear()
                        play_game(user_bank)
                    else:
                        screen.bye()
                else:
                    user_bank -= user_bet_money
                    lose_prompt = f"You lost ${user_bet_money}! The {win_color} turtle with odds of {odds_money} won!" \
                                  f"\n(press enter to continue)\nWould you like to place another bet? Yes or No\n"
                    if screen.textinput(title="YOU LOST :(", prompt=lose_prompt).lower() == "yes":
                        screen.clear()
                        play_game(user_bank)
                    else:
                        screen.bye()

            distance = random.randint(0, odds_move)
            turtle[0].fd(distance)
Beispiel #11
0
# Hilda Rocio Martin - 06/13/19 - Exercise 7.3 (polygons.py).
# Ask the user to enter a positive integer. Then consecutively draw shapes with 3, 4, 5, 6, and 7 sides
# where the side length of each is the user’s input.

#Modulo
import turtle
from turtle import Turtle, Screen

# Program inputs
screen = Screen()
length = None
# This loop opens a gui that ask the user for input
while not length:
    length = screen.numinput("Select Length",
                             "Enter side length no bigger than 100:",
                             minval=1)

# Pick up the pen and go to that location then puts down the pen
turtle.penup()
turtle.goto(-6 * length, 0)  # This is the coordinates on the screen
turtle.pendown()

# Draw three sides(triangle)
for i in range(3):
    turtle.color('red')  #color of the pen
    turtle.forward(length)  #It moves forward the indicated length
    turtle.left(120)  #The angle is 120 because 360/3 = 120

turtle.penup()
turtle.goto(-4.5 * length, 0)
turtle.pendown()
        Dim['Y']['upper']
    ]

    win.setworldcoordinates(D[0], D[1], D[2], D[3])

    G = Grapher(Dim)
    '''
    f = lambda x : sin(x)
    interval = (0,9,0.1)
    Region1 = singlaValueFun_numGen(f,interval)
    
    x_t = lambda t : cos(t)
    y_t = lambda t: 2*sin(t)
    interval = {
        'lower' : 0,
        'upper' : 2*pi,
        'increment' : 0.1
    }
    Region2 = ParametricEqu_numGen(x_t,y_t,interval)
    '''
    r_theta = lambda theta: 3 * cos(2 * theta)
    interval = {'lower': 0, 'upper': 2 * pi, 'increment': 0.01}
    Region3 = PolarEqu_numGen(r_theta, interval)

    win.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
    win.delay(5)

    G.plot(Region3)

    win.mainloop()
Beispiel #13
0
def main():

    from tkinter import messagebox
    import turtle
    from turtle import Turtle, Screen
    import random
    from coolname import generate_slug
    turtle.colormode(255)
    screen = Screen()
    screen.title("Let's race! ")
    screen.bgcolor('lavenderblush')
    screen.setup(width=.75, height=0.75, startx=None, starty=None)

    def create(num):
        colors = [(255, 51, 192), (223, 45, 168),
                  (191, 38, 144), (159, 32, 120), (128, 26, 96), (96, 19, 72),
                  (64, 13, 48), (32, 6, 24), (156, 208, 216), (154, 213, 175),
                  (241, 171, 151), (229, 212, 16), (125, 115, 160)]
        x = -450
        y = -150
        players = []
        for turtles in range(num):
            name = Turtle()
            name.name = generate_slug(2)
            name.shape('turtle')
            name.penup()
            name.color(random.choice(colors))
            name.setx(x)
            name.sety(y)
            name.write(f'  {name.name}\n', True, align="right")
            name.pendown()
            name.pensize(2)
            y += 50
            players.append(name)
        return players

    def finish_line():
        line_dude = Turtle()
        line_dude.hideturtle()
        line_dude.shape('turtle')
        line_dude.color((241, 13, 77))
        line_dude.penup()
        line_dude.setheading(90)
        line_dude.speed(0)
        line_dude.setpos(400, -200)
        line_dude.showturtle()
        line_dude.pendown()
        line_dude.speed(1)
        line_dude.forward(50 * num + 50)
        line_dude.hideturtle()

    num = int(
        screen.numinput("Number of Players",
                        "How many players in the race?:",
                        3,
                        minval=0,
                        maxval=10))

    players = create(num)
    finish_line()
    finish = 400
    messagebox.askquestion(title="Let's play!", message="ready to play?")
    if 'yes':
        game_on = True
        while game_on:
            for turtl in players:
                if turtl.xcor() >= finish - 1:
                    game_on = False
                    messagebox.askokcancel('winner', f'{turtl.name} won! yes!')
                    print(f'{turtl.name}')
                    break
                else:
                    rand_distance = random.randint(1, 10)
                    turtl.forward(rand_distance)

    if messagebox.askyesno(title="again?", message="Want to play again?"):
        turtle.clearscreen()
        main()
    else:
        turtle.clearscreen()

    screen.listen()
    screen.exitonclick()
Beispiel #14
0
        self.turtle.sety(start_y)
        self.turtle.shape("turtle")
        self.max_x = max_x

    def move_forward(self):
        self.turtle.forward(random.randint(0, 20))
        if self.turtle.xcor() + TURTLE_WIDTH >= self.max_x:
            return False
        return True


# number_of_turtles = input()

s = Screen()
num_turtles_entered = s.numinput(title="NUM",
                                 prompt="Enter Number of Turtles in race : ",
                                 default=2)
num_turtles = 2 if num_turtles_entered is None else int(num_turtles_entered)
s.setup(width=400,
        height=(num_turtles * TURTLE_HEIGHT * 2) + (2 * TURTLE_HEIGHT))

MIN_X = (-1 * s.window_width() / 2) + TURTLE_WIDTH
MIN_Y = (-1 * s.window_height() / 2) + TURTLE_HEIGHT
MAX_X = s.window_width() / 2

start_x = MIN_X
start_y = MIN_Y

with open("colors.json", "r") as f:
    json_colors = json.load(f)
Beispiel #15
0
class TurtleRace:

    def __init__(self):

        self.game_setup()
        self.winner = None

    def game_setup(self):
        """Resets the screen and asks for how many turtles to send to the races"""

        self.screen = Screen()

        self.screen.setup(width=500, height=400)

        self.screen.clearscreen()

        self.num_turtles = int(self.screen.numinput("num_turtle", "How many turtles race today?", 2, 2, 5))

        # Sets initial parameters for the turtles - 5 options
        self.names = ["Bob", "John", "Sally", "Rufus", "Marvin"]
        self.colors = ["red", "purple", "green", "yellow", "orange"]
        self.turtley = [-150, -50, 0, 50, 150]
        self.start = -230
        self.is_winner = False

        self.turtles = {}

        self.create_turtles()

        self.play()

    def create_turtles(self):
        """Generates the turtles!!"""
        for turtle_ind in range(self.num_turtles):
            self.turtles[self.names[turtle_ind]]=(Turtle(shape="turtle"))
            self.turtles[self.names[turtle_ind]].color(self.colors[turtle_ind])
            self.turtles[self.names[turtle_ind]].penup()
            self.turtles[self.names[turtle_ind]].goto(x=self.start,y=self.turtley[turtle_ind])



    def start_race(self):

        while not self.is_winner:

            for turtle in self.turtles:
                this_turtle = self.turtles[turtle]
                xchange=randint(1,10)
                next_x = this_turtle.xcor()+xchange
                this_turtle.goto(x=next_x,y=this_turtle.ycor())
                if next_x>=230:
                    self.winner = turtle
                    self.is_winner = True
                    break
                # self.is_winner(next_x)
        self.end_race()

    def end_race(self):

        print(f"We have a winner! Great job, {self.winner}!!!")
        print("Replay? Press r")

    def play(self):
        """Listens for player input"""
        self.screen.listen()
        self.screen.onkeypress(key="g", fun=self.start_race)
        self.screen.onkeypress(key="r", fun=self.game_setup)
        self.screen.exitonclick()
Beispiel #16
0
Write a program that takes in an integer. If the integer is less than 3, print a message and exit.
Otherwise, draw a shape with as many sides as the user’s input.'''

# Import modulo
import turtle
from turtle import Turtle, Screen

# Program inputs
screen = Screen()
sides = None
length = None
error = None
# This loop opens a gui that ask the user for input.
while not sides:
    sides = screen.numinput('Select Number of Sides',
                            'Enter the number of sides to draw a polygon',
                            minval=1)
# If the input is smaller than 3 it warns the user and exit the screen.
if sides < 3:
    error = screen.numinput('Select Number of Sides',
                            'Invalid number of sides, click "Cancel"',
                            minval=1)
    raise SystemExit  # Exit

while not length:  # A warning is included in case of the length is too long for the size of the screen.
    length = screen.numinput(
        "Select Length", "Enter side length "
        "\n(If the length is bigger than 100 and the sides more than 8, it might not fit the screen):",
        minval=1)

# Draw the shape with the number of sides from the user.
Beispiel #17
0
from turtle import Screen, Turtle
import random

screen = Screen()

screen.setup(width=500, height=400, startx=-100, starty=-100)

colors = ['red', 'green', 'orange', 'blue', 'yellow', 'purple']
all_turtles = {}

user_choice_turtle = int(
    screen.numinput(title="Make your bet:",
                    prompt='''Choose from number for your preferred color:
1:Red, 2:Green, 3:Orange, 4:Blue, 5:Yellow, 6:Purple''',
                    minval=1,
                    maxval=6))

y_pos = -150
for x in range(len(colors)):
    new_turtle = Turtle('turtle')
    new_turtle.penup()
    new_turtle.color(colors[x])
    new_turtle.goto(-230, y_pos)
    all_turtles[x + 1] = new_turtle
    y_pos += 60

game_running = True
winner = None
while game_running:
    position = 220
    for key in all_turtles: