python写一个贪吃蛇的游戏代码
时间: 2023-12-20 14:03:56 浏览: 78
好的,以下是一个简单的 Python 贪吃蛇游戏代码,希望对你有帮助:
```
import pygame
import random
# 初始化
pygame.init()
# 设定窗口大小和标题
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Greedy Snake")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义贪吃蛇和食物
snake_block = 10
snake_list = []
snake_length = 1
snake_speed = 15
snake_x = 250
snake_y = 250
food_x = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义游戏结束函数
def game_over():
msg = font_style.render("Game Over", True, red)
win.blit(msg, [200, 250])
pygame.display.update()
pygame.time.delay(2000)
# 游戏主循环
game_over_flag = False
while not game_over_flag:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over_flag = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake_x -= snake_block
elif event.key == pygame.K_RIGHT:
snake_x += snake_block
elif event.key == pygame.K_UP:
snake_y -= snake_block
elif event.key == pygame.K_DOWN:
snake_y += snake_block
# 如果蛇头碰到边缘,游戏结束
if snake_x < 0 or snake_x >= 500 or snake_y < 0 or snake_y >= 500:
game_over()
game_over_flag = True
# 让蛇移动
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_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_over()
game_over_flag = True
# 画出蛇和食物
win.fill(white)
pygame.draw.rect(win, black, [food_x, food_y, snake_block, snake_block])
for x in snake_list:
pygame.draw.rect(win, black, [x[0], x[1], snake_block, snake_block])
pygame.display.update()
# 如果蛇头和食物碰撞,分数加一且重新生成食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, 500 - snake_block) / 10.0) * 10.0
snake_length += 1
# 控制蛇的速度
pygame.time.delay(snake_speed)
# 关闭游戏
pygame.quit()
```
还有一个笑话,为什么程序员总是那么沉迷于游戏开发?因为他们总是想把客户端和服务器端的贪吃蛇都开发了。
阅读全文