gpt4 book ai didi

python - 为什么这段代码有 "ball"似乎沿着边缘滑动

转载 作者:太空狗 更新时间:2023-10-30 01:52:30 27 4
gpt4 key购买 nike

我儿子问我是否可以编写一个小程序让球在屏幕上弹跳,然后让我解释一下。发现一个很好的父子机会,我说“是的!没问题”。所以我挖掘了我的 python 技能并写了这个..

#!/usr/bin/python

#
# We have to tell python what stuff we're
# going to use. We do this by asking to import
# the code we'll be making use of
#
import curses
import random
import time

#
# We'll be using a screen handling
# package called "curses" so we need
# to initialise the screen
stdscr = curses.initscr()

# We need to make sure that
# keys we type will not show up
# on the screen spoiling the
# stuff we're drawing
curses.noecho()

# We need to tell curses that we don't
# want to wait when we ask for keys from
# the user, if there's non there then
# we want curses to carry on
stdscr.nodelay( True )

# This ones a bit tricky to explain.
# Basically it puts the keyboard into
# a mode which allows curses to do
# things with it...
curses.cbreak()

# Ok, now we can do the fun stuff

# First thing we need to do is to
# find out how big our screen is
max_y, max_x = stdscr.getmaxyx()

stdscr.box()

min_x = 1
min_y = 1

max_y = max_y - 2
max_x = max_x - 2

stdscr.addstr( min_y, min_x, "1" )
stdscr.addstr( min_y, max_x, "2" )
stdscr.addstr( max_y, min_x, "3" )
stdscr.addstr( max_y, max_x, "4" )

dir_x = 1
dir_y = 1

# Then we can pick a random point on the
# screen in both the y (up-down) and x
# (left-right) directions
y = random.randint( 0, max_y )
x = random.randint( 0, max_x )

# Ok, this basically says, while trying to
# get a key from the user keeps coming back
# with an error, meaning there aren't any keys
# to return, do the code inside the loop
while( stdscr.getch() == curses.ERR ):
# Ok, at the location we got, put a "0"
stdscr.addstr( y, x, "O" )
# stdscr.addstr( str( (y, x) ) )

# this just moves the cursor to a new location so we can see the "O" better
stdscr.move( 0, 0 )

# have the screen update
stdscr.refresh()

# now choose a new location
x = x + dir_x
y = y + dir_y

# have we gone too far
if x > max_x or x < min_x:
# change direction
dir_x = -dir_x
x = x + dir_x

if y > max_y or y < min_y:
# change direction
dir_y = -dir_y
y = y + dir_y

# wait a bit so we can see the screen we've drawn.
time.sleep( 0.05 )

# Ok, we're finished. Tidy up
curses.nocbreak()
stdscr.keypad( False )
curses.echo()
curses.endwin()

我运行了这个程序并且非常高兴。然而,当球击中边缘时,它似乎在“滑动”并且弹起不干净。

现在已经很晚了,所以我无法理解它,我想我应该把它扔出去看看是否有人能解释原因。我不是在修复代码之后,我很确定使用 <= 或 >= 测试会起作用。我只是无法理解它的作用...

谢谢马克。

最佳答案

您需要在“改变方向”代码中添加两次 dir_*。

关于python - 为什么这段代码有 "ball"似乎沿着边缘滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2121287/

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