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

如何创建exe文件列表并随机选取元素以实现游戏随机启动?

Got it, let's break down how to build this game randomizer tool—super fun project! Here's a step-by-step guide covering both maintaining your EXE list and picking one at random to launch:

1. 维护游戏EXE列表的实现方法

There are a few straightforward ways to store and manage your game paths, depending on how simple or feature-rich you want the tool to be:

方法一:纯文本文件(最简单,适合快速原型)

  • Use a plain .txt file where each line holds the full path to a game EXE. For example:
    C:\Games\Steam\steamapps\common\Portal 2\Portal2.exe
    D:\Games\GTA5\GTAV.exe
    C:\Program Files (x86)\Origin Games\Battlefield 4\bf4.exe
    
  • To maintain it, you can either edit the file manually or add a simple "add/remove" function in your program that appends/deletes lines from the text file.
  • Reading the list is as easy as loading all non-empty lines from the file.

方法二:JSON配置文件(更灵活,适合扩展)

  • If you want to store extra info like game names, icons, or categories, JSON is perfect for structured data:
    {
      "games": [
        {
          "name": "Portal 2",
          "path": "C:\\Games\\Steam\\steamapps\\common\\Portal 2\\Portal2.exe",
          "icon": "C:\\Games\\Steam\\steamapps\\common\\Portal 2\\portal2.ico"
        },
        {
          "name": "GTA 5",
          "path": "D:\\Games\\GTA5\\GTAV.exe",
          "icon": "D:\\Games\\GTA5\\GTAV.ico"
        }
      ]
    }
    
  • Your program can parse this JSON to pull out just the EXE paths when needed, or use the extra data to build a nicer UI later.

方法三:轻量数据库(适合 large game libraries)

  • If you have hundreds of games and want features like search, filtering, or tagging, use SQLite. Create a games table with columns like id, name, exe_path, category, and last_played.
  • This adds a bit more complexity but makes managing large collections way easier.
2. 随机选取并启动游戏的核心逻辑

Here are examples in two popular languages—pick whichever you're more comfortable with:

示例1:Python实现(quick & easy)

Python's built-in libraries make this a breeze:

import random
import subprocess

def load_game_list(file_path):
    # Load paths from text file, skip empty lines
    with open(file_path, 'r', encoding='utf-8') as f:
        return [line.strip() for line in f if line.strip()]

def random_launch(game_list):
    if not game_list:
        print("No games in your list! Add some first.")
        return
    
    # Pick a random EXE path
    selected_game = random.choice(game_list)
    print(f"Launching: {selected_game}")
    
    # Start the game
    try:
        subprocess.Popen(selected_game)
    except Exception as e:
        print(f"Oops, failed to launch: {str(e)}")

# Run the tool
if __name__ == "__main__":
    games = load_game_list("games.txt")
    random_launch(games)
  • Key notes:
    • random.choice() handles the random selection in one line
    • subprocess.Popen() safely launches the EXE, even if the path has spaces
    • Added error handling to catch invalid paths or launch failures

示例2:C#实现(Windows desktop-friendly)

If you want a native Windows app, C# is a great choice:

using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;

class GameRandomizer
{
    static List<string> LoadGameList(string filePath)
    {
        List<string> validPaths = new List<string>();
        if (File.Exists(filePath))
        {
            foreach (string line in File.ReadAllLines(filePath))
            {
                string path = line.Trim();
                // Only add paths that actually exist
                if (!string.IsNullOrEmpty(path) && File.Exists(path))
                {
                    validPaths.Add(path);
                }
            }
        }
        return validPaths;
    }

    static void LaunchRandomGame(List<string> gameList)
    {
        if (gameList.Count == 0)
        {
            Console.WriteLine("No valid game paths found!");
            return;
        }

        Random rng = new Random();
        string selectedExe = gameList[rng.Next(gameList.Count)];
        Console.WriteLine($"Launching: {selectedExe}");

        try
        {
            Process.Start(selectedExe);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error launching game: {ex.Message}");
        }
    }

    static void Main(string[] args)
    {
        List<string> games = LoadGameList("games.txt");
        LaunchRandomGame(games);
    }
}
  • Key notes:
    • Random.Next() generates a random index to pick from the list
    • Process.Start() is the Windows-native way to launch executables
    • We validate paths while loading to avoid trying to launch non-existent files
3. Quick Optimization Tips
  • Add a GUI: Use Python's Tkinter/Qt or C# WinForms/WPF to let users add/remove games with a click instead of editing text files.
  • Auto-scan for games: Write a function to crawl Steam/Origin/Epic Games folders and auto-add valid EXE paths to your list.
  • Avoid repeats: Track recently launched games and exclude them from the random selection for a set period.
  • Category filtering: Let users tag games (e.g., "RPG", "FPS") and randomize within a specific category.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:22:48