在上篇捡金币游戏的基础上,加上了开始选择和分数统计,结束功能。
gui.py
import arcade
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
def draw_button(content,center_x,center_y,font_size=20):
arcade.draw_rectangle_filled(
center_x,
center_y,
100,
50,
arcade.color.WHITE,
)
arcade.draw_text(content,
center_x,
center_y,
arcade.color.BLACK,
font_size,
anchor_x="center",
anchor_y="center",
font_name=('arial',)
)
main.py
import arcade
import random
from gui import draw_button
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Starting Template"
# 玩家
class Player(arcade.Sprite):
def __init__(self,image):
super().__init__(image)
self.center_x = SCREEN_WIDTH//2
self.center_y = self.height//2
def move(self,direction):
# 左移
if direction == "left" and self.center_x >0:
self.center_x = self.center_x - 20
# 右移
elif direction == "right" and self.center_x < SCREEN_WIDTH:
self.center_x = self.center_x + 20
# 金币
class Coin(arcade.Sprite):
def __init__(self,image):
super().__init__(image)
self.center_x = SCREEN_WIDTH//2
self.center_y = SCREEN_HEIGHT-self.height//2
# 创建游戏类
class MyGame(arcade.Window):
def __init__(self, width, height, title):
super().__init__(width, height, title)
self.setup()
def setup(self):
arcade.set_background_color(arcade.color.SKY_BLUE)
self.player = Player('robot.png')
self.coins = arcade.SpriteList()
# 程序运行总时间
self.total_time = 0
# 按键控制变量
self.direction = None
self.score = 0
# 是否开始
self.is_start = False
def on_draw(self):
arcade.start_render()
self.player.draw()
if self.coins:
for coin in self.coins:
coin.draw()
arcade.draw_text('score:{}'.format(self.score),
SCREEN_WIDTH-120 , SCREEN_HEIGHT - 30,
arcade.color.RED, 20,
font_name=('arial',)
)
if not self.is_start:
draw_button('开始',SCREEN_WIDTH // 2,SCREEN_HEIGHT-200,20)
draw_button('音乐', SCREEN_WIDTH // 2, SCREEN_HEIGHT - 300, 20)
def on_update(self, delta_time):
if self.is_start:
# 记录程序经过的时间
self.total_time = self.total_time + delta_time
if self.total_time >= 0.5:
c = Coin('gold.png')
x = random.randint(50,750)
c.center_x = x
self.coins.append(c)
self.total_time = 0
for coin in self.coins:
# 金币落下
coin.center_y -= 5
# 判断是否超出底边界
if coin.center_y < 0:
self.coins.remove(coin)
# 与金币列表碰撞检测,返回所有碰到的金币
coin_list = self.player.collides_with_list(self.coins)
# 循环删除所有碰到的金币
for c in coin_list:
self.score = self.score + 1
self.coins.remove(c)
if self.direction =='left':
self.player.move("left")
elif self.direction =='right':
self.player.move("right")
if self.score >=10:
exit()
def on_key_press(self, key, key_modifiers):
if key == arcade.key.A:
self.direction = 'left'
elif key == arcade.key.D:
self.direction = 'right'
def on_key_release(self, key, key_modifiers):
if key == arcade.key.A or key == arcade.key.D:
self.direction = None
def on_mouse_press(self, x, y, button, key_modifiers):
if x>(SCREEN_HEIGHT - 200 - 50) and x<(SCREEN_HEIGHT - 200 + 50) and y>(SCREEN_HEIGHT - 200-25) and y<(SCREEN_HEIGHT - 200+25):
self.is_start = True
if __name__ == '__main__':
# 实例对象
game = MyGame(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_TITLE)
arcade.run()