可以用python写一个贪吃蛇游戏吗
时间: 2023-10-30 11:05:07 浏览: 19
当然可以,Python 是一种非常适合编写小型游戏的编程语言。以下是一个简单的 Python 贪吃蛇游戏的示例代码,你可以参考一下:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
width = 500
height = 500
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("Snake Game")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇初始位置和大小
snake_block_size = 10
snake_speed = 15
font_style = pygame.font.SysFont(None, 50)
# 定义显示分数的方法
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 3])
# 定义游戏循环
def gameLoop():
game_over = False
game_close = False
# 设置贪吃蛇初始位置和移动方向
x1 = width / 2
y1 = height / 2
x1_change = 0
y1_change = 0
# 生成食物初始位置
foodx = round(random.randrange(0, width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block_size) / 10.0) * 10.0
while not game_over:
# 游戏结束后的处理
while game_close == True:
screen.fill(white)
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_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断贪吃蛇是否超出边界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
# 更新贪吃蛇位置
x1 += x1_change
y1 += y1_change
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, red, [foodx, foody, snake_block_size, snake_block_size])
# 绘制贪吃蛇
pygame.draw.rect(screen, white, [x1, y1, snake_block_size, snake_block_size])
# 判断贪吃蛇是否吃到食物
if x1 == foodx and y1 == foody:
print("Yummy!!")
pygame.display.update()
# 控制游戏速度
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
# 开始游戏
gameLoop()
```
这段代码使用 Pygame 库来创建游戏窗口和处理游戏循环。在游戏循环中,我们更新贪吃蛇的位置、检测是否游戏结束、绘制贪吃蛇和食物等。你可以运行这段代码并自己尝试玩玩看。
阅读全文