Python 文本版贪吃蛇游戏代码
当然可以帮您编写一个贪吃蛇游戏的文本版!以下是一个基本的文本版贪吃蛇游戏的 Python 代码示例:
import random
import msvcrt
# 定义游戏区域尺寸
WIDTH = 20
HEIGHT = 10
# 定义蛇身和食物的符号
SNAKE_SYMBOL = '■'
FOOD_SYMBOL = '★'
# 定义蛇类
class Snake:
def __init__(self):
self.body = [(WIDTH // 2, HEIGHT // 2)]
self.direction = 'right'
def move(self):
x, y = self.body[0]
if self.direction == 'up':
y -= 1
elif self.direction == 'down':
y += 1
elif self.direction == 'left':
x -= 1
elif self.direction == 'right':
x += 1
self.body.insert(0, (x, y))
self.body.pop()
def change_direction(self, new_direction):
if new_direction == 'up' and self.direction != 'down':
self.direction = new_direction
elif new_direction == 'down' and self.direction != 'up':
self.direction = new_direction
elif new_direction == 'left' and self.direction != 'right':
self.direction = new_direction
elif new_direction == 'right' and self.direction != 'left':
self.direction = new_direction
def check_collision(self):
x, y = self.body[0]
if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT or (x, y) in self.body[1:]:
return True
return False
def draw(self):
for y in range(HEIGHT):
for x in range(WIDTH):
if (x, y) == self.body[0]:
print(SNAKE_SYMBOL, end='')
elif (x, y) in self.body:
print('O', end='')
else:
print(' ', end='')
print()
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, WIDTH - 1)
self.y = random.randint(0, HEIGHT - 1)
def draw(self):
for y in range(HEIGHT):
for x in range(WIDTH):
if x == self.x and y == self.y:
print(FOOD_SYMBOL, end='')
else:
print(' ', end='')
print()
# 游戏初始化
snake = Snake()
food = Food()
# 游戏主循环
running = True
while running:
# 绘制游戏界面
snake.draw()
food.draw()
# 接收玩家输入
if msvcrt.kbhit():
key = msvcrt.getch().decode()
if key == 'w' or key == 'W':
snake.change_direction('up')
elif key == 's' or key == 'S':
snake.change_direction('down')
elif key == 'a' or key == 'A':
snake.change_direction('left')
elif key == 'd' or key == 'D':
snake.change_direction('right')
# 蛇移动
snake.move()
# 判断是否吃到食物
if snake.body[0] == (food.x, food.y):
snake.body.append((food.x, food.y))
food = Food()
# 判断游戏结束条件
if snake.check_collision():
running = False
print()
# 游戏结束提示
print('游戏结束!')
这是一个简单的文本版贪吃蛇游戏,您可以在此基础上进行更多的自定义和改进。希望您玩得开心!
原文地址: https://www.cveoy.top/t/topic/OZp 著作权归作者所有。请勿转载和采集!