帮我把缩进修改正确import randomimport curses# 设置窗口s = curses.initscr()curses.curs_set(0)sh, sw = s.getmaxyx()w = curses.newwin(sh, sw, 0, 0)w.keypad(1)w.timeout(100)# 初始化游戏界面score = 0score_str = f"Score: {score}"w.addstr(0, sw//2 - len(score_str)//2, score_str)w.addstr(sh-1, sw-10, "Press 'q' to quit")w.refresh()# 初始化游戏参数snake_x = sw//4snake_y = sh//2snake = [ [snake_y, snake_x], [snake_y, snake_x-1], [snake_y, snake_x-2]]food = [sh//2, sw//2]w.addch(food[0], food[1], curses.ACS_PI)key = curses.KEY_RIGHTwhile True: next_key = w.getch() key = key if next_key == -1 else next_key # 判断是否退出游戏 if key == ord('q'): curses.endwin() quit() # 计算蛇头位置 new_head = [snake[0][0], snake[0][1]] if key == curses.KEY_DOWN: new_head[0] += 1 if key == curses.KEY_UP: new_head[0] -= 1 if key == curses.KEY_LEFT: new_head[1] -= 1 if key == curses.KEY_RIGHT: new_head[1] += 1 # 更新蛇的位置 snake.insert(0, new_head) if snake[0] == food: score += 1 score_str = f"Score: {score}" w.addstr(0, sw//2 - len(score_str)//2, score_str) food = None while food is None: # 随机生成食物的位置 nf = [ random.randint(1, sh-1), random.randint(1, sw-1) ] food = nf if nf not in snake else None w.addch(food[0], food[1], curses.ACS_PI) else: tail = snake.pop() w.addch(tail[0], tail[1], ' ') # 判断游戏是否结束 if snake[0][0] in [0, sh-1] or snake[0][1] in [0, sw-1] or snake[0] in snake[1:]: curses.endwin() quit() # 显示蛇的位置 w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
时间: 2024-02-29 22:52:42 浏览: 136
以下是修改后的代码,主要是根据 Python 的规范对缩进进行了调整:
```python
import random
import curses
# 设置窗口
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
# 初始化游戏界面
score = 0
score_str = f"Score: {score}"
w.addstr(0, sw//2 - len(score_str)//2, score_str)
w.addstr(sh-1, sw-10, "Press 'q' to quit")
w.refresh()
# 初始化游戏参数
snake_x = sw//4
snake_y = sh//2
snake = [ [snake_y, snake_x], [snake_y, snake_x-1], [snake_y, snake_x-2]]
food = [sh//2, sw//2]
w.addch(food[0], food[1], curses.ACS_PI)
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
# 判断是否退出游戏
if key == ord('q'):
curses.endwin()
quit()
# 计算蛇头位置
new_head = [snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] += 1
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
# 更新蛇的位置
snake.insert(0, new_head)
if snake[0] == food:
score += 1
score_str = f"Score: {score}"
w.addstr(0, sw//2 - len(score_str)//2, score_str)
food = None
while food is None:
# 随机生成食物的位置
nf = [ random.randint(1, sh-1), random.randint(1, sw-1) ]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
# 判断游戏是否结束
if snake[0][0] in [0, sh-1] or snake[0][1] in [0, sw-1] or snake[0] in snake[1:]:
curses.endwin()
quit()
# 显示蛇的位置
w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
```
阅读全文