gpt4 book ai didi

python - 如何在 python 2 程序创建蛇游戏的前一点清除屏幕?

转载 作者:太空宇宙 更新时间:2023-11-04 12:17:06 26 4
gpt4 key购买 nike

我想创建一个贪吃蛇游戏。我的第一个目标是创建一个星号,它可以在不按任何键的情况下从上到下移动,模拟蛇的“移动”。我应该在我的代码中添加什么,以便 * 在控制台中移动而不打印循环运行的次数。

到目前为止我的代码是:

import time   
i=0
while (i<5):
print "*"
time.sleep(0.5)
i+=1

最佳答案

我绝对建议使用 curses 模块对终端进行细粒度控制。您可以找到许多使用此模块编程的 Snake 示例,例如 this one .

为了在没有诅咒的情况下处理它,我在下面编写了一些示例代码。请注意,您不能按原样使用 print,因为它会在每次调用后输出一个换行符 \n。 (在 Python 3 中,您可以编写 print("hello",end="",flush=True) 来解决这个问题)。所以,从字面上看,我正在使用 sys.stdout.write()

请记住使用 Ctrl+C 结束正在运行的终端程序。

import time
from sys import stdout as s

# Let's break this function down:
# After writing a line to stdout, any additional
# writing will happen at the end of this line.
# Use \r (the carriage return) to reset to the beginning of
# the line. Add 40 spaces to clear any characters on that line.
# Then, go back to the beginning of the line again.
def clear():
s.write("\r" + " "*40 + "\r")

x = 0
x_max = 20

while True:
clear()
time.sleep(0.2)

# Move the snake (*****) by increasing spaces
s.write(" "*x+"*****")

# Calling write puts characters into a 'buffer'
# Calling flush() will write that buffer to the screen
s.flush()

x += 1 # Increase the x position

# If the snake moves too far right,
# reset him
if (x > x_max):
x = 0

关于python - 如何在 python 2 程序创建蛇游戏的前一点清除屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47142536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com