写一个贪吃蛇的PYTHON代码
时间: 2023-09-26 09:07:08 浏览: 91
### 回答1:
好的,以下是一个基本的Python贪吃蛇代码示例:
```
import pygame
import random
pygame.init()
# 设置游戏窗口大小和标题
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Snake Game")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
# 设置蛇的属性
snake_size = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义函数,显示消息
def message(msg, color):
message_text = font_style.render(msg, True, color)
screen.blit(message_text, [screen_width/6, screen_height/3])
# 定义蛇的运动
def snake(snake_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, green, [x[0], x[1], snake_size, snake_size])
# 开始游戏
def gameLoop():
game_over = False
game_close = False
# 设置蛇的位置
x1 = screen_width / 2
y1 = screen_height / 2
# 设置蛇的移动
x1_change = 0
y1_change = 0
# 设置蛇身
snake_List = []
Length_of_snake = 1
# 产生果实
foodx = round(random.randrange(0, screen_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - snake_size) / 10.0) * 10.0
# 进行游戏
while not game_over:
# 失败
while game_close == True:
screen.fill(black)
message("You Lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()
# 判断是否退出或重新开始
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
# 退出游戏
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 设置蛇的移动
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# 判断是否超出边界,并进行处理
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
screen.fill(black)
# 绘制果实
pygame.draw.rect(screen, white, [foodx, foody, snake_size, snake_size])
# 存储蛇的位置
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
# 判断是否连续吃到果实
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
# 绘制蛇
snake(snake_size, snake_List)
pygame.display.update()
# 判断是否吃到果实
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, screen_width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - snake_size) / 10.0) * 10.0
Length_of_snake += 1
# 设置蛇的速度
pygame.time.Clock().tick(snake_speed)
pygame.quit()
gameLoop()
```
### 回答2:
下面是一个简单的贪吃蛇的Python代码:
```python
import pygame
import random
# 初始化pygame模块
pygame.init()
# 定义常量
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
SNAKE_SIZE = 20
FPS = 10
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.x = SCREEN_WIDTH // 2
self.y = SCREEN_HEIGHT // 2
self.direction = "right"
self.length = 1
self.body = [(self.x, self.y)]
def move(self):
if self.direction == "right":
self.x += SNAKE_SIZE
elif self.direction == "left":
self.x -= SNAKE_SIZE
elif self.direction == "up":
self.y -= SNAKE_SIZE
elif self.direction == "down":
self.y += SNAKE_SIZE
self.body.append((self.x, self.y))
if len(self.body) > self.length:
del self.body[0]
def draw(self):
for segment in self.body:
pygame.draw.rect(screen, WHITE, (segment[0], segment[1], SNAKE_SIZE, SNAKE_SIZE))
def change_direction(self, key):
if key == pygame.K_RIGHT and self.direction != "left":
self.direction = "right"
elif key == pygame.K_LEFT and self.direction != "right":
self.direction = "left"
elif key == pygame.K_UP and self.direction != "down":
self.direction = "up"
elif key == pygame.K_DOWN and self.direction != "up":
self.direction = "down"
class Food:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH // SNAKE_SIZE - 1) * SNAKE_SIZE
self.y = random.randint(0, SCREEN_HEIGHT // SNAKE_SIZE - 1) * SNAKE_SIZE
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, SNAKE_SIZE, SNAKE_SIZE))
snake = Snake()
food = Food()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
snake.change_direction(event.key)
snake.move()
if snake.body[-1][0] == food.x and snake.body[-1][1] == food.y:
snake.length += 1
food = Food()
if snake.x < 0 or snake.x >= SCREEN_WIDTH or snake.y < 0 or snake.y >= SCREEN_HEIGHT:
running = False
for segment in snake.body[:-1]:
if snake.body[-1][0] == segment[0] and snake.body[-1][1] == segment[1]:
running = False
# 清屏
screen.fill(BLACK)
snake.draw()
food.draw()
# 更新屏幕
pygame.display.flip()
# 控制游戏速度
clock.tick(FPS)
# 退出游戏
pygame.quit()
```
这个代码使用了pygame库来实现游戏窗口的显示和用户输入的响应。贪吃蛇以一个矩形块的形式表示,通过键盘的上下左右键来控制蛇的移动方向,并且通过检测蛇头与食物的碰撞来增加蛇的长度。游戏的界面使用了一个黑色背景,贪吃蛇和食物使用不同的颜色来进行区分。
### 回答3:
以下是一个简单的贪吃蛇的Python代码:
```python
import pygame
import random
# 初始化游戏界面
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
# 定义贪吃蛇的初始位置和移动速度
snake_block = 20
snake_speed = 10
snake_x = screen_width / 2
snake_y = screen_height / 2
snake_x_change = 0
snake_y_change = 0
# 定义食物的初始位置
food_x = round(random.randrange(0, screen_width - snake_block) / 20) * 20
food_y = round(random.randrange(0, screen_height - snake_block) / 20) * 20
# 定义分数
score = 0
# 定义游戏结束的标志
game_over = False
# 游戏循环
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT: # 当用户点击关闭窗口时
game_over = True
if event.type == pygame.KEYDOWN: # 当用户按键时
if event.key == pygame.K_LEFT:
snake_x_change = -snake_block
snake_y_change = 0
elif event.key == pygame.K_RIGHT:
snake_x_change = snake_block
snake_y_change = 0
elif event.key == pygame.K_UP:
snake_y_change = -snake_block
snake_x_change = 0
elif event.key == pygame.K_DOWN:
snake_y_change = snake_block
snake_x_change = 0
# 更新贪吃蛇的位置
snake_x += snake_x_change
snake_y += snake_y_change
# 判断是否吃到了食物,如果是就生成新的食物并增加分数
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, screen_width - snake_block) / 20) * 20
food_y = round(random.randrange(0, screen_height - snake_block) / 20) * 20
score += 1
# 绘制贪吃蛇和食物
screen.fill((255, 255, 255))
pygame.draw.rect(screen, (0, 255, 0), (food_x, food_y, snake_block, snake_block))
pygame.draw.rect(screen, (0, 0, 0), (snake_x, snake_y, snake_block, snake_block))
# 刷新屏幕
pygame.display.update()
# 判断贪吃蛇是否碰到边界或自己的身体,如果是则游戏结束
if snake_x >= screen_width or snake_x < 0 or snake_y >= screen_height or snake_y < 0:
game_over = True
# 显示最终得分
font_style = pygame.font.SysFont(None, 50)
message = font_style.render("Game Over! Your score: " + str(score), True, (255, 0, 0))
screen.blit(message, (screen_width / 2 - 200, screen_height / 2 - 50))
pygame.display.update()
# 延迟关闭窗口
pygame.time.delay(2000)
pygame.quit()
```
这个代码使用pygame库创建了一个简单的贪吃蛇游戏。游戏界面的大小为800x600,贪吃蛇和食物都是矩形形状,贪吃蛇可以通过键盘的方向键进行控制。当贪吃蛇吃到食物时,会生成新的食物并增加分数;当贪吃蛇碰到边界或自己的身体时,游戏结束,并显示最终得分。
阅读全文