写一个python语言,贪吃蛇小游戏
时间: 2023-05-22 17:03:17 浏览: 85
Python编写一个贪吃蛇游戏
以下是一个简单的 Python 贪吃蛇小游戏:
```
import pygame
import random
# 初始化 pygame
pygame.init()
# 游戏画面
screen_width = 500
screen_height = 500
game_screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Greedy Snake Game")
# 颜色定义
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
# 小方块大小
block_size = 10
# 字体定义
font_style = pygame.font.SysFont("bahnschrift", 25)
# 打印分数函数
def print_score(score):
score_text = font_style.render("Score: " + str(score), True, white)
game_screen.blit(score_text, [0, 0])
# 游戏结束函数
def game_over():
message = font_style.render("Game Over", True, red)
game_screen.blit(message, [screen_width / 6, screen_height / 3])
pygame.display.update()
pygame.time.wait(2000)
# 游戏主循环函数
def game_loop():
x, y = screen_width / 2, screen_height / 2 # 蛇头坐标
x_change, y_change = 0, 0 # 蛇头移动方向
food_x, food_y = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0, round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0 # 食物坐标
score = 0 # 得分
game_exit = False
while not game_exit:
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:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = block_size
x_change = 0
x += x_change
y += y_change
if x >= screen_width or x < 0 or y >= screen_height or y < 0: # 到达边缘,游戏结束
game_over()
game_exit = True
pygame.draw.rect(game_screen, green, [food_x, food_y, block_size, block_size]) # 画出食物
snake_head = [x, y]
snake_block = [snake_head]
pygame.draw.rect(game_screen, white, [x, y, block_size, block_size]) # 画出蛇头
# 吃到食物
if snake_head == [food_x, food_y]:
food_x, food_y = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0, round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
score += 10
pygame.display.update()
print_score(score)
pygame.time.wait(100) # 游戏速度控制
pygame.quit()
quit()
game_loop()
```
希望对您有所帮助!
阅读全文