【Python游戏】五大经典小游戏完整代码分享

文章目录

  • 前言
  • 案例1: 猜数字游戏
  • 案例2: 石头剪刀布游戏
  • 案例3: 使用pygame的简单打砖块游戏
  • 案例4: 井字棋(Tic-Tac-Toe)
  • 案例5: 贪吃蛇游戏(使用pygame)

  • 前言

    当然,我可以为你提供五个简单的Python游戏案例。这些游戏涵盖了不同的难度和类型,从文本冒险到简单的图形界面游戏。这些游戏将使用不同的库,比如pygame用于图形界面游戏,而纯文本游戏则不需要额外的库。


    案例1: 猜数字游戏

    这是一个简单的文本冒险游戏,玩家需要在一定次数内猜出计算机生成的随机数。

    代码示例:

    import random
     
    def guess_number():
        number_to_guess = random.randint(1, 100)
        attempts = 0
        print("猜一个1到100之间的数字。")
     
        while True:
            guess = int(input("你的猜测: "))
            attempts += 1
     
            if guess < number_to_guess:
                print("太小了!")
            elif guess > number_to_guess:
                print("太大了!")
            else:
                print(f"恭喜你,猜对了!你一共用了{attempts}次。")
                break
     
    if __name__ == "__main__":
        guess_number()
    

    案例2: 石头剪刀布游戏

    这是一个玩家与计算机对战的石头剪刀布游戏。

    代码示例:

    import random
     
    def rock_paper_scissors():
        choices = ['石头', '剪刀', '布']
        computer_choice = random.choice(choices)
        player_choice = input("请输入你的选择(石头、剪刀、布): ")
     
        if player_choice not in choices:
            print("无效输入,请重新运行游戏。")
        else:
            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("你输了!")
            print(f"计算机的选择是: {computer_choice}")
     
    if __name__ == "__main__":
        rock_paper_scissors()
    

    案例3: 使用pygame的简单打砖块游戏

    这个案例需要安装pygame库,可以使用pip install pygame进行安装。

    代码示例:

    import pygame
    import sys
     
    pygame.init()
     
    screen_width = 800
    screen_height = 600
    ball_radius = 10
    paddle_width = 75
    paddle_height = 10
    paddle_speed = 5
    ball_speed_x = 7
    ball_speed_y = 7
     
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("打砖块游戏")
     
    white = (255, 255, 255)
    black = (0, 0, 0)
     
    ball_x = screen_width // 2
    ball_y = screen_height - 30
    paddle_x = (screen_width - paddle_width) // 2
     
    bricks = []
    for c in range(8):
        brick_height = 50 - c * 7  # 50 is the height of the first row of bricks
        for r in range(10):
            bricks.append(pygame.Rect(r * (screen_width // 10), 30 + c * 7, screen_width // 10 - 5, brick_height))
     
    def draw_bricks(bricks):
        for brick in bricks:
            pygame.draw.rect(screen, black, brick)
     
    running = True
    clock = pygame.time.Clock()
     
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
     
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and paddle_x > 0:
            paddle_x -= paddle_speed
        if keys[pygame.K_RIGHT] and paddle_x < screen_width - paddle_width:
            paddle_x += paddle_speed
     
        ball_x += ball_speed_x
        ball_y += ball_speed_y
     
        if ball_x - ball_radius < 0 or ball_x + ball_radius > screen_width:
            ball_speed_x = -ball_speed_x
     
        if ball_y - ball_radius < 0:
            ball_speed_y = -ball_speed_y
     
        if ball_y + ball_radius > screen_height:
            running = False
     
        paddle_rect = pygame.Rect(paddle_x, screen_height - paddle_height, paddle_width, paddle_height)
        if paddle_rect.collidepoint(ball_x, ball_y):
            ball_speed_y = -ball_speed_y
     
        screen.fill(white)
        pygame.draw.ellipse(screen, black, (ball_x - ball_radius, ball_y - ball_radius, ball_radius * 2, ball_radius * 2))
        pygame.draw.rect(screen, black, paddle_rect)
        draw_bricks(bricks)
     
        for brick in bricks[:]:
            if brick.collidepoint(ball_x, ball_y):
                bricks.remove(brick)
                ball_speed_y = -ball_speed_y
                break
     
        pygame.display.flip()
        clock.tick(60)
     
    pygame.quit()
    sys.exit()
    

    案例4: 井字棋(Tic-Tac-Toe)

    这是一个文本模式的井字棋游戏,玩家与计算机对战。

    代码示例:

    def print_board(board):
        for row in board:
            print("|".join(row))
            print("-" * 5)
     
    def check_winner(board, player):
        # 检查行
        for row in board:
            if all([spot == player for spot in row]):
                return True
        # 检查列
        for col in range(3):
            if all([board[row][col] == player for row 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 is_board_full(board):
        return all([spot != " " for row in board for spot in row])
     
    def tic_tac_toe():
        board = [[" " for _ in range(3)] for _ in range(3)]
        current_player = "X"
     
        while True:
            print_board(board)
            row = int(input("输入行 (0, 1, 2): "))
            col = int(input("输入列 (0, 1, 2): "))
     
            if board[row][col] != " ":
                print("这个格子已经被占了,请选择另一个格子。")
                continue
     
            board[row][col] = current_player
     
            if check_winner(board, current_player):
                print_board(board)
                print(f"玩家 {current_player} 赢了!")
                break
     
            if is_board_full(board):
                print_board(board)
                print("平局!")
                break
     
            current_player = "O" if current_player == "X" else "X"
     
    if __name__ == "__main__":
        tic_tac_toe()
    

    案例5: 贪吃蛇游戏(使用pygame)

    这个案例也需要pygame库。

    代码示例:

    import pygame
    import sys
    import random
     
    pygame.init()
     
    screen_width = 640
    screen_height = 480
    cell_size = 20
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("贪吃蛇游戏")
     
    clock = pygame.time.Clock()
     
    white = (255, 255, 255)
    green = (0, 255, 0)
    red = (255, 0, 0)
     
    snake_block = 10
    snake_speed = 15
     
    font_style = pygame.font.SysFont(None, 35)
     
    def message(msg, color):
        mesg = font_style.render(msg, True, color)
        screen.blit(mesg, [screen_width / 6, screen_height / 3])
     
    def gameLoop():
        game_over = False
        game_close = False
     
        x1 = screen_
    

    作者:小北画画

    物联沃分享整理
    物联沃-IOTWORD物联网 » 【Python游戏】五大经典小游戏完整代码分享

    发表回复