import os
def clear_screen():
"""清空終端屏幕"""
os.system('cls' if os.name == 'nt' else 'clear')
class TicTacToe:
def __init__(self):
self.board = [' ' for _ in range(9)]
self.current_player = 'X'
self.winner = None
self.game_over = False
def draw_board(self):
"""繪製棋盤"""
clear_screen()
print("========== 井字遊戲 ==========")
print("玩家:X 和 O")
print("位置對應數字鍵盤:")
print(" 7 | 8 | 9 ")
print("---+---+---")
print(" 4 | 5 | 6 ")
print("---+---+---")
print(" 1 | 2 | 3 ")
print("\n當前棋盤:")
print(f" {self.board[6]} | {self.board[7]} | {self.board[8]} ")
print("---+---+---")
print(f" {self.board[3]} | {self.board[4]} | {self.board[5]} ")
print("---+---+---")
print(f" {self.board[0]} | {self.board[1]} | {self.board[2]} ")
print(f"\n當前玩家:{self.current_player}")
def make_move(self, position):
"""玩家下棋"""
if self.board[position] == ' ' and not self.game_over:
self.board[position] = self.current_player
self.check_winner()
if not self.game_over:
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
return False
def check_winner(self):
"""檢查是否有贏家或平局"""
winning_combinations = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6]
]
for combo in winning_combinations:
a, b, c = combo
if self.board[a] == self.board[b] == self.board[c] != ' ':
self.winner = self.board[a]
self.game_over = True
return
if ' ' not in self.board:
self.game_over = True
def play(self):
"""遊戲主循環"""
while not self.game_over:
self.draw_board()
try:
move = int(input(f"玩家 {self.current_player},請選擇位置 (1-9): "))
if move < 1 or move > 9:
print("無效位置!請輸入 1-9 之間的數字。")
input("按 Enter 繼續...")
continue
position = move - 1
if not self.make_move(position):
print("該位置已被佔用!請選擇其他位置。")
input("按 Enter 繼續...")
except ValueError:
print("無效輸入!請輸入 1-9 之間的數字。")
input("按 Enter 繼續...")
self.draw_board()
if self.winner:
print(f"恭喜!玩家 {self.winner} 獲勝!")
else:
print("平局!")
play_again = input("\n再玩一次?(y/n): ").lower()
if play_again == 'y':
new_game = TicTacToe()
new_game.play()
if __name__ == "__main__":
game = TicTacToe()
game.play()
import pygame
import random
import sys
pygame.init()
WIDTH, HEIGHT = 600, 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
FPS = 10
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 120, 255)
GRAY = (40, 40, 40)
class Snake:
def __init__(self):
self.reset()
def reset(self):
"""重置蛇的狀態"""
self.length = 3
self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
self.score = 0
self.grow_pending = 2
def get_head_position(self):
"""獲取蛇頭位置"""
return self.positions[0]
def turn(self, point):
"""改變蛇的方向"""
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def move(self):
"""移動蛇"""
head = self.get_head_position()
x, y = self.direction
new_x = (head[0] + x) % GRID_WIDTH
new_y = (head[1] + y) % GRID_HEIGHT
new_position = (new_x, new_y)
if new_position in self.positions[1:]:
return False
self.positions.insert(0, new_position)
if self.grow_pending > 0:
self.grow_pending -= 1
else:
self.positions.pop()
return True
def grow(self):
"""蛇增長"""
self.grow_pending += 1
self.length += 1
self.score += 10
def draw(self, surface):
"""繪製蛇"""
for i, p in enumerate(self.positions):
color = BLUE if i == 0 else GREEN
rect = pygame.Rect(p[0] * GRID_SIZE, p[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE)
pygame.draw.rect(surface, color, rect)
pygame.draw.rect(surface, BLACK, rect, 1)
if i == 0:
eye_size = GRID_SIZE // 5
if self.direction == (0, -1):
left_eye = (p[0] * GRID_SIZE + GRID_SIZE // 3, p[1] * GRID_SIZE + GRID_SIZE // 3)
elif self.direction == (0, 1):
left_eye = (p[0] * GRID_SIZE + GRID_SIZE // 3, p[1] * GRID_SIZE + 2 * GRID_SIZE // 3)
elif self.direction == (-1, 0):
left_eye = (p[0] * GRID_SIZE + GRID_SIZE // 3, p[1] * GRID_SIZE + GRID_SIZE // 3)
else:
left_eye = (p[0] * GRID_SIZE + 2 * GRID_SIZE // 3, p[1] * GRID_SIZE + GRID_SIZE // 3)
if self.direction == (0, -1):
right_eye = (p[0] * GRID_SIZE + 2 * GRID_SIZE // 3, p[1] * GRID_SIZE + GRID_SIZE // 3)
elif self.direction == (0, 1):
right_eye = (p[0] * GRID_SIZE + 2 * GRID_SIZE // 3, p[1] * GRID_SIZE + 2 * GRID_SIZE // 3)
elif self.direction == (-1, 0):
right_eye = (p[0] * GRID_SIZE + GRID_SIZE // 3, p[1] * GRID_SIZE + 2 * GRID_SIZE // 3)
else:
right_eye = (p[0] * GRID_SIZE + 2 * GRID_SIZE // 3, p[1] * GRID_SIZE + 2 * GRID_SIZE // 3)
pygame.draw.circle(surface, WHITE, left_eye, eye_size)
pygame.draw.circle(surface, WHITE, right_eye, eye_size)
class Food:
def __init__(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
"""隨機生成食物位置"""
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def draw(self, surface):
"""繪製食物"""
rect = pygame.Rect(self.position[0] * GRID_SIZE, self.position[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE)
pygame.draw.rect(surface, self.color, rect)
pygame.draw.rect(surface, BLACK, rect, 1)
stem_rect = pygame.Rect(self.position[0] * GRID_SIZE + GRID_SIZE // 2 - 2, self.position[1] * GRID_SIZE - 3, 4, 5)
pygame.draw.rect(surface, (139, 69, 19), stem_rect)
class Game:
def __init__(self):
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("貪吃蛇遊戲")
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont('simhei', 25)
self.big_font = pygame.font.SysFont('simhei', 50)
self.snake = Snake()
self.food = Food()
self.speed = FPS
self.game_over = False
def draw_grid(self):
"""繪製遊戲網格"""
for x in range(0, WIDTH, GRID_SIZE):
pygame.draw.line(self.screen, GRAY, (x, 0), (x, HEIGHT), 1)
for y in range(0, HEIGHT, GRID_SIZE):
pygame.draw.line(self.screen, GRAY, (0, y), (WIDTH, y), 1)
def draw_score(self):
"""繪製分數"""
score_text = self.font.render(f'分數:{self.snake.score}', True, WHITE)
self.screen.blit(score_text, (5, 5))
length_text = self.font.render(f'長度:{self.snake.length}', True, WHITE)
self.screen.blit(length_text, (5, 35))
def draw_game_over(self):
"""繪製遊戲結束畫面"""
game_over_text = self.big_font.render('遊戲結束!', True, RED)
score_text = self.font.render(f'最終分數:{self.snake.score}', True, WHITE)
restart_text = self.font.render('按 R 鍵重新開始,按 ESC 鍵退出', True, WHITE)
self.screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2 - 60))
self.screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2))
self.screen.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT // 2 + 40))
def check_food_collision(self):
"""檢查是否吃到食物"""
if self.snake.get_head_position() == self.food.position:
self.snake.grow()
self.food.randomize_position()
while self.food.position in self.snake.positions:
self.food.randomize_position()
if self.snake.score % 100 == 0:
self.speed += 1
def handle_events(self):
"""處理遊戲事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if self.game_over:
if event.key == pygame.K_r:
self.snake.reset()
self.food.randomize_position()
self.game_over = False
self.speed = FPS
elif event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
else:
if event.key == pygame.K_UP:
self.snake.turn((0, -1))
elif event.key == pygame.K_DOWN:
self.snake.turn((0, 1))
elif event.key == pygame.K_LEFT:
self.snake.turn((-1, 0))
elif event.key == pygame.K_RIGHT:
self.snake.turn((1, 0))
def run(self):
"""運行遊戲主循環"""
while True:
self.handle_events()
if not self.game_over:
if not self.snake.move():
self.game_over = True
self.check_food_collision()
self.screen.fill(BLACK)
self.draw_grid()
self.snake.draw(self.screen)
self.food.draw(self.screen)
self.draw_score()
if self.game_over:
self.draw_game_over()
pygame.display.flip()
self.clock.tick(self.speed)
if __name__ == "__main__":
game = Game()
game.run()