生成的代码如下:
import sys, random, pygame
from pygame.color import THECOLORS as COLORS
from pygame.locals import *
def draw_background():
# white background
screen.fill(COLORS['white'])
pygame.draw.rect(screen, COLORS['black'], (-100, GAME_SIZE[1], 3000, 200), 0)
def draw_wall():
for xy in wall_list:
pygame.draw.rect(screen, COLORS['darkgray'],
(xy[0] - WALL_WIDTH / 2, xy[1] - WALL_WIDTH / 2, WALL_WIDTH, WALL_HEIGHT), 0)
def draw_snake():
head = snake_list[0]
pygame.draw.circle(screen, COLORS['darkred'], (head[0], head[1]), int(SNAKE_WIDTH / 2), 0)
for xy in snake_list[1:]:
pygame.draw.rect(screen, COLORS['darkred'],
(xy[0] - SNAKE_WIDTH / 2, xy[1] - SNAKE_WIDTH / 2, SNAKE_WIDTH, SNAKE_HEIGHT), 2)
def draw_food():
for xyz in food_list:
pygame.draw.rect(screen, FOOD_COLORS[xyz[2] - 1],
(xyz[0] - FOOD_WIDTH / 2, xyz[1] - FOOD_WIDTH / 2, FOOD_WIDTH, FOOD_HEIGHT), 0)
def draw_context():
txt = FONT_M.render('Snake length: ' + str(len(snake_list) - 1), True, COLORS['lightblue'])
x, y = 10, GAME_SIZE[1] + (int((SIZE[1] - GAME_SIZE[1]) / 2))
y = int(y - FONT_M.size('Count')[1] / 2)
screen.blit(txt, (x, y))
def draw_pause():
s = pygame.Surface(SIZE, pygame.SRCALPHA)
s.fill((255, 255, 255, 220))
screen.blit(s, (0, 0))
txt = FONT_M.render('PAUSE', True, COLORS['darkgray'])
x, y = SIZE[0] / 2, SIZE[1] / 2
x, y = int(x - FONT_M.size('PAUSE')[0] / 2), int(y - FONT_M.size('PAUSE')[1] / 2)
screen.blit(txt, (x, y))
def draw_dead():
s = pygame.Surface(SIZE, pygame.SRCALPHA)
s.fill((255, 255, 255, 240))
screen.blit(s, (0, 0))
txt = FONT_M.render('YOU DEAD', True, COLORS['black'])
x, y = SIZE[0] / 2, SIZE[1] / 2
x, y = int(x - FONT_M.size('YOU DEAD')[0] / 2), int(y - FONT_M.size('YOU DEAD')[1] / 2)
screen.blit(txt, (x, y))
def rect_cover(rect1, rect2):
left1 = int(rect1[0])
right1 = int(rect1[0] + rect1[2])
up1 = int(rect1[1])
down1 = int(rect1[1] + rect1[3])
left2 = int(rect2[0])
right2 = int(rect2[0] + rect2[2])
up2 = int(rect2[1])
down2 = int(rect2[1] + rect2[3])
if not (right2 <= left1 or left2 >= right1 or down2 <= up1 or up2 >= down1):
return True
return False
def add_food():
while (True):
xyz = [random.choice(X_LIST), random.choice(Y_LIST), random.choice([1, 2, 3, 4])]
if xyz not in wall_list:
food_list.append(xyz)
break
def add_body(length=1):
for c in range(length):
# 尾巴加一节
last2, last1 = snake_list[-2], snake_list[-1]
if last2[0] == last1[0]: # 竖着的两段
if last2[1] > last1[1]: # 朝下
snake_list.append([last1[0], last1[1] - SNAKE_WIDTH])
else:
snake_list.append([last1[0], last1[1] + SNAKE_WIDTH])
else: # 横着的两段
if last2[0] > last1[0]: # 朝右
snake_list.append([last1[0] - SNAKE_WIDTH, last1[1]])
else:
snake_list.append([last1[0] + SNAKE_WIDTH, last1[1]])
def check_food():
# 头与食物
first = snake_list[0]
snake_head_rect = (first[0] - SNAKE_WIDTH / 2, first[1] - SNAKE_WIDTH / 2, SNAKE_WIDTH, SNAKE_HEIGHT)
for i in range(len(food_list)):
xyz = food_list[i]
food_rect = (xyz[0] - FOOD_WIDTH / 2, xyz[1] - FOOD_WIDTH / 2, FOOD_WIDTH, FOOD_HEIGHT)
if rect_cover(snake_head_rect, food_rect):
add_body(xyz[2])
del food_list[i]
return True
return False
def check_dead():
first = snake_list[0]
snake_head_rect = (first[0] - SNAKE_WIDTH / 2, first[1] - SNAKE_WIDTH / 2, SNAKE_WIDTH, SNAKE_HEIGHT)
# 头与边缘
if first[0] < 0 or first[0] > GAME_SIZE[0] or first[1] < 0 or first[1] > GAME_SIZE[1]:
return True
# 头与墙壁
for xy in wall_list:
wall_rect = (xy[0] - WALL_WIDTH / 2, xy[1] - WALL_WIDTH / 2, WALL_WIDTH, WALL_HEIGHT)
if rect_cover(snake_head_rect, wall_rect):
return True
# 头与自身
for xy in snake_list[1:]:
body_rect = (xy[0] - SNAKE_WIDTH / 2, xy[1] - SNAKE_WIDTH / 2, SNAKE_WIDTH, SNAKE_HEIGHT)
if rect_cover(snake_head_rect, body_rect):
return True
return False
if name == "main":
# init pygame
pygame.init()
# contant
GAME_SIZE = [900, 900]
SIZE = [GAME_SIZE[0], GAME_SIZE[1] + 100]
FONT_S = pygame.font.SysFont('Times', 50)
FONT_M = pygame.font.SysFont('Times', 90)
DIRECTION = ['up', 'right', 'down', 'left']
X_LIST = [x for x in range(GAME_SIZE[0])]
Y_LIST = [y for y in range(GAME_SIZE[1])]
FOOD_COLORS = ((46, 139, 87), (199, 21, 133), (25, 25, 112), (255, 215, 0))
# wall
wall_list = [[100, 200], [600, 500], [350, 200], [500, 800]]
WALL_WIDTH, WALL_HEIGHT = 30, 30
# food
food_list = [(150, 200, 1), (300, 500, 1), (740, 542, 1), (300, 600, 1), (700, 600, 1)]
FOOD_WIDTH, FOOD_HEIGHT = 14, 14
# create screen 500*500
screen = pygame.display.set_mode(SIZE)
# variable parameter
snake_list = [[100 + 12 * 4, 100], [100 + 12 * 3, 100], [100 + 12 * 2, 100], [100 + 12 * 1, 100], [100, 100]]
SNAKE_WIDTH, SNAKE_HEIGHT = 12, 12
snake_v = 0
count_time = 0
# level
frame = 0.05
level = 1
# main loop
running = True
pause = False
dead = False
head = 'right'
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
elif event.type == pygame.MOUSEBUTTONDOWN:
pause = not pause
elif event.type == pygame.KEYUP:
if event.key == K_LEFT:
if head in ['up', 'down']:
head = 'left'
elif event.key == K_RIGHT:
if head in ['up', 'down']:
head = 'right'
elif event.key == K_UP:
if head in ['left', 'right']:
head = 'up'
elif event.key == K_DOWN:
if head in ['left', 'right']:
head = 'down'
# update data
if not pause and not dead:
count_time += frame * level
first = snake_list[0]
snake_list[1:] = snake_list[:-1]
if head == 'up':
snake_list[0] = [first[0], first[1] - SNAKE_WIDTH]
elif head == 'down':
snake_list[0] = [first[0], first[1] + SNAKE_WIDTH]
elif head == 'left':
snake_list[0] = [first[0] - SNAKE_WIDTH, first[1]]
elif head == 'right':
snake_list[0] = [first[0] + SNAKE_WIDTH, first[1]]
# background
draw_background()
# tunnel
draw_wall()
# choose item
draw_snake()
# food
draw_food()
# point
draw_context()
# pause
if not dead and pause:
draw_pause()
# dead
if dead:
draw_dead()
# flip
pygame.display.flip()
# pause 20ms
pygame.time.delay(int(frame / level * 1000))
# check win or not
dead = check_dead()
if check_food():
add_food()
pygame.quit()
运行后没有按钮
以下是一个使用Python 3.7和Pygame库编写的贪食蛇游戏,包含重来和退出按钮:
python
import pygame
import random
pygame.init()
screen_width = 400
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪食蛇")
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
snake_size = 20
snake_speed = 10
food_size = 20
food_speed = random.randint(1, 5)
wall_size = screen_width // 100
wall_speed = 1
snake_pos = [[100, 100]]
snake_dir = right = 0
food_pos = [random.randint(wall_size, screen_width - wall_size), random.randint(wall_size, screen_height - wall_size)]
food_spawn = True
walls = [[screen_width // 2 - wall_size // 2, screen_height // 2 - wall_size // 2], [screen_width // 2 - wall_size // 2, screen_height // 2 + wall_size // 2], [screen_width // 2 + wall_size // 2, screen_height // 2 + wall_size // 2], [screen_width // 2 + wall_size // 2, screen_height // 2 - wall_size // 2]]
current_wall = random.choice(walls)
next_wall = random.choice(walls)
walls.remove(current_wall)
clock = pygame.time.Clock()
font = pygame.font.SysFont("arial", 30)
message = font.render("Game Over", True, red)
message_rect = message.get_rect()
message_rect.centerx = screen_width // 2
message_rect.centery = screen_height // 2 - message_rect.height // 2 - 50
game_over = False
score = len(snake_pos) - 1
level = 1
levels = [15, 10, 7.5, 6, 4.5, 3.5]
level_progress = level - levels[0] + 1
level_text = font.render("Level: " + str(level), True, green)
level_rect = level_text.get_rect()
level_rect.topright = [screen_width - level_text.get_width() - 10, level_text.get_height() // 2]
next_level = font.render("Next Level", True, green)
next_level_rect = next
要使用Python编写一个简单的贪食蛇游戏并添加重来和退出按钮,您可以使用pygame库,这是一个非常强大的库,可以用来创建2D游戏和交互式图形用户界面。
以下是一个基本的贪食蛇游戏的代码示例:
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
# 定义颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 蛇头初始位置
snake_x = screen_width / 2
snake_y = screen_height / 2
# 蛇的身体部分
body_parts = [[snake_x, snake_y]]
# 移动速度
speed = [0, 0]
# 食物的位置
food_x = random.randint(10, screen_width - 10)
food_y = random.randint(10, screen_height - 10)
# 游戏循环
while True:
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 更新键盘输入
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
speed[1] = -5
speed[0] = 0
elif keys[pygame.K_DOWN]:
speed[1] = 5
speed[0] = 0
elif keys[pygame.K_LEFT]:
speed[0] = -5
speed[1] = 0
elif keys[pygame.K_RIGHT]:
speed[0] = 5
speed[1] = 0
# 更新蛇的位置
snake_x += speed[0]
snake_y += speed[1]
# 绘制背景色
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, GREEN, [food_x, food_y, 10, 10])
# 绘制蛇的身体
for x, y in body_parts[:-1]:
pygame.draw.rect(screen, WHITE, [x, y, 10, 10])
# 绘制蛇头
pygame.draw.rect(screen, RED, [snake_x, snake_y, 10, 10])
# 添加食物到蛇的身体
if snake_x == food_x and snake_y == food_y:
food_x = random.randint(10, screen_width - 10)
food_y = random.randint(10, screen_height - 10)
body_parts.append([snake_x, snake_y])
# 更新游戏状态
body_parts.pop(0)
body_parts.append([snake_x, snake_y])
# 判断游戏是否结束
if len(body_parts) >= 5:
print("Game Over")
break
# 更新屏幕
pygame.display.update()
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。