python tkinter 写一个贪吃蛇
from tkinter import *
import random

# 游戏设置
GAME_WIDTH = 800  # 游戏宽度
GAME_HEIGHT = 800  # 游戏高度
SPEED = 50  # 贪吃蛇速度
SPACE_SIZE = 50  # 游戏单个部件的大小
BODY_PARTS = 3  # 贪吃蛇初始长度
SNAKE_COLOR = "#0000FF"  # 贪吃蛇颜色
FOOD_COLOR = "#FFFF00"  # 食物颜色
BACKGROUND_COLOR = "#000000"  # 游戏背景颜色


# 生成贪吃蛇
class Snake:

    def __init__(self, canvas):
        self.body_size = BODY_PARTS
        self.coordinates = []
        self.squares = []

        for i in range(0, BODY_PARTS):
            self.coordinates.append([0, 0])

        for x, y in self.coordinates:
            square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake")
            self.squares.append((square))


# 生成食物
class Food:

    def __init__(self, canvas):
        # 700 / 50 = 14 (0,13)
        x = random.randint(0, GAME_WIDTH / SPACE_SIZE - 1) * SPACE_SIZE
        y = random.randint(0, GAME_HEIGHT / SPACE_SIZE - 1) * SPACE_SIZE

        self.coordonates = [x, y]

        canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tags="food")


# 游戏
class Game:

    def __init__(self):

        self.window = Tk()
        self.window.title("Snake game")
        self.window.resizable(False, False)  # 设置为不可调整大小

        # 记录分数
        self.score = 0
        # 初始方向
        self.direction = "down"

        # 记录分数的窗体
        self.label = Label(self.window, text="Score:{}".format(self.score), font=("consolas", 40))
        self.label.pack()

        # 游戏运行主窗体
        self.canvas = Canvas(self.window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)
        self.canvas.pack()

        # 刷新窗体使其展示到屏幕中间
        self.window.update()

        window_width = self.window.winfo_width()
        window_height = self.window.winfo_height()
        screen_width = self.window.winfo_screenwidth()
        screen_height = self.window.winfo_screenheight()

        x = int((screen_width / 2) - (window_width / 2))
        y = int((screen_height / 2) - (window_height / 2))

        self.window.geometry(f"{window_width}x{window_height}+{x}+{y}")

        # 绑定按键事件
        self.window.bind("<Left>", lambda event: self.change_direction("left"))
        self.window.bind("<Right>", lambda event: self.change_direction("right"))
        self.window.bind("<Up>", lambda event: self.change_direction("up"))
        self.window.bind("<Down>", lambda event: self.change_direction("down"))

        # 调用生成贪吃蛇和食物
        snake = Snake(self.canvas)
        food = Food(self.canvas)

        # 调用开始游戏
        self.next_turn(snake, food)

        self.window.mainloop()

    # 开始游戏
    def next_turn(self, snake, food):
        # 绘制贪吃蛇身体
        x, y = snake.coordinates[0]

        if self.direction == "up":
            y -= SPACE_SIZE
        elif self.direction == "down":
            y += SPACE_SIZE
        elif self.direction == "left":
            x -= SPACE_SIZE
        elif self.direction == "right":
            x += SPACE_SIZE

        snake.coordinates.insert(0, (x, y))

        square = self.canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)

        snake.squares.insert(0, square)

        # 实现吃掉食物并计算分数
        if x == food.coordonates[0] and y == food.coordonates[1]:

            self.score += 1

            self.label.config(text="Score:{}".format(self.score))

            self.canvas.delete("food")

            food = Food(self.canvas)

        else:

            del snake.coordinates[-1]

            self.canvas.delete(snake.squares[-1])

            del snake.squares[-1]

        # 实现有碰撞结束游戏
        if self.check_collisions(snake):
            self.game_over()

        else:
            self.window.after(SPEED, self.next_turn, snake, food)

    # 控制方向
    def change_direction(self, new_direction):

        if new_direction == "left":
            if self.direction != "right":
                self.direction = new_direction
        elif new_direction == "right":
            if self.direction != "left":
                self.direction = new_direction
        elif new_direction == "up":
            if self.direction != "down":
                self.direction = new_direction
        elif new_direction == "down":
            if self.direction != "up":
                self.direction = new_direction

    # 检查碰撞
    def check_collisions(self, snake):

        x, y = snake.coordinates[0]

        # 检查墙壁碰撞
        if x < 0 or x >= GAME_WIDTH:
            return True
        elif y < 0 or y >= GAME_HEIGHT:
            return True

        # 检查身体碰撞
        for body_part in snake.coordinates[1:]:
            if x == body_part[0] and y == body_part[1]:
                return True

        return False

    # 游戏结束
    def game_over(self):

        self.canvas.delete(ALL)
        self.canvas.create_text(self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2, font=("consolas", 70),
                                text="GAME OVER", fill="red", tags="gameover")


Game()
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇