class Setup(Turtle): def __init__(self): super().__init__() self.screen = Screen() self.screen.setup(width=800, height=600) self.screen.bgcolor('black') self.screen.tracer(0) self.screen.title('Pong') self.line() def line(self): for i in range(19): self.screen.tracer(0) line = Turtle('square') line.speed(0) line.penup() line.color('black') line.goto(0, 280 - (i * 30)) line.shapesize(0.5, 0.3, 0.5) line.color('white') def update(self): self.screen.update() def exit(self): self.screen.exitonclick() def onkey(self, func, key): self.screen.listen() self.screen.onkey(func, key) def quit(self): self.screen.bye()
def play(): screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake Snake Snake") 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") game_is_on = True while game_is_on: screen.update() time.sleep(.1) snake.move() # Detect Collision with food if snake.head.distance(food) < 15: scoreboard.increase_score() snake.extend() food.refresh() print("nom nom nom") # Detect Collision with wall if snake.head.xcor() > 280 or snake.head.xcor( ) < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: scoreboard.reset_score() snake.reset_snake() answer = screen.textinput("Replay?", "Y/N").lower() if answer == "y": screen.clear() play() else: screen.bye() # Detect Collision with Tail for segment in snake.segments: if segment == snake.head: pass elif snake.head.distance(segment) < 10: scoreboard.reset_score() snake.reset_snake() answer = screen.textinput("Replay?", "Y/N").lower() if answer == "y": screen.clear() play() else: screen.bye() screen.exitonclick()
def drawKoch(n): # 建议不要输太大的数,绘图速度太慢了,待改进中 s = Screen() t = Turtle() directions = koch(n) for move in directions: if move == 'F': t.forward(300 / 3**n) if move == 'L': t.lt(60) if move == 'R': t.rt(120) s.bye()
def drawkoch(n): s = Screen() t = Turtle() directions = koch(n) for move in directions: if move == 'F': t.forward(300/3**n) if move == 'L': t.lt(60) if move == 'R': t.rt(120) s.bye()
class Game(): def __init__(self): self.win = Screen() self.win.bgcolor('pink') # self.win.setup(width=w, height=h, startx=None, starty=None) self.border = Border() width, height = self.win.window_width(), self.win.window_height() print(width, height) self.border.draw_self((width, height)) self.turtle = Arrow() self.win.onkey(self.quit, 'q') self.win.onkey(self.arrow_left, 'Left') self.win.onkey(self.arrow_right, 'Right') self.win.onkey(self.arrow_up, 'Up') self.win.onkey(self.arrow_down, 'Down') self.win.listen() self.win.onclick(self.check_coord) self.increase_speed() self.move_arrow() def check_coord(self, x, y): print(x, y) def quit(self): self.win.bye() def move_arrow(self): self.turtle.move() self.win.ontimer(self.move_arrow, 50) def arrow_left(self): self.turtle.turn_left() def arrow_right(self): self.turtle.turn_right() def arrow_up(self): self.turtle.turn_up() def arrow_down(self): self.turtle.turn_down() def increase_speed(self): self.turtle.speedup() self.win.ontimer(self.increase_speed, 3000) def main(self): self.win.mainloop()
def drawKoch(n): 'desenha enésima curva de Koch usando instruções da função koch()' s = Screen() # cria tela t = Turtle() # cria turtle directions = koch(n) # obtém direções para desenhar Koch(n) for move in directions: # segue os movimentos especificados if move == 'F': t.forward(300/3**n) # move para frente, tamanho normalizado if move == 'L': t.lt(60) # gira 60 graus para a esquerda if move == 'R': t.rt(120) # gira 120 graus para a direita s.bye()
def play(n): 'shows the solution of a Tower of Hanoi problem with n disks' screen = Screen() Peg.pos = -200 p1 = Peg(n) p2 = Peg(n) p3 = Peg(n) for i in range(n): # disks are pushed around peg 1 p1.push(Disk(n - i)) # in decreasing order of diameter hanoi(n, p1, p2, p3) screen.bye()
def turtle_race(): colors = ["red", "orange", "yellow", "green", "blue", "purple"] all_turtles = [] x = -440 y = 300 is_race_on = False winning_color = [] screen = Screen() screen.setup(width=1000, height=700) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a colour: ") for color in colors: new_turtle = Turtle(shape="turtle") new_turtle.color(color) new_turtle.penup() new_turtle.setpos(x=x, y=y) all_turtles.append(new_turtle) y -= 120 if user_bet: is_race_on = True while is_race_on: for turtle in all_turtles: rand_distance = random.randint(0, 10) turtle.forward(rand_distance) if turtle.xcor() > 400: winning_color.append(turtle.color()[0]) if winning_color: winning_color = ", ".join(winning_color) if user_bet.lower() in winning_color: is_play_again = screen.textinput(title="You've won!", prompt=f"The {winning_color} turtle is the winner!\n" "Do you want to play again?(y/n) ") else: is_play_again = screen.textinput(title="You've lost...", prompt=f"The {winning_color} turtle is the winner.\n" "Do you want to play again?(y/n) ") if is_play_again == "y": for old_turtle in screen.turtles(): old_turtle.hideturtle() turtle_race() else: is_race_on = False screen.bye()
def drawKoch(n): '''draws nth Koch curve using instructions from function koch()''' s = Screen() # create screen t = Turtle() # create turtle directions = koch(n) # obtain directions to draw Koch(n) for move in directions: # follow the specified moves if move == 'F': t.forward(300 / 3**n) # forward move length, normalized if move == 'L': t.lt(60) # rotate left 60 degrees if move == 'R': t.rt(120) # rotate right 60 degrees s.bye()
def DrawKoch(int_num): s = Screen() t = Turtle() direction = Koch(int_num) for item in direction: if(item == 'F'): t.forward(300 / 3 ** int_num) if(item == 'L'): t.lt(60) #rotate left 60 degrees if(item == 'R'): t.rt(120) #rotate right 60 degrees s.bye()
def drawSnowflake(n): s = Screen() t = Turtle() directions = koch(n) for i in range(3): for move in directions: if move == 'F': t.fd(300 / 3**n) if move == 'L': t.lt(60) if move == 'R': t.rt(120) t.rt(120) s.bye()
def drawSnowflake(n): 'draws n-th snowflake curve using function koch() 3 times' s = Screen() t = Turtle() directions = koch(n) for i in range(3): for move in directions: # draw koch(n) if move == 'F': t.fd(300 / 3**n) if move == 'L': t.lt(60) if move == 'R': t.rt(120) t.rt(120) # turn right 120 degrees s.bye()
def drawSnowflake(n): 'desenha enésima curva de floco de neve com função koch() 3 vezes' s = Screen() t = Turtle() directions = koch(n) for i in range(3): for move in directions: # desenha koch(n) if move == 'F': t.fd(300/3**n) if move == 'L': t.lt(60) if move == 'R': t.rt(120) t.rt(120) # gira 120 graus para a direita s.bye()
def draw_levy(n): """ Draws nth Levy Curve using instructions from function levy """ s = Screen() t = Turtle() directions = levy(n) for move in directions: if move == 'F': t.forward(300 / n) if move == 'L': t.lt(45) if move == 'R': t.rt(45) s.bye()
def main(): screen = Screen() screen.bgpic("blank_states_img.gif") screen.setup(width=725, height=491) screen.title("Guess the state game") screen.onkey(screen.exitonclick, "Escape") screen.listen() states = pandas.read_csv("50_states.csv") states_guessed = [] while len(states_guessed) < len(states): answer = screen.textinput( title=f"{len(states_guessed)}/50 Guessed states", prompt="Guess the name of the states") if answer.lower() == "exit": # for state in states.state: # if state not in states_guessed: # state_data = states[states.state == state] # x = int(state_data.x) # y = int(state_data.y) # new_csv.append([state]) # Replaced code above with list comprehension method new_csv = [(row.state, row.x, row.y) for (index, row) in states.iterrows() if row.state not in states_guessed] df = pandas.DataFrame(new_csv) df.columns = ['state', 'x', 'y'] df.to_csv("Missed_states.csv", index=False) screen.bye() elif answer is not None: answer = answer.title() if answer in states.state.to_list(): states_guessed.append(answer) state_data = states[states.state == answer] x = int(state_data.x) y = int(state_data.y) position = (x, y) t = Turtle() t.hideturtle() t.penup() t.setpos(position) t.write(answer)
def main(): # Setup screen screen = Screen() screen.setup(width=1.0, height=1.0) # For fullscreen. screen.bgcolor('black') screen.title("Apollo 8 Free Return Simulation") # Instantiate gravitational system gravsys = GravSys() # Instantiate Earth turtle #image_earth = 'earth_100x100.gif' #screen.register_shape(image_earth) t = Turtle() screen.register_shape('earth', drawCircle(6.371, 72, t)) earth = Body(1000000, (-200, 0), Vec(0, -2.5), gravsys, 'earth') earth.pencolor('white') earth.fillcolor('white') earth.getscreen().tracer(0, 0) # So csm polys won't show while drawing. # Instantiate moon turtle #image_moon = 'moon_27x27.gif' #screen.register_shape(image_moon) #moon_circle = circle(1.737) screen.register_shape('moon', drawCircle(1.737, 72, t)) moon = Body(32000, (156.7, 0), Vec(-27, 147), gravsys, 'moon') moon.pencolor('gray') moon.fillcolor('gray') # Build command-service-module(csm)shape csm = Shape('compound') cm = ((0, 0.1), (0, -0.1), (0.1, 0)) csm.addcomponent(cm, 'Silver', 'red') # Silver and red are also good. screen.register_shape('csm', csm) # Instantiate Apollo 8 CSM turtle ship = Body(1, (Ro_X, Ro_Y), Vec(Vo_X, Vo_Y), gravsys, 'csm') ship.shapesize(0.1) ship.color('white') # Path color. Silver and red are also good. ship.getscreen().tracer(1, 0) ship.setheading(90) gravsys.sim_loop() screen.bye() #close window automatically
def snowflake(n): """ Draws n-th snowflake curve using Koch() 3 times """ s = Screen() t = Turtle() directions = koch(n) for i in range(3): for move in directions: # draw hook (n) if move == 'F': t.fd(300 / 3**n) if move == 'L': t.lt(60) if move == 'R': t.rt(120) t.rt(120) s.bye()
def main(): screen = Screen() screen.setup(width=600, height=600) screen.bgcolor('black') screen.tracer(0) screen.title('Turtle Crossing') screen.colormode(255) scoreboard = Scoreboard() player = Player() car_manager = CarManager() screen.listen() screen.onkey(player.move_up, 'Up') screen.onkey(player.move_down, 'Down') screen.onkey(player.move_left, 'Left') screen.onkey(player.move_right, 'Right') game_is_on = True while game_is_on: time.sleep(0.1) screen.update() car_manager.create_car() car_manager.move_cars() for car in car_manager.all_cars: if car.distance(player) < 25: game_is_on = False scoreboard.game_over() play_again = screen.textinput( title="You lost bitch", prompt='Would you like to play again?').lower() if play_again[0] == 'y': screen.clear() main() else: screen.bye() if player.ycor() > 280: scoreboard.increase_level() player.player_reset() screen.exitonclick()
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)
# Setting up objects in game. snake_instance = Snake() food_instance = Food(snake_instance.get_segments()) score = Score() # Accepting player input. screen.listen() screen.onkeypress(snake_instance.move_left, "Left") screen.onkeypress(snake_instance.move_right, "Right") screen.onkeypress(snake_instance.move_up, "Up") screen.onkeypress(snake_instance.move_down, "Down") # Game loop run = True while run: screen.update() time.sleep(0.05) snake_instance.movement() if snake_instance.wall_collision(): run = False if snake_instance.self_collision(): run = False if snake_instance.food_collision(food_instance.get_food_x(), food_instance.get_food_y()): food_instance.randomize(snake_instance.get_segments()) snake_instance.growth() score.inc_score() score.update_score_counter() screen.bye()
# Cursor cursor = Turtle() # Create cursor cursor.shape("triangle") # Cursor Shape cursor.shapesize(1, 1, 0) # Cursor size cursor.color("#ff0000") # Cursor Color "Red" cursor.speed(6) # Cursor speed # Line cursor.pencolor("#ffffff") # Line color "white" cursor.pensize(2) # Line size (pixels) # Pen position cursor.penup() # Stop Drawing cursor.setx(0) # set X position cursor.sety(0) # set Y position cursor.pendown() # Start Drawing # Movement Loop circle # Movement Distance (pixels) x = 35 for i in range(10): # repeat (10 times) cursor.circle() # draw a circle (Pixels) # EXIT window.bye() # Window closes turtle.done()
class Game: def __init__(self): self.init_screen() self.is_game_on = True self.is_game_exited = True self.snake = Snake() self.food = Food() self.scoreboard = Scoreboard() self.define_keys() def init_screen(self): self.screen = Screen() self.screen.setup(width=SCREEN_WIDTH, height=SCREEN_HEIGHT) self.screen.bgcolor(BG_COLOR) self.screen.title(TITLE) def set_game_on(self): self.is_game_on = True def set_game_off(self): self.is_game_on = False def reset(self): self.snake.reset() self.food.reset() self.scoreboard.reset() self.screen.clearscreen() self.__init__() self.start_game() def define_keys(self): self.screen.listen() self.screen.onkey(key="Up", fun=self.snake.up) self.screen.onkey(key="Down", fun=self.snake.down) self.screen.onkey(key="Left", fun=self.snake.left) self.screen.onkey(key="Right", fun=self.snake.right) self.screen.onkey(key="c", fun=self.set_game_off) self.screen.onkey(key="r", fun=self.reset) self.screen.onkey(key="x", fun=self.exit_game) self.screen.onkey(key="s", fun=self.start_game) def exit_game(self): self.screen.bye() def is_snake_on_edge(self): xcor = self.snake.xcor() ycor = self.snake.ycor() edge_up = SCREEN_HEIGHT / 2 - 10 edge_down = -SCREEN_HEIGHT / 2 - 10 edge_left = -SCREEN_WIDTH / 2 - 10 edge_right = SCREEN_WIDTH / 2 - 10 if xcor < edge_left or \ xcor > edge_right or \ ycor < edge_down or \ ycor > edge_up: self.set_game_off() self.scoreboard.game_over() def start_game(self): self.screen.tracer(0) while self.is_game_on: self.screen.update() time.sleep(0.1) self.snake.move() self.is_snake_on_edge() if self.snake.snake_head.distance(self.food) < 20: self.food.refresh() self.snake.grow_snake() self.scoreboard.increase_score() for segment in self.snake.segments[2:]: if self.snake.snake_head.distance(segment) < 10: self.set_game_off() self.scoreboard.game_over()
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") if not res: wind.bye() else: winner.clear() player_1.score = 0 player_2.score = 0 score.clear() 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")) ball.setx(ball.xcor() + ball.dx) ball.sety(ball.ycor() + ball.dy) if ball.ycor() > 290: ball.sety(290) ball.dy *= -1
class Frame: def __init__(self, width=800, height=600): self.width = width self.height = height self.screen = Screen() self.screen.setup(width=width + 100, height=height + 100, startx=0, starty=0) self.screen.setworldcoordinates(-50, -50, width + 50, height + 50) self.quit = False self.draw_frame() def close(self): self.screen.bye() def clear(self): self.draw_frame() def draw_frame(self): self.screen.clear() width = self.width height = self.height boundary = Turtle() boundary.hideturtle() boundary.speed('fastest') boundary.penup() boundary.goto(0 + 2, 0 - 15) boundary.write('0') boundary.goto(0 - 8, 0) boundary.write('0') boundary.goto(0, 0) boundary.pendown() boundary.goto(width, 0) boundary.penup() boundary.goto(width - 10, 0 - 15) boundary.write(str(int(width))) boundary.goto(width, 0) boundary.pendown() boundary.goto(width, height) boundary.goto(0, height) boundary.penup() boundary.goto(0 - 25, height - 10) boundary.write(str(int(height))) boundary.goto(0, height) boundary.pendown() boundary.goto(0, 0) boundary.penup() self.screen.register_shape("button", ((0, 0), (0, 85), (25, 85), (25, 0))) t = Turtle(shape="button") t.hideturtle() t.penup() t.fillcolor('pink') t.goto(width - 95, -20) t.showturtle() boundary.goto(width - 62, -40) boundary.write("Quit", font=("Arial", 12, "normal")) self.screen.onclick(self.check_quit) def check_quit(self, x, y): self.quit = 706 < x < 792 and -47 < y < -20
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()
resetgame() elif z == "a": # singles game_state = 100 doubles = False buttonAcolor() elif z == "b": # doubles doubles = True gamepoints = 21 servechange = 4 penalties = 20 game_state = 150 player3 = False player4 = False buttonBcolor() elif z == "q": # command to close window window.bye() while game_state == 100: gamesize() z = input(str(input)) if z == "r": # command to close window resetgame() elif z == "a": gamepoints = 21 servechange = 4 penalties = 20 game_state = 150 buttonAcolor() elif z == "b": gamepoints = 11 servechange = 1 penalties = 10
class Game(object): def __init__(self): self.snake = snake.Snake() self.monster = monster.Monster(ri(-24,24) * 10,ri(-24,24) * 10) self.interface = Screen() self.interface.setup(500, 500) self.interface.tracer(0) self.interface.onkey(self.up, "Up") self.interface.onkey(self.down, "Down") self.interface.onkey(self.left, "Left") self.interface.onkey(self.right, "Right") self.interface.listen() def up(self): self.snake.turn(0, 1) def down(self): self.snake.turn(0, -1) def left(self): self.snake.turn(-1, 0) def right(self): self.snake.turn(1, 0) def listen(self): self.snake.move() self.monster.move(self.snake.getx(), self.snake.gety()) grow_len = self.foods.update(self.snake.getx(), self.snake.gety()) if grow_len: self.snake.grow(grow_len) self.interface.update() def show(self): self.interface.ontimer(self.listen(), 100) return self.foods.empty() def tutorial(self): pen = Turtle(visible=False) pen.penup() pen.goto(-200, 100) pen.pendown() pen.write('Welcome to 119010136\'s snake game...\n\nYou are going to use the 4 arrow keys to move\nthe snake around the screen, trying to consume\nall the food items before the monster catches you...', align='left', font=('Arial', 13, 'bold')) self.snake.appear() self.monster.appear() def fun(x, y): pen.clear() self.play() self.interface.onclick(fun) def play(self): self.foods = food.Foods() self.interface.update() self.snake.grow(5) while True: if self.show(): self.snake.win() break elif self.snake.crash(): self.snake.lose() break elif self.snake.die(self.monster.getx(),self.monster.gety()): self.snake.lose() break def refresh(self): self.snake = snake.Snake() def close(self): self.interface.bye() def end(self): self.interface.mainloop()