课程:《Python 程序设计》
班级: 1921
姓名: 胡光鑫
学号: 20192101
实验教师:王志强
实验日期:2020年6月14日
必修/选修: 公选课
1. 实验内容
Python综合应用:爬虫、数据处理、可视化、机器学习、神经网络、游戏、网络安全等
本次实验利用pygame编写简单的弹珠游戏
2.实验代码
import pygame
import sys
pygame.init()
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
color = (255, 255, 255)
ball = pygame.image.load('ball.png')
ballrect = ball.get_rect()
line = pygame.image.load('line.png')
linerect = line.get_rect()
speed = [5, 5]
speed2 = [20,0]
speed3 = [-20,0]
speed4 = [0,20]
speed5 = [0,-20]
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
linerect = linerect.move(speed3)
elif event.key == pygame.K_RIGHT:
linerect = linerect.move(speed2)
elif event.key == pygame.K_UP:
linerect = linerect.move(speed5)
elif event.key == pygame.K_DOWN:
linerect = linerect.move(speed4)
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.left < linerect.right and ballrect.left > linerect.right+25 or ballrect.right > linerect.left and ballrect.right < linerect.left+25:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
if ballrect.top < linerect.bottom and ballrect.top > linerect.bottom+25 or ballrect.bottom > linerect.top and ballrect.top <linerect.bottom+25 :
speed[1] = -speed[1]
screen.fill(color)
screen.blit(ball, ballrect)
screen.blit(line, linerect)
pygame.display.flip()
pygame.quit()
3.实验感想
通过此次试验,让我对游戏的编程有了进一步的了解。