用python编写贪吃蛇小游戏
时间: 2023-12-06 22:04:00 浏览: 85
好的,以下是一个简单的贪吃蛇小游戏的 Python 代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义窗口大小和标题
win_width = 500
win_height = 500
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("贪吃蛇")
# 定义游戏参数
block_size = 10
score_font = pygame.font.SysFont("Arial", 20)
clock = pygame.time.Clock()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.x = win_width / 2
self.y = win_height / 2
self.body = [(self.x, self.y)]
self.direction = "right"
def move(self):
if self.direction == "right":
self.x += block_size
elif self.direction == "left":
self.x -= block_size
elif self.direction == "up":
self.y -= block_size
elif self.direction == "down":
self.y += block_size
self.body.insert(0, (self.x, self.y))
self.body.pop()
def draw(self):
for x, y in self.body:
pygame.draw.rect(win, white, (x, y, block_size, block_size))
def grow(self):
self.body.insert(0, (self.x, self.y))
def collide(self):
if self.x < 0 or self.x + block_size > win_width or self.y < 0 or self.y + block_size > win_height:
return True
for i in range(1, len(self.body)):
if self.x == self.body[i][0] and self.y == self.body[i][1]:
return True
return False
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, win_width - block_size)
self.y = random.randint(0, win_height - block_size)
def draw(self):
pygame.draw.rect(win, red, (self.x, self.y, block_size, block_size))
# 定义游戏主循环
def main():
snake = Snake()
food = Food()
score = 0
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_LEFT and snake.direction != "right":
snake.direction = "left"
elif event.key == pygame.K_RIGHT and snake.direction != "left":
snake.direction = "right"
elif 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"
# 移动贪吃蛇
snake.move()
# 判断是否碰到墙壁或自身
if snake.collide():
pygame.quit()
quit()
# 判断是否吃到食物
if snake.x == food.x and snake.y == food.y:
snake.grow()
food = Food()
score += 10
# 绘制游戏界面
win.fill(black)
snake.draw()
food.draw()
score_text = score_font.render("Score: " + str(score), True, white)
win.blit(score_text, (10, 10))
pygame.display.update()
# 控制游戏帧率
clock.tick(20)
# 启动游戏
if __name__ == "__main__":
main()
```
这个代码使用 Pygame 库来实现贪吃蛇小游戏。在游戏窗口中,你需要使用方向键来控制贪吃蛇的移动,尽量避免碰到墙壁或自身,吃到食物可以增加得分。游戏结束后会显示最终得分。
阅读全文