2024年学编程很枯燥?用Python制作3个小游戏,边玩边学(含源码)

score_left, score_right = runDemo(screen)

endInterface(screen, score_left, score_right)

‘’‘run’‘’

if name == ‘main’:

main()

2、俄罗斯方块


玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的。

源码分享:

import os

import sys

import random

from modules import *

from PyQt5.QtGui import *

from PyQt5.QtCore import *

from PyQt5.QtWidgets import *

‘’‘定义俄罗斯方块游戏类’‘’

class TetrisGame(QMainWindow):

def init(self, parent=None):

super(TetrisGame, self).init(parent)

是否暂停ing

self.is_paused = False

是否开始ing

self.is_started = False

self.initUI()

‘’‘界面初始化’‘’

def initUI(self):

icon

self.setWindowIcon(QIcon(os.path.join(os.getcwd(), ‘resources/icon.jpg’)))

块大小

self.grid_size = 22

游戏帧率

self.fps = 200

self.timer = QBasicTimer()

焦点

self.setFocusPolicy(Qt.StrongFocus)

水平布局

layout_horizontal = QHBoxLayout()

self.inner_board = InnerBoard()

self.external_board = ExternalBoard(self, self.grid_size, self.inner_board)

layout_horizontal.addWidget(self.external_board)

self.side_panel = SidePanel(self, self.grid_size, self.inner_board)

layout_horizontal.addWidget(self.side_panel)

self.status_bar = self.statusBar()

self.external_board.score_signal[str].connect(self.status_bar.showMessage)

self.start()

self.center()

self.setWindowTitle(‘Tetris —— 九歌’)

self.show()

self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())

‘’‘游戏界面移动到屏幕中间’‘’

def center(self):

screen = QDesktopWidget().screenGeometry()

size = self.geometry()

self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)

‘’‘更新界面’‘’

def updateWindow(self):

self.external_board.updateData()

self.side_panel.updateData()

self.update()

‘’‘开始’‘’

def start(self):

if self.is_started:

return

self.is_started = True

self.inner_board.createNewTetris()

self.timer.start(self.fps, self)

‘’‘暂停/不暂停’‘’

def pause(self):

if not self.is_started:

return

self.is_paused = not self.is_paused

if self.is_paused:

self.timer.stop()

self.external_board.score_signal.emit(‘Paused’)

else:

self.timer.start(self.fps, self)

self.updateWindow()

‘’‘计时器事件’‘’

def timerEvent(self, event):

if event.timerId() == self.timer.timerId():

removed_lines = self.inner_board.moveDown()

self.external_board.score += removed_lines

self.updateWindow()

else:

super(TetrisGame, self).timerEvent(event)

‘’‘按键事件’‘’

def keyPressEvent(self, event):

if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty:

super(TetrisGame, self).keyPressEvent(event)

return

key = event.key()

P键暂停

if key == Qt.Key_P:

self.pause()

return

if self.is_paused:

return

向左

elif key == Qt.Key_Left:

self.inner_board.moveLeft()

向右

elif key == Qt.Key_Right:

self.inner_board.moveRight()

旋转

elif key == Qt.Key_Up:

self.inner_board.rotateAnticlockwise()

快速坠落

elif key == Qt.Key_Space:

self.external_board.score += self.inner_board.dropDown()

else:

super(TetrisGame, self).keyPressEvent(event)

self.updateWindow()

‘’‘run’‘’

if name == ‘main’:

app = QApplication([])

tetris = TetrisGame()

sys.exit(app.exec_())

3、滑雪

源码分享:

import sys

import cfg

import pygame

import random

‘’‘滑雪者类’‘’

class SkierClass(pygame.sprite.Sprite):

def init(self):

pygame.sprite.Sprite.init(self)

滑雪者的朝向(-2到2)

self.direction = 0

self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]

self.image = pygame.image.load(self.imagepaths[self.direction])

self.rect = self.image.get_rect()

self.rect.center = [320, 100]

self.speed = [self.direction, 6-abs(self.direction)*2]

‘’‘改变滑雪者的朝向. 负数为向左,正数为向右,0为向前’‘’

def turn(self, num):

self.direction += num

self.direction = max(-2, self.direction)

self.direction = min(2, self.direction)

center = self.rect.center

self.image = pygame.image.load(self.imagepaths[self.direction])

self.rect = self.image.get_rect()

self.rect.center = center

self.speed = [self.direction, 6-abs(self.direction)*2]

return self.speed

‘’‘移动滑雪者’‘’

def move(self):

self.rect.centerx += self.speed[0]

self.rect.centerx = max(20, self.rect.centerx)

self.rect.centerx = min(620, self.rect.centerx)

‘’‘设置为摔倒状态’‘’

def setFall(self):

self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])

‘’‘设置为站立状态’‘’

def setForward(self):

self.direction = 0

self.image = pygame.image.load(self.imagepaths[self.direction])

‘’’

Function:

障碍物类

Input:

img_path: 障碍物图片路径

location: 障碍物位置

attribute: 障碍物类别属性

‘’’

class ObstacleClass(pygame.sprite.Sprite):

def init(self, img_path, location, attribute):

pygame.sprite.Sprite.init(self)

self.img_path = img_path

self.image = pygame.image.load(self.img_path)

self.location = location

self.rect = self.image.get_rect()

self.rect.center = self.location

self.attribute = attribute

self.passed = False

‘’‘移动’‘’

def move(self, num):

self.rect.centery = self.location[1] - num

‘’‘创建障碍物’‘’

def createObstacles(s, e, num=10):

obstacles = pygame.sprite.Group()

locations = []

for i in range(num):

row = random.randint(s, e)

col = random.randint(0, 9)

location = [col64+20, row64+20]

if location not in locations:

locations.append(location)

attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys()))

img_path = cfg.OBSTACLE_PATHS[attribute]

obstacle = ObstacleClass(img_path, location, attribute)

obstacles.add(obstacle)

return obstacles

‘’‘合并障碍物’‘’

def AddObstacles(obstacles0, obstacles1):

obstacles = pygame.sprite.Group()

for obstacle in obstacles0:

obstacles.add(obstacle)

for obstacle in obstacles1:

obstacles.add(obstacle)

return obstacles

‘’‘显示游戏开始界面’‘’

def ShowStartInterface(screen, screensize):

screen.fill((255, 255, 255))

tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)

cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)

title = tfont.render(u’滑雪游戏’, True, (255, 0, 0))

content = cfont.render(u’按任意键开始游戏’, True, (0, 0, 255))

trect = title.get_rect()

trect.midtop = (screensize[0]/2, screensize[1]/5)

crect = content.get_rect()

crect.midtop = (screensize[0]/2, screensize[1]/2)

screen.blit(title, trect)

screen.blit(content, crect)

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit()

sys.exit()

elif event.type == pygame.KEYDOWN:

return

pygame.display.update()

‘’‘显示分数’‘’

def showScore(screen, score, pos=(10, 10)):

font = pygame.font.Font(cfg.FONTPATH, 30)

score_text = font.render(“Score: %s” % score, True, (0, 0, 0))

screen.blit(score_text, pos)

‘’‘更新当前帧的游戏画面’‘’

def updateFrame(screen, obstacles, skier, score):

screen.fill((255, 255, 255))

obstacles.draw(screen)

screen.blit(skier.image, skier.rect)

showScore(screen, score)

pygame.display.update()

‘’‘主程序’‘’

def main():

游戏初始化

pygame.init()

pygame.mixer.init()

pygame.mixer.music.load(cfg.BGMPATH)

pygame.mixer.music.set_volume(0.4)

pygame.mixer.music.play(-1)

设置屏幕

screen = pygame.display.set_mode(cfg.SCREENSIZE)

pygame.display.set_caption(‘滑雪游戏 —— 九歌’)

游戏开始界面

ShowStartInterface(screen, cfg.SCREENSIZE)

实例化游戏精灵

–滑雪者

skier = SkierClass()

–创建障碍物

obstacles0 = createObstacles(20, 29)

obstacles1 = createObstacles(10, 19)

obstaclesflag = 0

obstacles = AddObstacles(obstacles0, obstacles1)

游戏clock

clock = pygame.time.Clock()

记录滑雪的距离

distance = 0

记录当前的分数

score = 0

记录当前的速度

speed = [0, 6]

游戏主循环

while True:

–事件捕获

for event in pygame.event.get():

最后

Python崛起并且风靡,因为优点多、应用领域广、被大牛们认可。学习 Python 门槛很低,但它的晋级路线很多,通过它你能进入机器学习、数据挖掘、大数据,CS等更加高级的领域。Python可以做网络应用,可以做科学计算,数据分析,可以做网络爬虫,可以做机器学习、自然语言处理、可以写游戏、可以做桌面应用…Python可以做的很多,你需要学好基础,再选择明确的方向。这里给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

👉Python所有方向的学习路线👈

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

👉Python必备开发工具👈

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

👉Python全套学习视频👈

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

👉实战案例👈

学python就与学数学一样,是不能只看书不做题的,直接看步骤和答案会让人误以为自己全都掌握了,但是碰到生题的时候还是会一筹莫展。

因此在学习python的过程中一定要记得多动手写代码,教程只需要看一两遍即可。

👉大厂面试真题👈

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

需要这份系统化学习资料的朋友,可以戳这里无偿获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 15
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值