Python Turtle开发四子棋 如何处理超范围输入避免报错退出
问题说明
你在使用Python Turtle开发四子棋(Connect 4)程序时,通过长度为7的列表存储每列的落子状态,当前版本存在崩溃问题:当用户输入8、9等大于7,或是0、负数等不在1-7区间的列号时,会触发列表索引越界错误,导致游戏直接终止。需要修改代码实现:输入无效列号时程序不报错、不执行落子操作,玩家可以继续正常游戏。
问题根源
原有代码未对用户输入做任何合法性校验,直接将输入转为整数后就访问列表索引、修改游戏状态,除了超范围列号会触发索引错误外,输入字母、符号等非整数内容时,int()转换也会抛出错误导致崩溃;此外原有逻辑还存在隐藏问题:即使某列已经被棋子填满,仍然会累加列的高度计数,后续再选该列时棋子会绘制到棋盘外。
修改方法
- 封装通用的合法列号获取逻辑,统一处理红方、黄方的输入校验,避免重复代码
- 对输入做三层校验,不满足条件时直接给出提示并要求重新输入,不修改任何游戏状态、不执行落子:
- 校验输入是否为合法整数
- 校验转换后的列号是否在1-7的有效区间内
- 校验目标列是否已经被6个棋子填满(棋盘每列最多容纳6个棋子)
- 校验通过后再执行落子绘制、列计数累加、落子高度更新的操作。
修改后可直接运行的完整代码
import turtle pen = turtle.Turtle() screen = turtle.Screen() screen.setup(900,900) screen.title("四子棋") screen.tracer(0,0) fontText = ("Arial", 16) pen.ht() pen.penup() pen.speed(0) def board(): pen.color("blue") pen.fillcolor("blue") pen.goto(-350,-400) pen.pendown() pen.begin_fill() pen.goto(350,-400) pen.goto(350,200) pen.goto(-350,200) pen.goto(-350,-400) pen.end_fill() pen.penup() def circles(x,y): pen.goto(x,y) pen.color("white") pen.fillcolor("white") pen.begin_fill() for i in range(7): pen.pendown() pen.circle(25) pen.penup() pen.forward(100) pen.end_fill() pen.penup() def number(x,y,text): pen.color("black") pen.goto(x,y) pen.write(text, font=fontText, align="center") def drawCircles(): circles(-300, -370) circles(-300,-270) circles(-300,-170) circles(-300,-70) circles(-300,30) circles(-300,130) def numbers(): number(-300,220,"第1列") number(-200,220,"第2列") number(-100,220,"第3列") number(0,220,"第4列") number(100,220,"第5列") number(200,220,"第6列") number(300,220,"第7列") def draw_piece(x,y,color): pen.penup() pen.color(color) pen.fillcolor(color) pen.goto(x,y) pen.pendown() pen.begin_fill() pen.circle(25) pen.end_fill() pen.penup() def get_valid_column(prompt): while True: input_str = input(prompt) # 校验是否为整数 if not input_str.isdigit(): print("输入无效,请输入1-7之间的整数!") continue col = int(input_str) # 校验列号范围 if col < 1 or col >7: print("列号超出范围,请输入1-7之间的数字!") continue col_idx = col -1 # 校验列是否已填满 if kolomGevuld[col_idx] >=6: print("该列已满,请选择其他列!") continue return col_idx numbers() board() drawCircles() screen.update() start_y = -370 kolomGevuld = [0,0,0,0,0,0,0] rijGevuld = [start_y,start_y,start_y,start_y,start_y,start_y,start_y] space = 100 while True: # 红方回合 red_idx = get_valid_column("你要在哪一列放置红色棋子?请输入1-7的列号:") draw_piece(-300 + red_idx * space, rijGevuld[red_idx], "red") kolomGevuld[red_idx] +=1 rijGevuld[red_idx] += space screen.update() # 黄方回合 yellow_idx = get_valid_column("你要在哪一列放置黄色棋子?请输入1-7的列号:") draw_piece(-300 + yellow_idx * space, rijGevuld[yellow_idx], "yellow") kolomGevuld[yellow_idx] +=1 rijGevuld[yellow_idx] += space screen.update() turtle.done()
内容的提问来源于stack exchange,提问作者beginnercoder
相关产品推荐
相关产品推荐

