Files
PyGameZero/main.py
2026-06-23 15:38:36 +08:00

105 lines
2.5 KiB
Python

import pgzrun
import random
WIDTH = 800
HEIGHT = 600
background = Actor('grass')
player = Actor('p3_front')
player.x = 400
player.y = 300
coin = Actor('coingold')
coin.x = random.randint(50, WIDTH - 50)
coin.y = random.randint(50, HEIGHT - 50)
trees = []
tree_count = 2
for _ in range(tree_count):
new_tree = Actor('tree')
new_tree.x = random.randint(80, WIDTH - 80)
new_tree.y = random.randint(80, HEIGHT - 80)
while new_tree.colliderect(player):
new_tree.x = random.randint(80, WIDTH - 80)
new_tree.y = random.randint(80, HEIGHT - 80)
trees.append(new_tree)
score = 0
timer = 35
def check_tree_collision(new_x, new_y):
temp_player = Actor('p3_front', pos=(new_x, new_y))
for tree in trees:
if temp_player.colliderect(tree):
return False
return True
def update():
global score
global timer
if timer <= 0:
return
timer -= 1 / 60
move_speed = 5
if keyboard.up:
new_y = player.y - move_speed
if check_tree_collision(player.x, new_y):
player.y = new_y
if keyboard.down:
new_y = player.y + move_speed
if check_tree_collision(player.x, new_y):
player.y = new_y
if keyboard.left:
new_x = player.x - move_speed
if check_tree_collision(new_x, player.y):
player.x = new_x
if keyboard.right:
new_x = player.x + move_speed
if check_tree_collision(new_x, player.y):
player.x = new_x
if player.colliderect(coin):
while True:
coin.x = random.randint(50, WIDTH - 50)
coin.y = random.randint(50, HEIGHT - 50)
overlap_tree = False
for t in trees:
if coin.colliderect(t):
overlap_tree = True
break
if not overlap_tree:
break
score += 1
sounds.sfx_coin_single1.play()
def draw():
if timer <= 0:
screen.fill((30, 30, 30))
screen.draw.text('Game Over', (330, 270), color=(255,255,255), fontsize=36)
screen.draw.text('Final Score: ' + str(score), (330, 330), color=(255,255,255), fontsize=30)
else:
background.draw()
for tree in trees:
tree.draw()
player.draw()
coin.draw()
screen.draw.text('Score: ' + str(score), (15,10), color=(255,255,255), fontsize=30)
screen.draw.text('Time: ' + str(round(timer, 2)), (330,10), color=(255,255,255), fontsize=30)
pgzrun.go() # Must be last line