1. 程式人生 > >9*9的矩形,中間有個星號,按不同方向鍵,星星對應移動

9*9的矩形,中間有個星號,按不同方向鍵,星星對應移動

man 初始 int \n class 隨機 random dom 不同

"""共9*9個字符,隨機打印一個星星,用戶輸入L/R/u/d,向相應方向移動一位,到達最左/右停止移動,輸入EXIT退出"""
#導入隨機數
from random import randint


#建一個類
class Star:
def __init__(self):#位置參數
self.row = randint(0,9)
self.col = randint(0,9)

#向左移動
def left(self):
if self.row>=1:
self.row-=1


#向右移動
def right(self):
if self.row<9:
self.row+=1

def up(self):
if self.col>=1:
self.col-=1

def down(self):
if self.col<9:
self.col+=1


#打印
def draw(self):
for i in range(0,10):
if i==self.col:
print("."*self.row+"*"+"."*(9-self.row))
else:
print("."*10)


#初始化
if __name__=="__main__":
a = 0#運行狀態開關

star = Star()#建立實例

while a ==0:#運行開關
star.draw()#實例執行類方法
command = input("\n請輸入移動方向或退出:L/l or R/r or D/d or U/u or exit")#提示對話
#向左移
if command.lower() =="r":
star.left()
elif command.lower() =="l":#向右移
star.right()
elif command.lower() == "u": # 向上移
star.up()
elif command.lower() == "d": # 向下移
star.down()
elif command.lower() =="exit": #退出
a+=1
else:print("你的輸入有誤!")

9*9的矩形,中間有個星號,按不同方向鍵,星星對應移動