。下面是一个基本的贪吃蛇游戏代码示例,供参考。

import tkinter as tk
import random

# 定义常量
WIDTH = 500
HEIGHT = 500
DELAY = 100
UNIT_SIZE = 20

# 初始化变量
score = 0
direction = "Right"
new_direction = "Right"
snake = [(0, 0), (UNIT_SIZE, 0), (2*UNIT_SIZE, 0)]
food = None

# 创建主窗口
root = tk.Tk()
root.title("Snake Game")

# 创建画布
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

# 创建蛇和食物
def create_snake():
    for x, y in snake:
        canvas.create_rectangle(x, y, x+UNIT_SIZE, y+UNIT_SIZE, fill="green")

def create_food():
    global food
    x = random.randint(0, (WIDTH-UNIT_SIZE) // UNIT_SIZE) * UNIT_SIZE
    y = random.randint(0, (HEIGHT-UNIT_SIZE) // UNIT_SIZE) * UNIT_SIZE
    food = canvas.create_oval(x, y, x+UNIT_SIZE, y+UNIT_SIZE, fill="red")

# 蛇的移动
def move_snake():
    global direction, new_direction, score
    head_x, head_y = snake[-1]
    if new_direction == "Up":
        head_y -= UNIT_SIZE
    elif new_direction == "Down":
        head_y += UNIT_SIZE
    elif new_direction == "Left":
        head_x -= UNIT_SIZE
    elif new_direction == "Right":
        head_x += UNIT_SIZE
    snake.append((head_x, head_y))
    if head_x == food_x and head_y == food_y:
        score += 10
        canvas.delete(food)
        create_food()
    else:
        snake.pop(0)
    canvas.delete("all")
    create_snake()
    canvas.create_text(WIDTH-50, 20, text=f"Score: {score}")
    canvas.after(DELAY, move_snake)

# 碰撞检测
def check_collision():
    global snake
    head = snake[-1]
    x, y = head
    if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
        game_over()
    for i in range(len(snake)-1):
        if head == snake[i]:
            game_over()

# 游戏结束
def game_over():
    canvas.create_text(WIDTH//2, HEIGHT//2, text="Game Over!", font=("Arial", 20))
    canvas.after_cancel(move_id)

# 处理键盘事件
def on_key_press(event):
    global new_direction
    if event.keysym == "Up" and direction != "Down":
        new_direction = "Up"
    elif event.keysym == "Down" and direction != "Up":
        new_direction = "Down"
    elif event.keysym == "Left" and direction != "Right":
        new_direction = "Left"
    elif event.keysym == "Right" and direction != "Left":
        new_direction = "Right"

# 绑定键盘事件
canvas.bind_all("<Key>", on_key_press)

# 启动游戏
create_snake()
create_food()
move_id = canvas.after(DELAY, move_snake)
check_id = canvas.after(DELAY, check_collision)
root.mainloop()
游戏规则 贪吃蛇游戏的规则非常简单:玩家控制一条蛇通过不断地吃食物来增加自己的长度同时避免碰撞到墙壁或自己的身体。当蛇的头部碰到墙壁或身体时游戏结束。 游戏界面 游戏界面可以使用Python中的Tkinter模块进行设计。你可以创建一个画布将蛇和食物都绘制在画布上。 蛇的移动 蛇的移动可以通过不断地更新蛇的坐标来实现。每当蛇移动一格时就需要重新绘制蛇的身体。 食物的生成 食物可以随机生成在画

原文地址: https://www.cveoy.top/t/topic/bq2n 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录