ต้องการสร้างเกมง่ายๆ สำหรับการเรียนรู้การพิมพ์ด้วยแป้นคีย์บอร์ดและการใช้เมาส์ เลยให้ AI Google Gemini สร้างให้
เกมแรก ฝึกการพิมพ์แป้นคีย์บอร์ด

หลังจากนั้น Google Gemini ก็เขียนโค้ดออกมา
โดยมีการขอให้ปรับปรุงแก้ไข 2-3 ครั้ง แก้ไขเปลี่ยนภาษาในเกมจากไทยเป็นอังกฤษ แก้ไขให้เปิดเกมแล้วแสดงเต็มหน้าจอทันที่ เมื่อจบเกมแล้วให้มี end screen แสดงข้อมูล



ผลลัพธ์ : typing_game.py
import tkinter as tk
import random
import time
# --- Global Variables ---
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
current_char = ""
last_displayed_char = ""
score = 0
time_left = 30
game_running = False
# --- Functions ---
def update_timer():
"""Update the countdown timer every 1 second"""
global time_left, game_running
if game_running:
if time_left > 0:
time_left -= 1
timer_label.config(text=f"Time: {time_left} seconds")
window.after(1000, update_timer)
else:
game_running = False
end_game()
def generate_new_char():
"""Generate a new random character and display it, ensuring it's not the same as the last one"""
global current_char, last_displayed_char
if game_running:
new_char = random.choice(alphabet)
# Ensure the new character is different from the last one
while new_char == last_displayed_char:
new_char = random.choice(alphabet)
current_char = new_char
last_displayed_char = new_char # Update the last displayed character
char_label.config(text=current_char, fg="blue")
feedback_label.config(text="") # Clear feedback message
def check_key_press(event):
"""Check the pressed key"""
global score
if game_running: # Check if the game is running
pressed_key = event.char.upper()
if pressed_key == current_char:
feedback_label.config(text="Correct! Excellent!", fg="green")
score += 1
score_label.config(text=f"Score: {score}")
window.after(300, generate_new_char) # Short delay before new character
elif pressed_key.isalpha(): # Only show feedback for alphabet keys
feedback_label.config(text=f"Try again! You pressed '{pressed_key}'", fg="red")
def start_game():
"""Start the game"""
global score, time_left, game_running, last_displayed_char
score = 0
time_left = 30
game_running = True
last_displayed_char = "" # Reset this variable for a new game
score_label.config(text=f"Score: {score}")
timer_label.config(text=f"Time: {time_left} seconds")
result_label.config(text="") # Clear previous result
start_button.pack_forget() # Hide the Start button
generate_new_char() # Generate the first character
update_timer() # Start the timer
def end_game():
"""End the game and display the final score"""
char_label.config(text="Game Over!", fg="purple")
feedback_label.config(text="")
timer_label.config(text="Time: 0 seconds")
result_label.config(text=f"You scored {score} points! Great job!", font=("Arial", 28, "bold"), fg="darkgreen")
# Show the Start/Play Again button
start_button.config(text="Play Again")
start_button.pack(pady=20)
# --- Create Game Window ---
window = tk.Tk()
window.title("A-Z Typing Practice Game") # Changed title
# Maximize window immediately
window.state('zoomed')
# Alternative for true fullscreen (hides title bar):
# window.attributes('-fullscreen', True)
# If using fullscreen, add an escape key binding to exit:
# window.bind("<Escape>", lambda event: window.attributes("-fullscreen", False))
# Label for displaying the character
char_label = tk.Label(window, text="Ready to Play?", font=("Arial", 100, "bold")) # Changed text
char_label.pack(pady=30)
# Label for displaying feedback
feedback_label = tk.Label(window, text="", font=("Arial", 20))
feedback_label.pack()
# Label for displaying time
timer_label = tk.Label(window, text=f"Time: {time_left} seconds", font=("Arial", 22)) # Changed text
timer_label.pack(pady=10)
# Label for displaying score
score_label = tk.Label(window, text=f"Score: {score}", font=("Arial", 22)) # Changed text
score_label.pack(pady=10)
# Label for displaying final results
result_label = tk.Label(window, text="", font=("Arial", 28, "bold"))
result_label.pack(pady=20)
# Start Game Button
start_button = tk.Button(window, text="Start Game", command=start_game, font=("Arial", 24), bg="lightgreen", fg="white", activebackground="green") # Changed text
start_button.pack(pady=30)
# Bind key presses to the check_key_press function
window.bind("<Key>", check_key_press)
# Start the GUI event loop
window.mainloop()
เกมที่สอง ฝึกการใช้เมาส์

มีแก้ไขเล็กน้อยจากโค้ดที่ได้ชุดแรก
ติดตั้งส่วนเสริมของ Python สำหรับใช้สร้างเกม
pip install pygameผลลัพธ์ : target_clicker.py
import pygame
import random
import sys
# --- Game Initialization Settings ---
pygame.init()
# Use these flags to create a fullscreen window
# Pygame will automatically detect the screen's resolution when using (0, 0)
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
# Get the actual screen dimensions after setting fullscreen mode
SCREEN_WIDTH, SCREEN_HEIGHT = screen.get_size()
pygame.display.set_caption("Target Clicker!")
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
# Fonts
font_large = pygame.font.Font(None, 74)
font_medium = pygame.font.Font(None, 50)
font_small = pygame.font.Font(None, 36)
# Sound (Optional)
click_sound = None # pygame.mixer.Sound("click.wav")
# --- Game Variables ---
target_radius = 30
target_x = 0
target_y = 0
score = 0
game_timer = 30 # seconds
start_time = 0
start_button_rect = None
end_button_rect = None
final_score_display = 0 # To store the score when game ends
# Function to spawn a new target randomly
def spawn_new_target():
global target_x, target_y
target_x = random.randint(target_radius, SCREEN_WIDTH - target_radius)
target_y = random.randint(target_radius, SCREEN_HEIGHT - target_radius)
# --- Start Screen / Menu ---
def draw_start_screen():
screen.fill(BLUE)
title_text = font_large.render("Target Clicker!", True, WHITE)
screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, SCREEN_HEIGHT // 4))
instruction_text = font_medium.render("Click the circles as fast as you can!", True, WHITE)
screen.blit(instruction_text, (SCREEN_WIDTH // 2 - instruction_text.get_width() // 2, SCREEN_HEIGHT // 2 - 50))
start_button_text = font_large.render("Start Game", True, BLACK)
start_button_rect_local = start_button_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 100))
pygame.draw.rect(screen, GREEN, start_button_rect_local.inflate(20, 10))
screen.blit(start_button_text, start_button_rect_local)
pygame.display.flip()
return start_button_rect_local
# --- End Game Screen ---
def draw_end_screen(final_score):
screen.fill(BLUE)
game_over_text = font_large.render("Game Over!", True, WHITE)
screen.blit(game_over_text, (SCREEN_WIDTH // 2 - game_over_text.get_width() // 2, SCREEN_HEIGHT // 4))
score_text = font_medium.render(f"You clicked: {final_score} times!", True, WHITE)
screen.blit(score_text, (SCREEN_WIDTH // 2 - score_text.get_width() // 2, SCREEN_HEIGHT // 2 - 50))
play_again_button_text = font_large.render("Play Again", True, BLACK)
play_again_button_rect_local = play_again_button_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 100))
pygame.draw.rect(screen, GREEN, play_again_button_rect_local.inflate(20, 10))
screen.blit(play_again_button_text, play_again_button_rect_local)
pygame.display.flip()
return play_again_button_rect_local
# --- Main Game Loop ---
running = True
clock = pygame.time.Clock()
state = "start_screen" # "start_screen", "playing", "end_screen"
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = event.pos
if state == "playing":
distance = ((mouse_x - target_x)**2 + (mouse_y - target_y)**2)**0.5
if distance < target_radius:
score += 1
spawn_new_target()
if click_sound:
click_sound.play()
elif state == "start_screen":
if start_button_rect and start_button_rect.collidepoint(mouse_x, mouse_y):
state = "playing"
score = 0
start_time = pygame.time.get_ticks()
spawn_new_target()
start_button_rect = None
end_button_rect = None
elif state == "end_screen":
# Only check for clicks on the "Play Again" button when in end_screen state
if end_button_rect and end_button_rect.collidepoint(mouse_x, mouse_y):
state = "start_screen"
score = 0
start_time = 0
spawn_new_target()
start_button_rect = None # Ensure start screen is drawn and button is set
end_button_rect = None # Reset end button rect
# --- Update and Draw Screen based on Game State ---
if state == "start_screen":
start_button_rect = draw_start_screen()
end_button_rect = None
elif state == "playing":
elapsed_time = (pygame.time.get_ticks() - start_time) / 1000
remaining_time = max(0, game_timer - int(elapsed_time))
if remaining_time == 0:
state = "end_screen"
final_score_display = score
# No need to call draw_end_screen here, it will be called in the next frame
# under the elif state == "end_screen" block.
start_button_rect = None # Hide start game button
# Draw game screen elements ONLY when playing
screen.fill(BLACK)
pygame.draw.circle(screen, RED, (target_x, target_y), target_radius)
score_text = font_medium.render(f"Score: {score}", True, WHITE)
time_text = font_medium.render(f"Time: {remaining_time}", True, WHITE)
screen.blit(score_text, (10, 10))
screen.blit(time_text, (SCREEN_WIDTH - time_text.get_width() - 10, 10))
pygame.display.flip()
elif state == "end_screen":
# Draw the end game screen ONLY when in end_screen state
end_button_rect = draw_end_screen(final_score_display) # Must assign to end_button_rect
clock.tick(60)
pygame.quit()
sys.exit()
วิธีนำเกม Python ไปใช้งาน
คัดลอกโค้ดแต่ละเกม ไปวางในโปรแกรม Text Editor เช่น Windows Notepad หรือ Notepad++ แล้วบันทึก save เป็นไฟล์ นามสกุล .py
แล้วคลิกเปิดไฟล์เพื่อเล่นเกมได้เลย

ทั้งนี้ หากยังไม่เคยติดตั้งโปรแกรม Python มาก่อน ให้ดาวน์โหลดจาก Microsoft store
เมื่อดาวน์โหลดโปรแกรม Python เรียบร้อย ก็คลิกเปิดไฟล์เกมได้เลย

- Log in to post comments