使用Python实现贪吃蛇游戏。

以下代码中将使用字符表示蛇和食物,并在控制台中移动。

代码如下:

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键控制蛇的方向,每次蛇吃到食物时得分会增加并且食物会重新随机生成在游戏板上。

如有更多需求,请自行修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值