以下代码中将使用字符表示蛇和食物,并在控制台中移动。
代码如下:
import os
import random
import time
# 游戏设置
board_size = 20 # 游戏板大小
snake = [(board_size // 2, board_size // 2 - 1)] # 蛇的初始位置
direction = 'RIGHT' # 蛇的初始方向
food = None # 食物的初始位置
score = 0 # 得分
# 清空控制台
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
# 打印游戏板
def print_board():
global snake, food
clear_screen()
for i in range(board_size):
for j in range(board_size):
if (i, j) in snake:
print('S', end=' ')
elif (i, j) == food:
print('F', end=' ')
elif i == j == 0 or i == board_size - 1 or j == board_size - 1:
print('#', end=' ')
else:
print(' ', end=' ')
print()
# 改变方向
def change_direction(new_direction):
global direction
if (direction == 'RIGHT' and new_direction == 'LEFT') or \
(direction == 'LEFT' and new_direction == 'RIGHT') or \
(direction == 'UP' and new_direction == 'DOWN') or \
(direction == 'DOWN' and new_direction == 'UP'):
return
direction = new_direction
# 移动蛇
def move_snake():
head_x, head_y = snake[-1]
if direction == 'UP':
new_head = (head_x, head_y - 1)
elif direction == 'DOWN':
new_head = (head_x, head_y + 1)
elif direction == 'LEFT':
new_head = (head_x - 1, head_y)
elif direction == 'RIGHT':
new_head = (head_x + 1, head_y)
if new_head in snake:
print("Game Over! You've hit yourself!")
exit(0)
snake.append(new_head)
if snake[0] == food:
global score
score += 1
food = None
else:
snake.pop(0)
if food is None:
food = (random.randint(1, board_size - 2), random.randint(1, board_size - 2))
# 游戏主循环
def game_loop():
global snake, food, score
print_board()
while True:
move_snake()
print_board()
print(f'Score: {score}')
time.sleep(0.5)
# 监听按键事件
def listen_key_events():
import sys
import select
while True:
if select.select([sys.stdin], [], [], 0.1) == ([sys.stdin], [], []):
char = sys.stdin.read(1)
if char == 'a':
change_direction('LEFT')
elif char == 'd':
change_direction('RIGHT')
elif char == 'w':
change_direction('UP')
elif char == 's':
change_direction('DOWN')
if __name__ == '__main__':
try:
game_thread = threading.Thread(target=game_loop)
listen_thread = threading.Thread(target=listen_key_events)
game_thread.start()
listen_thread.start()
game_thread.join()
except KeyboardInterrupt:
print("Game exited.")
此游戏中玩家可以使用WASD键控制蛇的方向,每次蛇吃到食物时得分会增加并且食物会重新随机生成在游戏板上。
如有更多需求,请自行修改。