用Python写一个贪吃蛇小游戏
时间: 2023-05-21 22:01:43 浏览: 57
我可以帮助你用Python编写一个贪吃蛇小游戏。为了实现这一目标,首先需要创建一个游戏窗口,然后添加一个蛇和一块食物。接下来,我们需要设计游戏规则,包括蛇的移动逻辑和食物的生成逻辑,并实现边界检测和游戏结束条件。最后,我们在游戏中添加一些额外的功能,比如分数、暂停等,以完善游戏体验。
相关问题
使用PYTHON写一个贪吃蛇小游戏
好的,下面是使用Python实现贪吃蛇小游戏的代码,希望对你有帮助:
```python
import pygame
import sys
import time
import random
# 初始化pygame
pygame.init()
# 设置游戏界面大小及标题
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('贪吃蛇')
# 定义颜色变量
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
# 定义游戏结束函数
def gameOver():
# 设置字体样式
gameOverFont = pygame.font.SysFont('arial.ttf', 72)
# 设置字体颜色
gameOverSurf = gameOverFont.render('Game Over!', True, red)
# 设置字体位置
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
# 将字体渲染到界面中
playSurface.blit(gameOverSurf, gameOverRect)
# 刷新界面
pygame.display.flip()
# 延迟3秒钟退出游戏
time.sleep(3)
# 退出游戏
pygame.quit()
sys.exit()
# 定义主函数
def main():
# 初始化游戏速度
fpsClock = pygame.time.Clock()
# 初始化贪吃蛇的起始位置
snakePosition = [100, 100]
# 初始化贪吃蛇的身体长度
snakeSegments = [[100, 100], [80, 100], [60, 100]]
# 初始化食物的位置
foodPosition = [300, 300]
# 初始化食物的标志
foodSpawned = 1
# 初始化方向
direction = 'right'
# 初始化分数
score = 0
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 退出游戏
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord('d'):
direction = 'right'
if event.key == pygame.K_LEFT or event.key == ord('a'):
direction = 'left'
if event.key == pygame.K_UP or event.key == ord('w'):
direction = 'up'
if event.key == pygame.K_DOWN or event.key == ord('s'):
direction = 'down'
# 通过ESC键退出游戏
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# 根据方向移动贪吃蛇的位置
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
# 增加贪吃蛇的身体长度
snakeSegments.insert(0, list(snakePosition))
# 判断是否吃到食物
if snakePosition[0] == foodPosition[0] and snakePosition[1] == foodPosition[1]:
foodSpawned = 0
score += 1
else:
snakeSegments.pop()
# 重新生成食物位置
if foodSpawned == 0:
x = random.randrange(1, 32)
y = random.randrange(1, 24)
foodPosition = [int(x * 20), int(y * 20)]
foodSpawned = 1
# 填充背景颜色
playSurface.fill(black)
# 绘制贪吃蛇
for position in snakeSegments:
pygame.draw.rect(playSurface, green, pygame.Rect(
position[0], position[1], 20, 20))
# 绘制食物
pygame.draw.rect(playSurface, white, pygame.Rect(
foodPosition[0], foodPosition[1], 20, 20))
# 判断是否撞墙
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
if snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
# 判断是否碰到自己
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver()
# 设置分数字体样式
scoreFont = pygame.font.SysFont('arial.ttf', 24)
# 设置分数字体颜色
scoreSurf = scoreFont.render('Score: ' + str(score), True, white)
# 设置分数字体位置
scoreRect = scoreSurf.get_rect()
scoreRect.midtop = (320, 10)
# 将分数渲染到界面中
playSurface.blit(scoreSurf, scoreRect)
# 刷新界面
pygame.display.flip()
# 控制游戏速度
fpsClock.tick(10)
# 运行主函数
if __name__ == '__main__':
main()
```
运行以上代码后,就可以在游戏界面上体验贪吃蛇小游戏啦!
使用python写一个贪吃蛇小游戏
好的,下面是一个简单的贪吃蛇小游戏的代码,使用Python语言编写:
```python
import pygame
import random
pygame.init()
# 游戏区域大小
width = 500
height = 500
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 创建游戏窗口
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇小游戏")
# 设置帧率
clock = pygame.time.Clock()
# 定义蛇的大小和速度
snake_size = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 显示得分
def show_score(score):
score_text = font_style.render("得分:" + str(score), True, white)
game_display.blit(score_text, [0, 0])
# 绘制蛇
def draw_snake(snake_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, green, [x[0], x[1], snake_size, snake_size])
# 显示消息
def message(msg, color):
message_text = font_style.render(msg, True, color)
game_display.blit(message_text, [width / 6, height / 3])
# 游戏循环
def game_loop():
game_exit = False
game_over = 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 - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
while not game_exit:
while game_over == True:
game_display.fill(black)
message("游戏结束!按Q退出,按C重新开始", red)
show_score(length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
elif event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# 判断是否出界
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over = True
# 更新坐标
x1 += x1_change
y1 += y1_change
game_display.fill(black)
# 绘制食物
pygame.draw.rect(game_display, red, [foodx, foody, snake_size, snake_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 x in snake_list[:-1]:
if x == snake_head:
game_over = True
# 绘制蛇
draw_snake(snake_size, snake_list)
# 显示得分
show_score(length_of_snake - 1)
# 更新游戏
pygame.display.update()
# 判断是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
length_of_snake += 1
# 设置帧率
clock.tick(snake_speed)
pygame.quit()
quit()
game_loop()
```
你可以将以上代码复制到Python环境中运行,就可以开始游戏了!
阅读全文