ballGame
2018-07-30 本文已影响88人
GHope
-- coding: utf-8 --
@Time : 2018/7/30 15:39
@Author : G.Hope
@Email : 1638327522@qq.com
@File : ballGame.py
@Software: PyCharm
通过键盘方向键控制小球移动方向,使其不触碰到程序窗口边界。否则认为游戏失败,程序自动退出。
import pygame
def draw_ball(place, color, pos):
pygame.draw.circle(place, color, pos, 20)
# 方向对应的key值
Up = 273
Down = 274
Left = 276
Right = 275
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill((255, 255, 255))
pygame.display.flip()
# 保存初始坐标
ball_x = 400
ball_y = 300
x_speed = 1
y_speed = 1
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == Up:
x_speed = 0
y_speed = -1
elif event.key == Down:
x_speed = 0
y_speed = 1
elif event.key == Right:
x_speed = 1
y_speed = 0
elif event.key == Left:
x_speed = -1
y_speed = 0
# 刷新屏幕
pygame.time.delay(10)
screen.fill((255, 255, 255))
ball_x += x_speed
ball_y += y_speed
if ball_x + 20 >= 800 or ball_x <= 20 or ball_y + 20 >= 600 or ball_y <= 20:
print('游戏结束')
exit()
# ball_x = 600 - 20
# x_speed *= -1
# if ball_x <0:
# ball_x = 0
# x_speed *= -1
draw_ball(screen, (255, 0, 0), (ball_x, ball_y))
pygame.display.update()