You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Blackjack游戏自定义Clear函数无法彻底清屏求助(PyCharm)

解决PyCharm中Python控制台彻底清屏的问题

我是自学Python12天的新手,正在用PyCharm开发BlackJack游戏,现在遇到的问题是没法实现像Replit那样彻底清除控制台的效果。我自己写了个clear函数,靠打印100个换行模拟清屏,但效果不好,想找正确的清屏方法,游戏代码如下:

import random
import ascii
print(ascii.logo)


# 为了简化,A记为11,所有面值10的牌统一记为10
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

# 发玩家初始牌
mycards = [random.choice(cards), random.choice(cards)]
print(f"Your cards are: {mycards} current score:{sum(mycards)}")

# 发庄家初始牌,仅展示第一张
dealers_1st_card = random.choice(cards)
computercards = []
computercards.append(dealers_1st_card)
computercards.append(random.choice(cards))
print(f"Dealer's first card is: {dealers_1st_card}")

# 定义辅助函数简化流程
def clear():
    """ 用换行模拟清屏的临时方案"""
    print(100 * "\n")
def draw():
    if sum(mycards) == sum(computercards):
        print(computercards)
        print("It's a draw!")

def ace_check(mycards, computercards):
    # 玩家A的数值转换:超过21时11转1
    for i in range(len(mycards)):
        if mycards[i] == 11 and sum(mycards) > 21:
            mycards[i] = 1
    # 庄家A的数值转换
    for i in range(len(computercards)):
        if computercards[i] == 11 and sum(computercards) > 21:
            computercards[i] = 1


def stand():
    # 庄家补牌规则:总分≤16继续补牌
    while sum(computercards) <= 16:
       computercards.append(random.choice(cards))
    ace_check(mycards, computercards)
    # 再次检查补牌
    while sum(computercards) <= 16:
       computercards.append(random.choice(cards))
    print(f"Dealer's cards are: {computercards} current score: {sum(computercards)}")
    # 判断胜负
    if sum(computercards) > sum(mycards) and sum(computercards) <= 21:
        print("You Lose.")
    elif sum(computercards) < sum(mycards) and sum(mycards) <= 21:
        print("You Win.")
    elif sum(computercards) > 21:
        print("You Win.")
    elif sum(mycards) > 21:
        print("You Lose.")
    else:
        draw()


def hit():
    # 玩家补牌
    mycards.append(random.choice(cards))
    ace_check(mycards, computercards)
    print(f"Your cards are {mycards} current score: {sum(mycards)}")
    # 判断补牌后状态
    if sum(mycards) > 21:
        print("You lose")
        print(f"Dealer's cards: {computercards} current score: {sum(computercards)}")
    elif sum(mycards) == 21:
        print(f"Dealer's cards are {computercards} current score: {sum(computercards)}")
        if sum(mycards) > sum(computercards):
            print("You win!")
        else:
            draw()
    elif sum(mycards) <= 21:
        hit_or_stand = input("Type 'y' to get another card, type 'n' to pass: ")
        if hit_or_stand == "y":
            hit()
        elif hit_or_stand == "n":
            stand()
    else:
        draw()

def myblackjack(mycards, computercards):
    # 检查玩家是否拿到黑杰克
    if 10 in mycards and 11 in mycards:
        print(computercards)
        print("BLACKJACK\nYOU WON!")
    else:
        hit_or_stand = input("Type 'y' to get another card, type 'n' to pass: ")
        if hit_or_stand == "y":
            hit()
        elif hit_or_stand == "n":
            stand()


# 启动游戏
myblackjack(mycards, computercards)


# 多轮游戏循环
while True:
    keep_playing = input("Do you want to play another game of BlackJack? Type 'y' if that's so, otherwise type 'n'. ")
    if keep_playing == "y":
        clear()
        print(ascii.logo)
        mycards.clear()
        computercards.clear()
        cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

        # 重新发玩家初始牌
        mycards = [random.choice(cards), random.choice(cards)]
        print(f"Your cards are: {mycards} current score:{sum(mycards)}")

        # 重新发庄家初始牌
        dealers_1st_card = random.choice(cards)
        computercards = []
        computercards.append(dealers_1st_card)
        computercards.append(random.choice(cards))
        print(f"Dealer's first card is: {dealers_1st_card}")
        myblackjack(mycards, computercards)
    else:
        break

跨平台彻底清屏方案

要实现和Replit一致的彻底清屏效果,需调用系统原生清屏命令,替换原有的换行模拟方案:

  1. 导入os模块,重写clear函数:
import os

def clear():
    # Windows系统执行cls命令
    if os.name == 'nt':
        os.system('cls')
    # Linux/macOS系统执行clear命令
    else:
        os.system('clear')

关键说明

  • os.name会返回当前系统标识:Windows为nt,类Unix系统(Linux/macOS)为posix
  • os.system()直接调用终端原生命令,能完全清空控制台内容,解决换行模拟的无效问题

额外注意

  • PyCharm的Run输出面板不支持cls/clear命令的清屏效果,需切换到底部的Terminal标签页运行脚本
  • 若部分终端兼容性有问题,可补充ANSI转义序列增强效果:
def clear():
    os.system('cls' if os.name == 'nt' else 'clear')
    # ANSI转义序列,强制光标回到屏幕顶部并清空内容
    print("\033[H\033[J")

内容的提问来源于stack exchange,提问作者SSebu22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:12:04