整理了10款Python经典童年小游戏!注意别玩上瘾哟~(附源码)
曾开心哈
2024年08月26日 16:33
收录于文集
共311篇

童年的游戏总是充满着无尽的乐趣和回忆。如今,我们可以用 Python 编程语言来重新体验这些经典的童年游戏。下面就为大家介绍 10 款用 Python 实现的童年游戏,并附上源码,让你在编程的世界中重温童年的欢乐。

 完整版Python游戏源码在文末 

一、猜数字游戏

游戏规则:计算机随机生成一个数字,玩家通过猜测逐步逼近这个数字。

源码示例:

代码块
Python
自动换行
复制代码
import random

number = random.randint(1, 100)
guesses = 0

while True:
    guess = int(input("猜一个数字(1-100):"))
    guesses += 1
    if guess < number:
        print("猜小了!")
    elif guess > number:
        print("猜大了!")
    else:
        print(f"猜对了!你用了{guesses}次猜测。")
        break
复制成功

二、石头剪刀布游戏

游戏规则:玩家和计算机分别选择石头、剪刀、布中的一个,比较胜负。

源码示例:

代码块
Python
自动换行
复制代码
import random

choices = ["石头", "剪刀", "布"]

while True:
    player_choice = input("请选择(石头、剪刀、布):")
    computer_choice = random.choice(choices)
    print(f"计算机选择了:{computer_choice}")
    if player_choice == computer_choice:
        print("平局!")
    elif (player_choice == "石头" and computer_choice == "剪刀") or (player_choice == "剪刀" and computer_choice == "布") or (player_choice == "布" and computer_choice == "石头"):
        print("你赢了!")
    else:
        print("你输了!")
复制成功

三、贪吃蛇游戏

游戏规则:控制蛇吃食物,蛇身会越来越长。

源码示例:

代码块
Python
自动换行
复制代码
import pygame
import random

# 初始化 pygame
pygame.init()

# 屏幕尺寸
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

# 蛇的初始位置和大小
snake_block = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x = SCREEN_WIDTH / 2
snake_y = SCREEN_HEIGHT / 2

# 食物的初始位置
food_x = round(random.randrange(0, SCREEN_WIDTH - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - snake_block) / 10.0) * 10.0

# 游戏时钟
clock = pygame.time.Clock()

def draw_snake(snake_list):
    for x,y in snake_list:
        pygame.draw.rect(screen, (0, 255, 0), [x, y, snake_block, snake_block])

def run_game():
    game_over = False
    while not game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            snake_x -= snake_block
        if keys[pygame.K_RIGHT]:
            snake_x += snake_block
        if keys[pygame.K_UP]:
            snake_y -= snake_block
        if keys[pygame.K_DOWN]:
            snake_y += snake_block

        snake_head = []
        snake_head.append(snake_x)
        snake_head.append(snake_y)
        snake_list.append(snake_head)
        if len(snake_list) > snake_length:
            del snake_list[0]

        screen.fill((0, 0, 0))
        pygame.draw.rect(screen, (255, 0, 0), [food_x, food_y, snake_block, snake_block])
        draw_snake(snake_list)
        pygame.display.update()

        if snake_x == food_x and snake_y == food_y:
            food_x = round(random.randrange(0, SCREEN_WIDTH - snake_block) / 10.0) * 10.0
            food_y = round(random.randrange(0, SCREEN_HEIGHT - snake_block) / 10.0) * 10.0
            snake_length += 1

        if snake_x >= SCREEN_WIDTH or snake_x < 0 or snake_y >= SCREEN_HEIGHT or snake_y < 0:
            game_over = True

        clock.tick(snake_speed)

    pygame.quit()
    quit()

run_game()
复制成功

四、井字棋游戏

游戏规则:在 3x3 的棋盘上,玩家和计算机轮流下棋,先连成一条线的一方获胜。

源码示例:

代码块
Python
自动换行
复制代码
import random

board = [[' ' for _ in range(3)] for _ in range(3)]

def print_board():
    for row in board:
        print('|'.join(row))
        print('-' * 5)

def check_win(player):
    for i in range(3):
        if all(board[i][j] == player for j in range(3)):
            return True
        if all(board[j][i] == player for j in range(3)):
            return True
    if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
        return True
    return False

def computer_move():
    empty_cells = [(i, j) for i in range(3) for j in range(3) if board[i][j] == ' ']
    return random.choice(empty_cells)

def play_game():
    while True:
        print_board()
        row = int(input("请输入行号(0-2):"))
        col = int(input("请输入列号(0-2):"))
        if board[row][col] == ' ':
            board[row][col] = 'X'
            if check_win('X'):
                print_board()
                print("你赢了!")
                break
            if all(board[i][j]!= ' ' for i in range(3) for j in range(3)):
                print_board()
                print("平局!")
                break
            row, col = computer_move()
            board[row][col] = 'O'
            if check_win('O'):
                print_board()
                print("计算机赢了!")
                break
        else:
            print("该位置已被占用,请重新选择。")

play_game()
复制成功

五、五子棋游戏

游戏规则:在棋盘上,玩家和计算机轮流下棋,先连成五个子的一方获胜。

源码示例:

代码块
Python
自动换行
复制代码
board_size = 15
board = [[' ' for _ in range(board_size)] for _ in range(board_size)]

def print_board():
    for row in board:
        print(' '.join(row))

def check_win(player):
    # 检查行
    for i in range(board_size):
        for j in range(board_size - 4):
            if all(board[i][j + k] == player for k in range(5)):
                return True
    # 检查列
    for i in range(board_size - 4):
        for j in range(board_size):
            if all(board[i + k][j] == player for k in range(5)):
                return True
    # 检查正对角线
    for i in range(board_size - 4):
        for j in range(board_size - 4):
            if all(board[i + k][j + k] == player for k in range(5)):
                return True
    # 检查反对角线
    for i in range(4, board_size):
        for j in range(board_size - 4):
            if all(board[i - k][j + k] == player for k in range(5)):
                return True
    return False

def computer_move():
    empty_cells = [(i, j) for i in range(board_size) for j in range(board_size) if board[i][j] == ' ']
    return random.choice(empty_cells)

def play_game():
    while True:
        print_board()
        row = int(input("请输入行号(0-14):"))
        col = int(input("请输入列号(0-14):"))
        if board[row][col] == ' ':
            board[row][col] = 'X'
            if check_win('X'):
                print_board()
                print("你赢了!")
                break
            if all(board[i][j]!= ' ' for i in range(board_size) for j in range(board_size)):
                print_board()
                print("平局!")
                break
            row, col = computer_move()
            board[row][col] = 'O'
            if check_win('O'):
                print_board()
                print("计算机赢了!")
                break
        else:
            print("该位置已被占用,请重新选择。")

play_game()
复制成功

六、弹珠游戏

游戏规则:模拟弹珠的运动和碰撞。

源码示例:

代码块
Python
自动换行
复制代码
import random

class Marble:
    def __init__(self, x, y, speed_x, speed_y):
        self.x = x
        self.y = y
        self.speed_x = speed_x
        self.speed_y = speed_y

    def move(self):
        self.x += self.speed_x
        self.y += self.speed_y
        if self.x <= 0 or self.x >= width:
            self.speed_x = -self.speed_x
        if self.y <= 0 or self.y >= height:
            self.speed_y = -self.speed_y

width = 500
height = 500
marbles = [Marble(random.randint(0, width), random.randint(0, height), random.randint(-5, 5), random.randint(-5, 5)) for _ in range(10)]

while True:
    for marble in marbles:
        marble.move()
    # 这里可以使用图形库来绘制弹珠的位置,这里只是概念性示例,没有实际的图形显示
复制成功

七、捉迷藏游戏(模拟)

游戏规则:玩家寻找隐藏的角色。

源码示例:

代码块
Python
自动换行
复制代码
import random

hiders = ['小明', '小红', '小刚']
seeker = '玩家'
hidden_locations = {person: random.randint(1, 10) for person in hiders}

def check_hider(person, guess):
    if hidden_locations[person] == guess:
        print(f"{person}被找到了!")
        del hidden_locations[person]
    else:
        print(f"{person}不在这个位置。")

while hidden_locations:
    print(f"现在是{seeker}寻找。")
    for person in hiders:
        if person in hidden_locations:
            guess = int(input(f"猜猜{person}在哪里(1-10):"))
            check_hider(person, guess)
复制成功

八、跳房子游戏(模拟)

游戏规则:通过跳跃前进,完成游戏。

源码示例:

代码块
Python
自动换行
复制代码
steps = 10
current_position = 0

while current_position < steps:
    jump = random.randint(1, 3)
    print(f"向前跳了{jump}步。")
    current_position += jump
    print(f"现在在第{current_position}步。")
print("完成跳房子游戏!")
复制成功

九、翻花绳游戏(模拟)

游戏规则:通过变换花绳形状进行游戏。

源码示例:

代码块
Python
自动换行
复制代码
shapes = ['面条', '降落伞', '五角星']

current_shape = random.choice(shapes)

print(f"开始的形状是{current_shape}。")

while True:
    new_shape = input("请输入下一个形状:")
    if new_shape in shapes and new_shape!= current_shape:
        current_shape = new_shape
        print(f"现在的形状是{current_shape}。")
    else:
        print("输入错误,请重新输入一个有效的形状。")
复制成功

十、打弹弓游戏(模拟)

游戏规则:模拟弹弓发射物体,命中目标。

源码示例:

代码块
Python
自动换行
复制代码
import math
import random

distance = 100
power = random.randint(1, 10)
angle = random.randint(15, 75)

def calculate_distance(power, angle):
    # 这里可以根据物理公式进行简单的距离计算,这只是一个模拟示例
    return power * 5 * math.sin(math.radians(angle))

calculated_distance = calculate_distance(power, angle)

if abs(calculated_distance - distance) < 10:
    print("命中目标!")
else:
    print("未命中目标。")
复制成功

快来试试这些用 Python 实现的童年游戏吧,让你的编程之旅充满乐趣!同时,也可以根据自己的需求对源码进行修改和扩展,创造出属于自己的独特游戏体验。

写在最后

除了以上Python实战项目,曾曾还给大家准备了另外25款Python小游戏视频教程及源码,不管是作为项目练手,还是毕业设计都可以,都已经打包好啦!需要的可以文末自取!

1、一键三连+关注

2、后台回复“Python”即可