python贪吃蛇
时间: 2023-06-22 11:17:46 浏览: 107
Python贪吃蛇是一个经典的小游戏,玩家需要操纵一条小蛇在游戏区域内移动,吃到食物后身体会变长,如果撞到墙壁或自己的身体就会游戏失败。以下是一个简单的Python贪吃蛇代码示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏区域大小
width = 640
height = 480
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("Python贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇和食物的大小
block_size = 10
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义函数,显示消息
def message(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [width/6, height/3])
# 定义函数,绘制贪吃蛇
def snake(block_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], block_size, block_size])
# 定义主函数
def main():
game_over = False
game_close = False
# 初始化贪吃蛇的位置和长度
lead_x = width/2
lead_y = height/2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 初始化食物的位置
rand_food_x = round(random.randrange(0, width-block_size)/10.0)*10.0
rand_food_y = round(random.randrange(0, height-block_size)/10.0)*10.0
# 游戏循环
while not game_over:
# 如果游戏结束,显示消息
while game_close == True:
screen.fill(white)
message("游戏结束!按Q-退出或C-重新开始", 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:
main()
# 监听键盘事件
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:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
# 判断是否撞墙
if lead_x >= width or lead_x < 0 or lead_y >= height or lead_y < 0:
game_close = True
# 修改贪吃蛇的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制食物
pygame.draw.rect(screen, red, [rand_food_x, rand_food_y, block_size, block_size])
# 绘制贪吃蛇
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断是否撞到自己的身体
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
snake(block_size, snake_list)
pygame.display.update()
# 如果吃到食物,贪吃蛇变长
if lead_x == rand_food_x and lead_y == rand_food_y:
rand_food_x = round(random.randrange(0, width-block_size)/10.0)*10.0
rand_food_y = round(random.randrange(0, height-block_size)/10.0)*10.0
snake_length += 1
# 设置游戏刷新率
clock = pygame.time.Clock()
clock.tick(20)
# 退出Pygame
pygame.quit()
# 运行主函数
main()
```
这是一个比较简单的Python贪吃蛇代码,可以通过修改代码来增加游戏的难度和功能。
阅读全文