2025年5月7日 星期三

左右移動方塊+跳跳球

 import pygame

import sys

import random


pygame.init()


# 畫面設定

WIDTH, HEIGHT = 800, 600

WHITE = (255, 255, 255)

RED = (255, 0, 0)

BLUE = (0, 100, 255)


screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("球四向反彈")


# 玩家方塊

player_width = 100

player_height = 20

player_x = WIDTH // 2 - player_width // 2

player_y = HEIGHT - 75

player_speed = 8


# 球

ball_radius = 20

ball_x = random.randint(ball_radius, WIDTH - ball_radius)

ball_y = 100

ball_x_speed = 4   # 新增:水平速度

ball_y_speed = 5   # 垂直速度


# 分數

score = 0

font = pygame.font.SysFont(None, 36)


clock = pygame.time.Clock()

running = True

while running:

    clock.tick(60)


    # 處理事件

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False


    # 玩家左右移動

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:

        player_x -= player_speed

    if keys[pygame.K_RIGHT]:

        player_x += player_speed

    player_x = max(0, min(WIDTH - player_width, player_x))


    # 球移動(新增水平速度)

    ball_x += ball_x_speed

    ball_y += ball_y_speed


    # 撞到左右邊界反彈

    if ball_x - ball_radius <= 0 or ball_x + ball_radius >= WIDTH:

        ball_x_speed = -ball_x_speed


    # 撞到方塊反彈(僅從上方)

    if (

        player_y <= ball_y + ball_radius <= player_y + player_height

        and player_x <= ball_x <= player_x + player_width

        and ball_y_speed > 0

    ):

        ball_y_speed = -ball_y_speed

        score += 1


    # 撞到頂部反彈

    if ball_y - ball_radius <= 0:

        ball_y_speed = -ball_y_speed


    # 掉出畫面底部(沒接到):重置球與分數

    if ball_y > HEIGHT:

        ball_x = random.randint(ball_radius, WIDTH - ball_radius)

        ball_y = 100

        ball_x_speed = random.choice([-4, 4])  # 重新設定方向

        ball_y_speed = 5

        score = 0


    # 畫圖

    screen.fill(WHITE)

    pygame.draw.rect(screen, RED, (player_x, player_y, player_width, player_height))

    pygame.draw.circle(screen, BLUE, (int(ball_x), int(ball_y)), ball_radius)

    score_text = font.render(f"Score: {score}", True, (0, 0, 0))

    screen.blit(score_text, (10, 10))

    pygame.display.flip()


pygame.quit()

sys.exit()

左右移動方塊

 import pygame

import sys


# 初始化

pygame.init()


# 視窗大小與顏色

WIDTH, HEIGHT = 800, 600

WHITE = (255, 255, 255)

RED = (255, 0, 0)


# 視窗

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("左右移動方塊")


# 方塊設定

player_size = 50

player_x = WIDTH // 2

player_y = HEIGHT - 75  # 固定在底部上方約 2 公分

player_speed = 5


# 遊戲主迴圈

clock = pygame.time.Clock()

running = True

while running:

    clock.tick(60)


    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False


    # 左右移動控制

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:

        player_x -= player_speed

    if keys[pygame.K_RIGHT]:

        player_x += player_speed


    # 邊界限制(只限 x)

    player_x = max(0, min(WIDTH - player_size, player_x))


    # 畫面更新

    screen.fill(WHITE)

    pygame.draw.rect(screen, RED, (player_x, player_y, player_size, player_size))

    pygame.display.flip()


pygame.quit()

sys.exit()

2025年5月6日 星期二

777 拉霸機




 import tkinter as tk

import random


def play_once():

    global curmoney

    if curmoney < 30:

        result_label.config(text='金額不足,請結束遊戲!')

        return


    # 清除舊的元件(除了按鈕)

    for widget in frame.winfo_children():

        if widget not in (btn_play, btn_play10, btn_play100):

            widget.destroy()


    # 隨機產生三個數字

    ns = [random.randint(0, 9) for _ in range(3)]


    # 顯示數字

    colors = ['#f90', '#09c', '#fc0']

    for i, n in enumerate(ns):

        label = tk.Label(frame, text=n, bg=colors[i], font=('Arial', 100, 'bold'))

        label.grid(column=i, row=0)


    # 判斷中幾個 7

    c7 = ns.count(7)

    money = [0, 50, 500, 5000][c7]


    # 更新金額

    curmoney = curmoney - 30 + money


    # 顯示說明文字

    tk.Label(frame, text='多少個7: ' + str(c7), background='#ccc').grid(column=0, row=1, columnspan=3)

    tk.Label(frame, text='獎金:' + str(money), background='#ccc').grid(column=0, row=2, columnspan=3)

    tk.Label(frame, text='可用金額:'+str(curmoney), font=('Arial', 20)).grid(column=0, row=3, columnspan=3)


def play_10_times(i=0):

    if i < 10 and curmoney >= 30:

        play_once()

        frame.after(10, play_10_times, i+1)

    elif curmoney < 30:

        result_label.config(text='金額不足,中止連續遊戲')


def play_100_times(i=0):

    if i < 100 and curmoney >= 30:

        play_once()

        frame.after(100, play_100_times, i+1)

    elif curmoney < 30:

        result_label.config(text='金額不足,中止連續遊戲')


def create_ui():

    global frame, btn_play, btn_play10, btn_play100, result_label


    root = tk.Tk()

    root.title('777 拉霸機')

    root.geometry('360x480')


    frame = tk.Frame(root)

    frame.pack(pady=20)


    # 單次遊戲按鈕

    btn_play = tk.Button(frame, text='PLAY', font=('Arial', 20, 'bold'), command=play_once)

    btn_play.grid(column=1, row=8)


    # 連續 10 次按鈕

    btn_play10 = tk.Button(frame, text='PLAY10', font=('Arial', 20, 'bold'), command=play_10_times)

    btn_play10.grid(column=1, row=9)


    # 連續 100 次按鈕

    btn_play100 = tk.Button(frame, text='PLAY100', font=('Arial', 20, 'bold'), command=play_100_times)

    btn_play100.grid(column=1, row=10)


    # 提示文字

    result_label = tk.Label(frame, text='', font=('Arial', 14))

    result_label.grid(column=0, row=11, columnspan=3)


    root.mainloop()


curmoney = 1000

create_ui()

2025年5月2日 星期五

dictionary sample

 student_score = { "Chaoyen":[80, 87, 67],

                  "Joanne":[76, 80, 95],

                  "Manchster":[85, 70, 90],

}


math_sum = 0   


for k,v in student_score.items():

  # print(k,v)

  math_sum+=v[2]

print(math_sum/len(student_score))

dictionary sample

 def getGrade(score):

  if score>=90:

    return 'A'

  elif score>=80:

    return 'B'

  elif score>=70:

    return 'C'

  elif score>=60:

    return 'D'

  else:

    return 'E'


students = [

    {'name': '小明', 'score': 85},

    {'name': '小朱', 'score': 62},

    {'name': '小華', 'score': 92},

    {'name': '小美', 'score': 67},

    {'name': '小王', 'score': 73},

    {'name': '小沈', 'score': 63},

    {'name': '阿杰', 'score': 58},

]

grades = {'A':[],'B':[],'C':[],'D':[],'E':[],'F':[]}


for student in students:

  grades[getGrade(student['score'])].append([student['name'],student['score']])

  

for k,v in grades.items():

  print(k,v)


# Output:


# A [['小華', 92]]

# B [['小明', 85]]

# C [['小王', 73]]

# D [['小朱', 62], ['小美', 67], ['小沈', 63]]

# E [['阿杰', 58]]

# F []

itertools compress sample

 import itertools

a = 'tomorrow'

b =map(int, list('11001011'))

c = itertools.compress(a, b)

print(''.join(c))   # torow

pytho dict sample

 data = [

    ('水果', '蘋果'),

    ('飲料', '可樂'),

    ('水果', '香蕉'),

    ('飲料', '茶'),

    ('水果', '芒果'),

]


fruits = set([i[0] for i in data])

# print(fruits)


f = dict()

for fruit in fruits:

  t = [ i[1] for i in data if i[0]==fruit]

  f[fruit] = t

for k,v in f.items():

  print(k,v)