python3.8做贪吃蛇
时间: 2024-03-19 21:38:09 浏览: 70
100行python代码完成的贪吃蛇游戏,简单方便快捷,下载即可运行,可做毕业设计
Python 3.8是一种流行的编程语言,可以用来开发各种类型的应用程序,包括游戏。下面是一个简单的Python 3.8贪吃蛇游戏的示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义蛇的初始位置和大小
snake_block_size = 20
snake_speed = 15
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
def our_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block_size, snake_block_size])
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [screen_width / 6, screen_height / 3])
def game_loop():
game_over = False
game_close = False
# 初始化蛇的位置和移动方向
x1 = screen_width / 2
y1 = screen_height / 2
x1_change = 0
y1_change = 0
# 初始化蛇的长度和身体坐标列表
snake_list = []
length_of_snake = 1
# 初始化食物的位置
foodx = round(random.randrange(0, screen_width - snake_block_size) / 20.0) * 20.0
foody = round(random.randrange(0, screen_height - snake_block_size) / 20.0) * 20.0
while not game_over:
while game_close:
screen.fill(BLACK)
message("游戏结束!按Q退出,按C重新开始", 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:
game_loop()
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 >= screen_width or x1 < 0 or y1 >= screen_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])
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_close = True
our_snake(snake_block_size, snake_list)
pygame.display.update()
# 判断蛇是否吃到食物,更新食物位置,增加蛇的长度
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, screen_width - snake_block_size) / 20.0) * 20.0
foody = round(random.randrange(0, screen_height - snake_block_size) / 20.0) * 20.0
length_of_snake += 1
# 控制蛇的移动速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
pygame.quit()
game_loop()
```
这是一个简单的贪吃蛇游戏示例,使用了Python 3.8和Pygame库。你可以运行这段代码来体验贪吃蛇游戏。如果你想进一步了解如何开发游戏,可以查阅相关的Python游戏开发教程。
阅读全文