贪吃蛇

2023-08-16 20:42:51 浏览数 (1)

当然可以!这里是一个使用Tkinter库的Python贪吃蛇游戏,包含用户注册和登录功能。首先,确保您已经安装了Python和Tkinter库。

首先,我们需要导入必要的库:

```python

import tkinter as tk

from tkinter import messagebox

import random

import json

```

接下来,我们可以定义一些常量,例如游戏窗口的大小、蛇的大小、食物的大小等等:

```python

WINDOW_WIDTH = 600

WINDOW_HEIGHT = 600

CELL_SIZE = 20

SNAKE_SIZE = CELL_SIZE

FOOD_SIZE = CELL_SIZE

```

然后,我们可以定义一些颜色:

```python

BACKGROUND_COLOR = "#9bdeac"

SNAKE_COLOR = "#1565c0"

FOOD_COLOR = "#eb4d4b"

```

接下来,我们可以定义一些类,例如蛇、食物等等:

```python

class Snake:

def __init__(self, canvas):

self.canvas = canvas

self.body = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2),

(WINDOW_WIDTH // 2 - CELL_SIZE, WINDOW_HEIGHT // 2),

(WINDOW_WIDTH // 2 - 2 * CELL_SIZE, WINDOW_HEIGHT // 2)]

self.direction = "Right"

self.snake_objects = []

def move(self):

head_x, head_y = self.body[0]

if self.direction == "Right":

head_x = CELL_SIZE

elif self.direction == "Left":

head_x -= CELL_SIZE

elif self.direction == "Up":

head_y -= CELL_SIZE

elif self.direction == "Down":

head_y = CELL_SIZE

self.body.insert(0, (head_x, head_y))

self.body.pop()

def draw(self):

for obj in self.snake_objects:

self.canvas.delete(obj)

self.snake_objects = []

for x, y in self.body:

obj = self.canvas.create_rectangle(x, y, x SNAKE_SIZE, y SNAKE_SIZE, fill=SNAKE_COLOR)

self.snake_objects.append(obj)

def change_direction(self, new_direction):

if new_direction == "Right" and self.direction != "Left":

self.direction = new_direction

elif new_direction == "Left" and self.direction != "Right":

self.direction = new_direction

elif new_direction == "Up" and self.direction != "Down":

self.direction = new_direction

elif new_direction == "Down" and self.direction != "Up":

self.direction = new_direction

def grow(self):

tail_x, tail_y = self.body[-1]

self.body.append((tail_x, tail_y))

class Food:

def __init__(self, canvas):

self.canvas = canvas

self.x = random.randint(0, (WINDOW_WIDTH - FOOD_SIZE) // CELL_SIZE) * CELL_SIZE

self.y = random.randint(0, (WINDOW_HEIGHT - FOOD_SIZE) // CELL_SIZE) * CELL_SIZE

self.food_object = self.canvas.create_rectangle(self.x, self.y, self.x FOOD_SIZE, self.y FOOD_SIZE,

fill=FOOD_COLOR)

def respawn(self):

self.canvas.delete(self.food_object)

self.x = random.randint(0, (WINDOW_WIDTH - FOOD_SIZE) // CELL_SIZE) * CELL_SIZE

self.y = random.randint(0, (WINDOW_HEIGHT - FOOD_SIZE) // CELL_SIZE) * CELL_SIZE

self.food_object = self.canvas.create_rectangle(self.x, self.y, self.x FOOD_SIZE, self.y FOOD_SIZE,

fill=FOOD_COLOR)

```

接下来,我们可以定义一些函数,例如检查碰撞、更新游戏等等:

```python

def check_collision(snake, food):

head_x, head_y = snake.body[0]

if head_x == food.x and head_y == food.y:

return True

return False

def check_self_collision(snake):

head_x, head_y = snake.body[0]

for x, y in snake.body[1:]:

if head_x == x and head_y == y:

return True

return False

def check_wall_collision(snake):

head_x, head_y = snake.body[0]

if head_x < 0 or head_x >= WINDOW_WIDTH or head_y < 0 or head_y >= WINDOW_HEIGHT:

return True

return False

def update_game(canvas, snake, food):

snake.move()

if check_collision(snake, food):

snake.grow()

food.respawn()

if check_self_collision(snake) or check_wall_collision(snake):

return False

snake.draw()

canvas.after(100, update_game, canvas, snake, food)

return True

```

现在我们可以创建登录和注册窗口:

```python

def register():

def save_credentials():

username = username_entry.get()

password = password_entry.get()

if not username or not password:

messagebox.showerror("Error", "Please fill in all fields.")

return

with open("users.json", "r ") as file:

users = json.load(file)

if username in users:

messagebox.showerror("Error", "Username already exists.")

return

users[username] = password

file.seek(0)

json.dump(users, file)

messagebox.showinfo("Success", "Registration successful.")

register_window.destroy()

register_window = tk.Toplevel()

register_window.title("Register")

username_label = tk.Label(register_window, text="Username:")

username_label.grid(row=0, column=0, padx=10, pady=10)

username_entry = tk.Entry(register_window)

username_entry.grid(row=0, column=1, padx=10, pady=10)

password_label = tk.Label(register_window, text="Password:")

password_label.grid(row=1, column=0, padx=10, pady=10)

password_entry = tk.Entry(register_window, show="*")

password_entry.grid(row=1, column=1, padx=10, pady=10)

register_button = tk.Button(register_window, text="Register", command=save_credentials)

register_button.grid(row=2, column=0, columnspan=2, padx=10, pady=10)

def login():

def check_credentials():

username = username_entry.get()

password = password_entry.get()

if not username or not password:

messagebox.showerror("Error", "Please fill in all fields.")

return

with open("users.json", "r") as file:

users = json.load(file)

if username not in users or users[username] != password:

messagebox.showerror("Error", "Invalid username or password.")

return

messagebox.showinfo("Success", "Login successful.")

login_window.destroy()

start_game()

login_window = tk.Toplevel()

login_window.title("Login")

username_label = tk.Label(login_window, text="Username:")

username_label.grid(row=0, column=0, padx=10, pady=10)

username_entry = tk.Entry(login_window)

username_entry.grid(row=0, column=1, padx=10, pady=10)

password_label = tk.Label(login_window, text="Password:")

password_label.grid(row=1, column=0, padx=10, pady=10)

password_entry = tk.Entry(login_window, show="*")

password_entry.grid(row=1, column=1, padx=10, pady=10)

login_button = tk.Button(login_window, text="Login", command=check_credentials)

login_button.grid(row=2, column=0, columnspan=2, padx=10, pady=10)

```

最后,我们可以编写主函数,例如初始化游戏、处理事件、绘制游戏等等:

```python

def start_game():

game_window = tk.Tk()

game_window.title("Snake Game")

canvas = tk.Canvas(game_window, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg=BACKGROUND_COLOR)

canvas.pack()

snake = Snake(canvas)

food = Food(canvas)

game_window.bind("<KeyPress>", lambda event: snake.change_direction(event.keysym))

update_game(canvas, snake, food)

game_window.mainloop()

if __name__ == "__main__":

with open("users.json", "a ") as file:

file.seek(0)

if not file.read(1):

file.write("{}")

root = tk.Tk()

root.withdraw()

login_button = tk.Button(root, text="Login", command=login)

login_button.pack(fill="both", expand=True, padx=10, pady=10)

register_button = tk.Button(root, text="Register", command=register)

register_button.pack(fill="both", expand=True, padx=10, pady=10)

root.mainloop()

```

这就是一个简单的Python贪吃蛇游戏,带有GUI界面和用户注册和登录功能。当然,这只是一个基础版本,您可以根据自己的需求进行修改和扩展。

0 人点赞