|
发表于 2023-4-1 16:39:22
来自手机
|
显示全部楼层
来自 北京
好的,下面是一个简单的Python贪吃蛇游戏示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 创建游戏窗口
width = 500
height = 500
window = pygame.display.set_mode((width, height))
pygame.display.set_caption(\"贪吃蛇\")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏帧率
clock = pygame.time.Clock()
FPS = 10
# 定义贪吃蛇的初始位置和长度
snake_block_size = 10
snake_speed = 15
x1 = width/2
y1 = height/2
x1_change = 0
y1_change = 0
# 创建食物
food_size = 10
food_x = round(random.randrange(0, width - food_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - food_size) / 10.0) * 10.0
# 绘制贪吃蛇和食物的函数
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_block_size, snake_block_size])
def draw_food(x, y, food_size):
pygame.draw.rect(window, red, [x, y, food_size, food_size])
# 创建游戏循环
def game_loop():
game_over = False
game_close = False
snake_list = []
snake_length = 1
while not game_over:
while game_close:
window.fill(white)
font_style = pygame.font.SysFont(None, 30)
message = font_style.render(\"Game Over! Press Q-Quit or C-Restart\", True, red)
window.blit(message, [width/6, height/3])
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
elif 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 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
# 修改贪吃蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制游戏背景
window.fill(white)
# 绘制食物和贪吃蛇
draw_food(food_x, food_y, food_size)
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断是否吃到食物,如果吃到,加分并重新生成食物
for segment in snake_list[:-1]:
if segment == snake_head:
game_close = True
draw_snake(snake_block_size, snake_list)
pygame.display.update()
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, width - food_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - food_size) / 10.0) * 10.0
snake_length += 1
clock.tick(FPS)
pygame.quit()
quit()
# 开始游戏
game_loop()
```
这个示例只是一个基础的贪吃蛇游戏,你可以根据自己的喜好和需要进行改进和优化。 |
|