Python贪吃蛇小游戏
时间: 2024-08-16 16:07:44 浏览: 59
Python贪吃蛇小游戏是一款经典的文本游戏,通常基于控制台界面,玩家通过键盘控制小蛇移动,目标是吃到屏幕上的食物并逐渐增加长度,同时避免碰到自己的身体。这里有一个简化的版本:
```python
import curses
import random
SNAKE_SPEED = 0.1
SNAKE_SIZE = 5
SNAKE_HEAD = (0, 0)
FOOD_POSITION = None
SNAKE_BODY = [(0, 0), (0, -1), (0, -2), ...] # 初始化蛇的身体
def main(stdscr):
global SNAKE_HEAD, FOOD_POSITION
curses.curs_set(0) # 隐藏光标
stdscr.clear()
while True:
# 检查是否吃到食物
if SNAKE_HEAD == FOOD_POSITION:
# 长大蛇身,生成新的食物位置
SNAKE_BODY.append(SNAKE_HEAD)
FOOD_POSITION = (random.randint(0, stdscr.getmaxyx() - 2),
random.randint(0, stdscr.getmaxyx() - 2))
# 更新蛇的位置
new_head = (SNAKE_HEAD, SNAKE_HEAD + SNAKE_SPEED * curses.KEY_DOWN)
if not valid_move(new_head, SNAKE_BODY):
break
SNAKE_BODY.insert(0, new_head)
# 渲染屏幕
for y in range(len(SNAKE_BODY)):
x = SNAKE_BODY[y]
stdscr.addch(y, x, 'O')
if y == len(SNAKE_BODY) - 1:
stdscr.addch(y, x, 'G') # 尾部用绿色表示
# 移动食物
if FOOD_POSITION is not None:
stdscr.addch(FOOD_POSITION, FOOD_POSITION, '*')
stdscr.refresh()
def valid_move(head, body):
return head not in body and 0 <= head < curses.LINES and 0 <= head < curses.COLS
curses.wrapper(main)
阅读全文