使用python写个贪吃蛇游戏代码
时间: 2023-03-10 07:34:30 浏览: 115
这可能需要一些编程知识,但是我可以提供一些建议:1)使用Python中的turtle模块来创建游戏窗口和蛇的视觉表示;2)设计碰撞检测算法,以确定蛇是否撞到边界或自身;3)创建一个随机食物生成器,以使蛇保持饥饿;4)实现蛇的移动功能,并增加蛇的长度以反映吃到的食物。
相关问题
用Python写一个贪吃蛇游戏代码
好的,我可以为您提供一个Python写的贪吃蛇游戏代码。请注意,这是基于Python 3版本的代码。以下是代码:
```python
import tkinter as tk
import random
class Snake(tk.Canvas):
def __init__(self):
super().__init__(width=600, height=620, background="black", highlightthickness=0)
self.active = True
self.snake_positions = [(100, 100), (80, 100), (60, 100)]
self.food_position = self.set_new_food_position()
self.score = 0
self.direction = "Right"
self.bind_all("<Key>", self.on_key_press)
self.score_text = self.create_text(45, 12, text=f"Score: {self.score}",
fill="#fff", font=("TkDefaultFont", 14))
self.focus_set()
self.change_direction()
self.mainloop()
def on_key_press(self, event):
new_direction = event.keysym
all_directions = ("Up", "Down", "Left", "Right")
opposites = ({"Up", "Down"}, {"Left", "Right"})
if (new_direction in all_directions) and ({new_direction, self.direction} not in opposites):
self.direction = new_direction
def move_snake(self):
head_x, head_y = self.snake_positions[0]
if self.direction == "Left":
new_head_position = (head_x-20, head_y)
elif self.direction == "Right":
new_head_position = (head_x+20, head_y)
elif self.direction == "Up":
new_head_position = (head_x, head_y-20)
elif self.direction == "Down":
new_head_position = (head_x, head_y+20)
self.snake_positions = [new_head_position] + self.snake_positions[:-1]
for segment, position in zip (self.find_withtag("snake"), self.snake_positions):
self.coords(segment, position)
def change_direction(self):
if self.active:
self.move_snake()
self.check_collisions()
self.check_food_collision()
self.after(100, self.change_direction)
def set_new_food_position(self):
while True:
x_position = random.randint(1, 29) * 20
y_position = random.randint(3, 30) * 20
food_position = (x_position, y_position)
if food_position not in self.snake_positions:
return food_position
def check_food_collision(self):
if self.snake_positions[0] == self.food_position:
self.snake_positions.append(self.snake_positions[-1])
self.create_image(*self.snake_positions[-1], image=self.snake_body, tag="snake")
self.food_position = self.set_new_food_position()
self.score += 10
self.itemconfig(self.score_text, text=f"Score: {self.score}", fill="#fff")
def check_collisions(self):
head_x, head_y = self.snake_positions[0]
body = self.snake_positions[1:]
crosses = [position for position in body if position == (head_x, head_y)]
if (head_x < 0) or (head_x > 580) or (head_y < 20) or (head_y > 600) or crosses:
self.game_over()
def game_over(self):
self.active = False
self.delete(tk.ALL)
self.create_text(self.winfo_width()/2, self.winfo_height()/2,
text=f"Game Over!\nFinal Score: {self.score}", fill="#fff", font=("TkDefaultFont", 14))
if __name__ == "__main__":
root = tk.Tk()
root.title("Snake")
snake_game = Snake()
```
这段代码将创建一个窗口,其中包含一个可移动的贪吃蛇和一个随机放置的食物。当贪吃蛇吃掉食物时,它会变得更长,并增加玩家的分数。如果贪吃蛇碰到窗口的边缘或自己的身体,则游戏结束。
用python写一个贪吃蛇游戏代码
好的,以下是一个简单的贪吃蛇游戏的 Python 代码:
```python
import pygame
import random
# 设置游戏窗口尺寸
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 定义方块大小和蛇的初始长度
BLOCK_SIZE = 20
INITIAL_LENGTH = 3
# 初始化 pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置游戏窗口标题
pygame.display.set_caption("Snake Game")
# 创建时钟对象
clock = pygame.time.Clock()
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义方向常量
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.length = INITIAL_LENGTH
self.direction = RIGHT
self.body = []
for i in range(self.length):
self.body.append([i*BLOCK_SIZE, 0])
def move(self):
# 计算贪吃蛇头部的下一个位置
if self.direction == UP:
new_head = [self.body[0][0], self.body[0][1] - BLOCK_SIZE]
elif self.direction == DOWN:
new_head = [self.body[0][0], self.body[0][1] + BLOCK_SIZE]
elif self.direction == LEFT:
new_head = [self.body[0][0] - BLOCK_SIZE, self.body[0][1]]
elif self.direction == RIGHT:
new_head = [self.body[0][0] + BLOCK_SIZE, self.body[0][1]]
# 把新位置插入到贪吃蛇头部
self.body.insert(0, new_head)
# 如果贪吃蛇头部和食物位置重合,则贪吃蛇长度加1
if self.body[0] == food.position:
food.generate()
self.length += 1
# 如果贪吃蛇长度大于1,则删除贪吃蛇尾部
if self.length > 1:
self.body.pop()
def draw(self):
for block in self.body:
pygame.draw.rect(window, WHITE, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])
# 定义食物类
class Food:
def __init__(self):
self.position = [0, 0]
self.generate()
def generate(self):
# 在随机位置生成食物
x = random.randint(0, (WINDOW_WIDTH-BLOCK_SIZE)//BLOCK_SIZE) * BLOCK_SIZE
y = random.randint(0, (WINDOW_HEIGHT-BLOCK_SIZE)//BLOCK_SIZE) * BLOCK_SIZE
self.position = [x, y]
def draw(self):
pygame.draw.rect(window, RED, [self.position[0], self.position[1], BLOCK_SIZE, BLOCK_SIZE])
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏主循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake.direction != DOWN:
snake.direction = UP
elif event.key == pygame.K_DOWN and snake.direction != UP:
snake.direction = DOWN
elif event.key == pygame.K_LEFT and snake.direction != RIGHT:
snake.direction = LEFT
elif event.key == pygame.K_RIGHT and snake.direction != LEFT:
snake.direction = RIGHT
# 移动贪吃蛇
snake.move()
# 绘制游戏界面
window.fill(BLACK)
snake.draw()
food.draw()
# 检测贪吃蛇是否撞到墙壁或自己身体
if snake.body[0][0] < 0 or snake.body[0][0] >= WINDOW_WIDTH or snake.body[0][1] < 0 or snake.body[0][1] >= WINDOW_HEIGHT:
text = font.render("Game Over!", True, WHITE)
window.blit(text, [WINDOW_WIDTH//2-text.get_width()//2, WINDOW_HEIGHT//2-text.get_height()//2])
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
for block in snake.body[1:]:
if block == snake.body[0]:
text = font.render("Game Over!", True, WHITE)
window.blit(text, [WINDOW_WIDTH//2-text.get_width()//2, WINDOW_HEIGHT//2-text.get_height()//2])
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 更新游戏窗口
pygame.display.update()
# 设置游戏帧率
clock.tick(10)
```
运行以上代码,即可开始玩贪吃蛇游戏。