使用Q语言编写一个贪吃蛇小游戏
时间: 2024-03-05 20:49:17 浏览: 51
snake_snake_小游戏贪吃蛇_
很抱歉,我并不支持Q语言,但我可以给您提供一个基于Python的简单贪吃蛇小游戏代码,供您参考:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设定游戏界面大小
width = 640
height = 480
screen = pygame.display.set_mode((width, height))
# 设定游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# 设定游戏帧率
fps = pygame.time.Clock()
# 设定初始位置
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 设定初始食物位置
food_pos = [random.randrange(1, (width//10)) * 10, random.randrange(1, (height//10)) * 10]
food_spawn = True
# 设定初始方向
direction = "RIGHT"
change_to = direction
# 设定分数
score = 0
# 定义绘制文字函数
def draw_text(text, size, color, x, y):
font = pygame.font.SysFont(None, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
screen.blit(text_surface, text_rect)
# 定义游戏结束函数
def game_over():
draw_text("游戏结束", 40, red, width/2, height/4)
draw_text("分数: " + str(score), 30, white, width/2, height/2)
draw_text("按Q键退出", 20, white, width/2, height*3/4)
pygame.display.flip()
pygame.time.wait(5000)
pygame.quit()
quit()
# 开始游戏主循环
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_q:
pygame.quit()
quit()
elif event.key == pygame.K_LEFT:
change_to = "LEFT"
elif event.key == pygame.K_RIGHT:
change_to = "RIGHT"
elif event.key == pygame.K_UP:
change_to = "UP"
elif event.key == pygame.K_DOWN:
change_to = "DOWN"
# 判断是否反向移动
if change_to == "LEFT" and direction != "RIGHT":
direction = "LEFT"
elif change_to == "RIGHT" and direction != "LEFT":
direction = "RIGHT"
elif change_to == "UP" and direction != "DOWN":
direction = "UP"
elif change_to == "DOWN" and direction != "UP":
direction = "DOWN"
# 根据方向移动蛇头
if direction == "LEFT":
snake_pos[0] -= 10
elif direction == "RIGHT":
snake_pos[0] += 10
elif direction == "UP":
snake_pos[1] -= 10
elif direction == "DOWN":
snake_pos[1] += 10
# 增加蛇身长度
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
food_spawn = False
score += 1
else:
snake_body.pop()
# 重新生成食物
if not food_spawn:
food_pos = [random.randrange(1, (width//10)) * 10, random.randrange(1, (height//10)) * 10]
food_spawn = True
# 绘制游戏界面
screen.fill(black)
for pos in snake_body:
pygame.draw.rect(screen, green, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, blue, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# 判断是否撞墙或撞到自己
if snake_pos[0] < 0 or snake_pos[0] > width-10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > height-10:
game_over()
for block in snake_body[1:]:
if snake_pos == block:
game_over()
# 绘制分数
draw_text("分数: " + str(score), 18, white, width-80, 10)
# 更新游戏界面
pygame.display.update()
# 设定游戏帧率
fps.tick(15)
```
阅读全文