Python贪吃蛇游戏高级代码
时间: 2024-05-04 20:14:45 浏览: 101
Python贪吃蛇游戏的高级代码可以实现更加丰富的游戏功能,例如添加难度级别、计分系统、声音效果等。以下是一个简单的Python贪吃蛇游戏高级代码示例:
```
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 设置游戏窗口尺寸
size = (400, 400)
screen = pygame.display.set_mode(size)
# 设置游戏标题
pygame.display.set_caption("Snake Game")
# 定义贪吃蛇类
class Snake():
def __init__(self):
self.x = 200
self.y = 200
self.size = 10
self.body = [[self.x, self.y]]
self.direction = "RIGHT"
def move(self):
if self.direction == "RIGHT":
self.x += 10
elif self.direction == "LEFT":
self.x -= 10
elif self.direction == "UP":
self.y -= 10
elif self.direction == "DOWN":
self.y += 10
self.body.insert(0, [self.x, self.y])
self.body.pop()
def change_direction(self, direction):
if direction == "RIGHT" and self.direction != "LEFT":
self.direction = "RIGHT"
elif direction == "LEFT" and self.direction != "RIGHT":
self.direction = "LEFT"
elif direction == "UP" and self.direction != "DOWN":
self.direction = "UP"
elif direction == "DOWN" and self.direction != "UP":
self.direction = "DOWN"
# 定义食物类
class Food():
def __init__(self):
self.x = random.randint(0, 39) * 10
self.y = random.randint(0, 39) * 10
def respawn(self):
self.x = random.randint(0, 39) * 10
self.y = random.randint(0, 39) * 10
# 初始化贪吃蛇和食物对象
snake = Snake()
food = Food()
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置初始分数和字体
score = 0
font = pygame.font.SysFont(None, 25)
# 游戏循环开始
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_RIGHT:
snake.change_direction("RIGHT")
elif event.key == pygame.K_LEFT:
snake.change_direction("LEFT")
elif event.key == pygame.K_UP:
snake.change_direction("UP")
elif event.key == pygame.K_DOWN:
snake.change_direction("DOWN")
# 移动贪吃蛇和检测碰撞
snake.move()
if snake.body < 0 or snake.body > size or snake.body < 0 or snake.body > size:
game_over = True
for i in range(1, len(snake.body)):
if snake.body == snake.body[i]:
game_over = True
if snake.body == [food.x, food.y]:
food.respawn()
snake.body.append(snake.body[-1])
score += 1
# 绘制游戏界面
screen.fill(WHITE)
for pos in snake.body:
pygame.draw.rect(screen, BLACK, [pos, pos, snake.size, snake.size])
pygame.draw.rect(screen, RED, [food.x, food.y, snake.size, snake.size])
text = font.render("Score: "+str(score), True, BLACK)
screen.blit(text, [10, 10])
pygame.display.update()
# 设置游戏帧率
clock.tick(10)
# 结束游戏并退出Pygame
pygame.quit()
quit()
```
阅读全文