如何让 Turtle 等待按下的键

2024-01-09

我和我的团队创建了一款在 Turtle 上运行的棋盘游戏。我们很难在不需要 IDE 控制台的情况下运行游戏。 我们希望使用 onkeypress 来运行我们的游戏,这样用户就不必离开游戏窗口。

#import turtle
from turtle import *
from random import *
from time import *

#drawing board game
def boardgame(size):    
    """Draw a square by drawing a line and turning through 90 degrees 4 times"""
    pendown()
    color("black", "blue")
    begin_fill()
    for _ in range(4):
        forward(size)
        right(90)
    end_fill()
    penup() 

#numbering each tile
def number():
    """Draw the tile number for each tile"""
    # I tried to compress this part of the code, but a lot of bugs occured, so I decided to kep the big lines because it is way more simple
    goto(-300, 80)
    x = 0
    x += 1
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)
    goto(-300, -70)
    x += 5
    write(x)
    forward(square_size)
    x -= 1
    write(x)
    forward(square_size)
    x -= 1
    write(x)
    forward(square_size)
    x -= 1
    write(x)
    forward(square_size)
    x -= 1
    write(x)
    forward(square_size)
    goto(-300, -220)
    x += 5
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)
    x += 1
    write(x)
    forward(square_size)

#assingning tile order

def order(cmd):
    """Whites the order of the tile at the canter of the tile"""
    write(cmd,align="center", font=("Arial", 24, "normal"))

#drawing dice number
def dice_draw(number):
    """Write the dice number"""
    undo()
    goto(450,75)
    N = randint(1,4)
    sleep(1)
    write(N,align="center", font=("Arial", 40, "normal"))
    sleep(0.2)
    undo()
    write(N+2,align="center", font=("Arial", 40, "normal"))
    sleep(0.2)
    undo()
    write(number,align="center", font=("Arial", 40, "normal"))
    sleep(1)


#starting the interface
square_size = 150
penup()
hideturtle()
speed(0)

#writing title
def title():
    sleep(1)
    goto(0, 260)
    write("Turtle Racer",align="center", font=("Comic Sans MS", 80, "normal"))
    sleep(1)

#starting block
def start_box():
    penup()
    goto(-450,225)
    pendown()
    color("black", "green")
    begin_fill()
    forward(75)
    right(90)
    forward(150)
    right(90)
    forward(75)
    right(90)
    forward(150)
    right(90)
    end_fill()
    penup()

#drawing board
def board():

    goto(-375, 225)

    for i in range(5): 
        boardgame(square_size)

        forward(square_size)
    goto(-375,75)
    for i in range(5): 
        boardgame(square_size)

        forward(square_size)
    goto(-375, -75)
    for i in range(5): 
        boardgame(square_size)

        forward(square_size) 


#ending block
def end_box():
    penup()
    goto(375,-75)
    pendown()
    color("black", "red")
    begin_fill()
    forward(75)
    right(90)
    forward(150)
    right(90)
    forward(75)
    right(90)
    forward(150)
    right(90)
    end_fill()
    penup()

#drawing numbers
def draw_number():
    goto(-375, 225)
    number()
    goto(0, 130)
    order('-2')
    goto(300, 130)
    order('+1') 
    goto(0, -20)
    order('+2') 
    goto(-150, -170)
    order('-3')
    goto(300, -170)
    order('-14')
    order('-14')

#draw dice box
def dice_box():
    penup()
    goto(415, 140)
    pendown()
    for _ in range(4):
        forward(70)
        right(90)
    penup()
    goto(450,150)
    pendown()
    write("DICE",align="center", font=("Comic Sans MS", 20, "normal"))
    penup()

#winner message
#def win():

title()
start_box()
board()
end_box()
dice_box()
draw_number()

#end of fernando's code//////////////////////////////////////////////////////////////////////////////

#get the turtles ready to be played
player_one_turtle = Turtle()
player_one_turtle.color('cyan')
player_one_turtle.shape('turtle')
player_one_turtle.penup()
player_one_turtle.goto(-400, 112)

player_two_turtle = Turtle()
player_two_turtle.color('orange')
player_two_turtle.shape('turtle')
player_two_turtle.penup()
player_two_turtle.goto(-400, 188)
#an array for for the player positions that will move to each spot
#currently set for testing purposes
player_one_positions = [(-400, 112),(-300, 112),(-150, 112),(0, 112),(150, 112),(300, 112),(300, 30),(150, 30),(0, 30), (-150, 30), (-300, 30), (-300, -112), (-150, -112), (0, -112), (150, -112), (300, -112), (400, -112)] #on screen board positions
player_two_positions = [(-400, 188),(-300, 188),(-150, 188),(0, 188),(150, 188),(300, 188),(300, -38),(150, -38),(0, -38), (-150, -38), (-300, -38), (-300, -188), (-150, -188), (0, -188), (150, -188), (300, -188), (400, -188)] #on screen board positions
player_one_spot = 0;#which spot the player is on 
player_two_spot = 0;
board_size = 15#number of tiles on the board
dice_val = 0;#define to be used to temporarily store the value of the dice
winner = '';#set when there is a winner, also used to return the player's name 
hot_spot = {3: 1, 5: 6, 8: 10, 12: 9, 15: 1}#takes the board positions and moves them if landed on a specific square

#function returns a number between 1-6
def diceroll():
    number = randint(1, 6)
    return number


#start the game
while (winner == ''): #if the spot is greater than the board, that player has one
    #ask player one to roll
    print("player one value:" + str(player_one_spot))
    print("player two value:" + str(player_two_spot))
    input("Press enter to roll the dice: ")
    dice_val = diceroll()
    dice_draw(dice_val)
    player_one_spot = dice_val + player_one_spot#roll the dice for the player
    print("You roled: " + str(dice_val))
    if player_one_spot > board_size:
        winner = 'player one'
        #move turtle to the end of the board
        player_one_turtle.goto(400, -112)
        break #game is over
    #go to the new spot
    player_one_turtle.goto(player_one_positions[player_one_spot])
    #//move turtle to the new spot if on spot
    if player_one_spot in hot_spot: 
        for i in hot_spot: 
            if player_one_spot == i:
                player_one_spot = hot_spot[i]
                player_one_turtle.goto(player_one_positions[player_one_spot])
    #roll for the second plasyer
    dice_val = diceroll()
    dice_draw(dice_val)
    player_two_spot = dice_val + player_two_spot  #roll the dice for the computer
    print("The computer roled: " + str(dice_val))
    if player_two_spot > board_size:
        winner = 'player two'
        #//move turtle to the end 
        player_two_turtle.goto(400, -188)
        break  
    #go to the new spot
    player_two_turtle.goto(player_two_positions[player_two_spot])
    if player_two_spot in hot_spot: 
        for i in hot_spot: 
            if player_two_spot == i:
                player_two_spot = hot_spot[i]   
                player_two_turtle.goto(player_two_positions[player_two_spot])

print("player one value:" + str(player_one_spot))
print("player two value:" + str(player_two_spot))
if player_one_spot > player_two_spot:
    print('player one wins!')
else: 
    print('player two wins!')
exitonclick()

问题出在 while 循环中,需要输入才能运行代码。

input("Press enter to roll the dice: ")

我们很难找到输入的替代品。


这并不完美,但您可以使用textinput()Python3 Turtle 中的函数来实现这一点。一个极简的例子:

from turtle import Screen

screen = Screen()

while True:
    answer = screen.textinput("Next Game", "Press OK to roll the dice, Cancel to quit:")

    if answer is None:
        break
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让 Turtle 等待按下的键 的相关文章

随机推荐

  • iPhone 应用程序启动

    如何让我的 iPhone 应用程序每次都在同一位置启动 即我的 主 屏幕 我不希望用户回到上次玩游戏时的位置 就在游戏过程中 但这就是正在发生的事情 预先感谢您的任何提示 您需要设置UIApplicationExitsOnSuspend输入
  • asp-for 和 if 条件在同一组件中

    我正在尝试在组件内使用 asp for 和条件 但我找不到方法来做到这一点 这是我的代码
  • 设置定时器问题

    我的双核机器上运行以下代码 当我在同一台 PC 上运行该应用程序的一两个实例时 我的正确计时分辨率为 100 毫秒 然而 当我在同一台 PC 上运行同一应用程序的 3 个实例时 计时分辨率超过 100 毫秒 是否有可能使应用程序的 3 个实
  • Magento XML 用简单的英语构建?

    我一直在阅读有关 Magento 的内容 并且了解其请求周期的核心流程等 基于配置的 MVC 和类重写等 但是 我似乎找不到关于具体细节的好文章 文档 特别是当涉及到为自定义模块等构建 config xml 所需的不同节点时 或者 XML
  • 将不同版本的 python 与 virtualenvwrapper 一起使用

    我使用 Macports 在我的 Mac 上安装了各种版本的 python 当我选择 python 2 7 通过 port select python python27 virtualenvwrapper 工作完美 但是如果我选择另一个版本
  • 使用 boost 创建具有自定义环境的子进程

    文档boost https www boost org doc libs 1 64 0 doc html process html没有提供任何使用自定义环境创建子进程的示例process child 给出了一个例子process syste
  • 如何在单个事务中保存多个 django 模型?

    在我看来 我将数据保存在多个模型中 def myview request do some processing model1 save model2 save 如何确保有回滚model1 save 以防万一model2 save 引发错误
  • 当计时器结束时如何自动继续?

    我想在计时器用完时自动继续 我在这里构建了一个计时器 class Timer var timer NSTimer the callback to be invoked everytime the timer ticks var handle
  • 创造一个只是兑现的空洞承诺? [复制]

    这个问题在这里已经有答案了 我有一个包装器 可以捕获承诺的最后结果 对其进行格式化并输出数据 req resolve promise gt return promise then gt res json req user catch Seq
  • 使用跨几何图形的通用美学和数据框过滤 ggplot2 的几何图形

    假设我有以下数据框 Dummy data frame df lt data frame x rep 1 5 2 y runif 10 z rep c A B each 5 x y z 1 1 0 92024937 A 2 2 0 37246
  • 使用 python 解压主文件夹中的文件夹内的 gz 文件

    我在多个文件夹中有 gz 压缩文件 这些文件都位于名为 usa 的主文件夹中 我能够使用下面的代码提取单个文件 import gzip import shutil source r C usauc300 dbf gz output r C
  • Schedulers.io() 上的并行数据库搜索

    我想知道当我并行访问数据库表时是否应该使用 Schedulers io 还是 Schedulers newThread 例如 如果我使用 Schedulers io 并行地从数千个表中选择记录 则任务完成后会在线程池中创建很多新创建的线程
  • Scala 解释器有哪些限制和解决方法?

    什么样的结构需要 scalac 编译以及如何制作可在解释器中工作的等效结构 Edit 我想使用 scala 而不是 python 作为脚本语言 使用 usr bin scala 您应该能够在 REPL 中执行任何可以在外部代码中执行的操作
  • 将 UIImage 转换为 NSString(反之亦然)

    我需要一种方法来转换 NSString 中的 UIImage 然后将 NSString 转换回 UIImage Thanks 适用于 gt iOS 7 NSString imageToNSString UIImage image NSDat
  • mupdf for android:ndk-build问题(错误:typedef的重新定义......)

    我正在按照必要的步骤安装适用于 Android 的 MuPDF MuPDF 是在我的系统上构建的 我能够使用 C 来利用它 现在尝试使用 Android README 中的所有步骤均已成功执行 但当我执行到步骤 10 时 我就必须这样做nd
  • Rails 错误:`rescue in ':未初始化的常量 Bundler (NameError)

    今天早些时候 我更新了系统上的 gems gem update 它更新了一些 gem 但之后我无法启动我的 Rails 服务器 我收到此错误 Users gugguson rubys my rails app config boot rb
  • NoSuchMethodError Lcom/google/gson/Gson;改造响应后

    因此 我的应用程序发布近一年了 但没有看到此问题 现在它出现了 即使现在 我手机上的调试版本也没有这个问题 我从 Android Studio 打开的任何模拟器都没有任何问题 然而 Google 开发者控制台中的预发布报告中的几乎每个模拟器
  • 了解编译器的工作原理

    我正在学习 C 编程语言 我对编译器如何创建可执行文件有疑问 我的书上说 C 是一种编译语言 因此您需要将源代码翻译为计算机可以执行的文件 这个文件是由编译器生成的 称为目标代码 obj 但是像 hello world 程序这样的程序是由我
  • ostream 链接,输出顺序

    我有一个函数需要ostream引用作为参数 将一些数据写入流 然后返回对同一流的引用 如下所示 include
  • 如何让 Turtle 等待按下的键

    我和我的团队创建了一款在 Turtle 上运行的棋盘游戏 我们很难在不需要 IDE 控制台的情况下运行游戏 我们希望使用 onkeypress 来运行我们的游戏 这样用户就不必离开游戏窗口 import turtle from turtle