sheap 发表于 3 天前

作品分享的第二天"Alien"

"Alien"作品代码(拷贝即用):

from tkinter import*
window=Tk()
window.title('Alien')
c=Canvas(window,height=300,width=400)
c.pack()
body=c.create_oval(100,150,300,250,fill='green')
eye=c.create_oval(170,70,230,130,fill='white')
eyeball=c.create_oval(190,90,210,110,fill='black')
mouth=c.create_oval(150,220,250,240,fill='red')
neck=c.create_line(200,150,200,130)
hat=c.create_polygon(180,75,220,75,200,20,fill='blue')
def mouth_open(event):
    c.itemconfig(mouth,fill='black')
def mouth_close(event):
    c.itemconfig(mouth,fill='red')
def blink(event):
    c.itemconfig(eye,fill='green')
    c.itemconfig(eyeball,state=HIDDEN)
def unblink(event):
    c.itemconfig(eye,fill='white')
    c.itemconfig(eyeball,state=NORMAL)
words=c.create_text(200,280,text='I am an alien!')
def steal_hat(event):
    c.itemconfig(hat,state=HIDDEN)
    c.itemconfig(words,text='Give my hat back!')
def return_hat(event):
    c.itemconfig(hat,state=NORMAL)
    c.itemconfig(words,text='Thank you!')
c.bind_all('<KeyPress-a>',blink)
c.bind_all('<KeyPress-z>',unblink)
c.bind_all('<KeyPress-d>',steal_hat)
c.bind_all('<KeyPress-k>',return_hat)
c.bind_all('<KeyPress-t>',mouth_open)
c.bind_all('<KeyPress-h>',mouth_close)

可以给些建议,谢谢&#128591;
(没有用turtle函数,因为不会用,希望有大佬教导,可以看下我的日志,未来可能会改进程序**** Hidden Message *****

FishC 发表于 3 天前

FishC 专家点评

鱼油你好!看了你的两个作品,非常棒!作为计算机教育专家,我来给你一些具体的改进建议,让你的代码更专业、更健壮。

一、关于 "Alien"(Tkinter 图形版)

[*]代码结构:当前所有代码都写在一级函数里,建议用 class AlienGame: 封装,方便扩展和管理状态。
[*]变量命名: c 可以改成 canvas,更清晰。
[*]事件绑定: 目前使用了 bind_all 绑定按键,但若窗口失去焦点会失效;可以改成 window.bind('<KeyPress-a>', ...) 或绑定到画布。
[*]交互反馈: 比如按 'a' 眨眼后,眨眼应该是临时的,可以增加一个定时恢复(使用 after 方法),让程序更生动。
[*]退出按钮: 建议添加一个关闭按钮或按 Esc 退出,增加用户体验。
[*]图片支持: 如果需要更复杂的图形,可以学习 tkinter.PhotoImage 或 PIL 库。

改进示例(关键部分):

def blink(event):
    c.itemconfig(eye, fill='green')
    c.itemconfig(eyeball, state=HIDDEN)
    # 0.5秒后自动恢复
    window.after(500, unblink, event)


二、关于 "Ghost Game"(控制台版)

[*]输入验证: 用户可能输入非数字(如 'abc'),程序会崩溃。应使用异常处理 try...except 或 str.isdigit() 检查。
[*]逻辑改进: 当前如果用户输入 1/2/3 以外的数字,程序说“没有这个门”却不加分,但循环继续,这合理。但建议将判断条件改为 if door_num in : 更直观。
[*]游戏循环: 可以增加退出选项(如输入 'q' 退出),避免只能用运气结束游戏。
[*]函数封装: 把核心逻辑写成 def play_game(): 函数,方便后续升级(如增加难度、计分排行)。
[*]界面美化: 添加 os.system('cls') 清屏,或使用 time.sleep() 增加节奏感。

改进关键代码(输入验证):

while True:
    door = input('1,2,or 3? (输入 q 退出) ')
    if door.lower() == 'q':
      print('下次再来!')
      break
    if not door.isdigit() or int(door) not in (1,2,3):
      print('无效输入,请重新输入!')
      continue
    door_num = int(door)
    # 后续逻辑不变


你的创作热情很值得鼓励!继续完善这两个项目,可以加入更多交互细节,比如外星人眨眼计时、幽灵游戏分数排行榜等。期待你的新版本!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 作品分享的第二天"Alien"