使用linux编写一个贪吃蛇游戏
时间: 2024-05-13 15:19:04 浏览: 89
linux下的贪食蛇游戏
好的,下面是一个简单的贪吃蛇游戏示例代码,使用了Python和Pygame库,可以在Linux系统上运行:
```python
import pygame
import random
# 初始化
pygame.init()
# 设置窗口大小
width = 500
height = 500
screen = pygame.display.set_mode((width, height))
# 设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# 设置字体
font = pygame.font.SysFont(None, 25)
# 设置蛇和食物大小
block_size = 10
# 定义函数:绘制蛇
def snake(snake_List):
for block in snake_List:
pygame.draw.rect(screen, white, [block[0], block[1], block_size, block_size])
# 定义函数:显示消息
def message(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [width / 6, height / 3])
# 游戏循环
def gameLoop():
game_over = False
game_close = False
# 初始化蛇的位置和速度
x1 = width / 2
y1 = height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
# 初始化食物的位置
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
# 游戏主循环
while not game_over:
# 游戏结束
while game_close == True:
screen.fill(black)
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 = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = 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, block_size, block_size])
# 维护蛇的长度
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
# 判断是否吃到食物
for block in snake_List[:-1]:
if block == snake_Head:
game_close = True
# 绘制蛇
snake(snake_List)
# 更新屏幕
pygame.display.update()
# 判断是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
Length_of_snake += 1
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(20)
# 退出游戏
pygame.quit()
quit()
# 运行游戏
gameLoop()
```
你可以将上述代码保存到一个名为 snake.py 的文件中,使用以下命令在Linux终端中运行:
```
python snake.py
```
就可以开始游戏了。
阅读全文