【Dison夏令营 Day 26】PyGame 中的赛车游戏

在本文中,我们将了解如何使用 Pygame 在 Python 中创建一个赛车游戏。在这个游戏中,我们将拥有驾驶、障碍物碰撞、通过关卡时速度增加、暂停、倒计时、记分牌和说明书屏幕等功能。

在这里插入图片描述

所需模块:

在继续之前,请在命令提示符下运行以下命令行,安装必要的软件包,并将它们导入到您的 game.py 文件中:

pip install pygame
pip install time 
pip install random

项目结构:

在这里插入图片描述

第 1 步:导入所有模块

# code for developing car racing game in python 
import pygame 
import time 
import random 

第 2 步:设置屏幕

使用 pygame.init() 初始化所有 Pygame 模块。现在设置颜色值。现在设置不同文字的标题

pygame.image.load() 用于加载图像资源
# Initialize pygame and set the colors with captions 
pygame.init() 

# Define color codes 
gray = (119, 118, 110) 
black = (0, 0, 0) 
red = (255, 0, 0) 
green = (0, 200, 0) 
blue = (0, 0, 200) 
bright_red = (255, 0, 0) 
bright_green = (0, 255, 0) 
bright_blue = (0, 0, 255) 

# Define display dimensions 
display_width = 800
display_height = 600

# Set up game display 
gamedisplays = pygame.display.set_mode((display_width, 
										display_height)) 
pygame.display.set_caption("car game") 
clock = pygame.time.Clock() 

# Load car image and background images 
carimg = pygame.image.load('car1.jpg') 
backgroundpic = pygame.image.load("download12.jpg") 
yellow_strip = pygame.image.load("yellow strip.jpg") 
strip = pygame.image.load("strip.jpg") 
intro_background = pygame.image.load("background.jpg") 
instruction_background = pygame.image.load("background2.jpg") 

# Set car width and initialize pause state 
car_width = 56
pause = False

第 3 步:使用 “开始 ”屏幕

在 “开始 ”屏幕中,有三个按钮,分别名为 “开始”、“退出 ”和 “指导”。START 按钮将初始化游戏,QUIT 按钮将退出窗口,INSTRUCTION 按钮将显示玩家控制按钮。

如果当前屏幕是介绍屏幕,那么名为 intro 的布尔值将被设置为 True。

使用 .rect() 绘制矩形。输入长、宽、高来制作矩形。
blit() 将把矩形表面放到屏幕顶部。
# Intro screen 
def intro_loop(): 
	intro = True
	while intro: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 
				sys.exit() 

		# Display background image 
		gamedisplays.blit(intro_background, 
						(0, 0)) 

		# Render and display "CAR GAME" text 
		largetext = pygame.font.Font 
					('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects 
						("CAR GAME", largetext) 
		TextRect.center = (400, 100) 
		gamedisplays.blit(TextSurf, TextRect) 

		# Render and display "START" button 
		button("START", 150, 520, 100, 50, green, 
								bright_green, "play") 

		# Render and display "QUIT" button 
		button("QUIT", 550, 520, 100, 50, red, 
								bright_red, "quit") 

		# Render and display "INSTRUCTION" button 
		button("INSTRUCTION", 300, 520, 200, 
					50, blue, bright_blue, "intro") 

		pygame.display.update() 
		clock.tick(50) 

第 4 步:为按钮添加功能

现在,让我们把这些看起来花哨的按钮变成反应按钮。例如,“播放”(PLAY)按钮应触发主游戏循环,并带有一个计数器,用于计算玩家玩游戏的秒数。“退出”(QUIT)按钮应退出窗口。“介绍”(INTRO)按钮应提供游戏说明手册(详情将在下一步讨论)。

# Function to create a button with specified parameters 
# msg: The text to be displayed on the button 
# x, y: The coordinates of the top-left corner of the button 
# w, h: The width and height of the button 
# ic: The color of the button when inactive 
# ac: The color of the button when active (hovered over) 
# action: The action to be performed when the button is clicked 

def button(msg, x, y, w, h, ic, ac, action=None): 
	# Get the current mouse position 
	mouse = pygame.mouse.get_pos() 
	# Get the current state of mouse buttons 
	click = pygame.mouse.get_pressed() 

	# Check if mouse is within the button's boundaries 
	if x+w > mouse[0] > x and y+h > mouse[1] > y: 
		# Draw button with active color 
		pygame.draw.rect(gamedisplays, ac, (x, y, w, h)) 
		# Check if left mouse button is clicked 
		# and action is specified 
		if click[0] == 1 and action != None: 
			# If action is "play", call the countdown() 
			if action == "play": 
				countdown() 
			# If action is "quit", quit the game 
			elif action == "quit": 
				pygame.quit() 
				quit() 
				sys.exit() 

			elif action == "intro": 
				introduction() 
			# If action is "menu", call the intro_loop() function 
			elif action == "menu": 
				intro_loop() 
			# If action is "pause", call the paused() function 
			elif action == "pause": 
				paused() 
			# If action is "unpause", call the unpaused() function 
				unpaused() 
			elif action == "unpause": 

	else: 
		# Draw button with inactive color 
		pygame.draw.rect(gamedisplays, ic, (x, y, w, h)) 
	smalltext = pygame.font.Font("freesansbold.ttf", 20) 
	textsurf, textrect = text_objects(msg, smalltext) 
	textrect.center = ((x+(w/2)), (y+(h/2))) 
	gamedisplays.blit(textsurf, textrect) 

第 5 步:实现介绍界面

由于当前屏幕是说明屏幕,我们将把说明布尔值设为 true。在说明手册中,最重要的是玩家的控制和游戏的内容。因此,我们将在说明界面中组织这些细节。

pygame.font.Font('fontname.ttf', fontsize) => 这将显示指定字体大小的字体
# Function to display the introduction screen 
def introduction(): 
	introduction = True
	while introduction: 
		# Get events from the event queue 
		for event in pygame.event.get(): 
			# If the 'QUIT' event is triggered 
			# (e.g., window closed) 
			if event.type == pygame.QUIT: 
				pygame.quit() # Quit pygame 
				quit() # Quit the game 
				sys.exit() # Exit the system 
		# Draw the instruction background 
		gamedisplays.blit(instruction_background, (0, 0)) 
		# Set font for large text 
		largetext = pygame.font.Font('freesansbold.ttf', 80) 
		# Set font for small text 
		smalltext = pygame.font.Font('freesansbold.ttf', 20) 
		# Set font for medium text 
		mediumtext = pygame.font.Font('freesansbold.ttf', 40) 

		# Render and draw the instruction text 
		textSurf, textRect = text_objects("This is an car game" +
			"in which you need dodge the coming cars", smalltext) 
		textRect.center = ((350), (200)) 
		TextSurf, TextRect = text_objects("INSTRUCTION", largetext) 
		TextRect.center = ((400), (100)) 
		gamedisplays.blit(TextSurf, TextRect) 
		gamedisplays.blit(textSurf, textRect) 

		# Render and draw the control instructions 
		stextSurf, stextRect = text_objects( 
			"ARROW LEFT : LEFT TURN", smalltext) 
		stextRect.center = ((150), (400)) 
		hTextSurf, hTextRect = text_objects( 
			"ARROW RIGHT : RIGHT TURN", smalltext) 
		hTextRect.center = ((150), (450)) 
		atextSurf, atextRect = text_objects 
					("A : ACCELERATOR", smalltext) 
		atextRect.center = ((150), (500)) 
		rtextSurf, rtextRect = text_objects 
						("B : BRAKE ", smalltext) 
		rtextRect.center = ((150), (550)) 
		ptextSurf, ptextRect = text_objects 
						("P : PAUSE ", smalltext) 
		ptextRect.center = ((150), (350)) 
		sTextSurf, sTextRect = text_objects 
							("CONTROLS", mediumtext) 
		sTextRect.center = ((350), (300)) 
		gamedisplays.blit(sTextSurf, sTextRect) 
		gamedisplays.blit(stextSurf, stextRect) 
		gamedisplays.blit(hTextSurf, hTextRect) 
		gamedisplays.blit(atextSurf, atextRect) 
		gamedisplays.blit(rtextSurf, rtextRect) 
		gamedisplays.blit(ptextSurf, ptextRect) 

		# Render and draw the 'BACK' button 
		button("BACK", 600, 450, 100, 50, blue, 
							bright_blue, "menu") 

		pygame.display.update() # Update the display 
		clock.tick(30) # Limit frame rate to 30 FPS 

第 6 步:实现暂停功能

由于暂停函数会在您玩游戏时出现,因此它应该能够冻结除自身函数外的所有全局操作。因此,为了确保这一点,我们在 “暂停 ”按钮中使用了全局声明,并将其值设置为 True。按下 “暂停 ”按钮后,新界面将显示 “继续”(CONTINUE)、“重启”(RESTART)和 “主菜单”(MAIN MENU)按钮。取消暂停时,我们只需将全局布尔暂停重置为 “False”。

def paused(): 
	global pause 

	# Loop for handling events during pause state 
	while pause: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 
				sys.exit() 
		gamedisplays.blit(instruction_background, 
						(0, 0)) 
		largetext = pygame.font.Font('freesansbold.ttf', 
							115) 
		TextSurf, TextRect = text_objects("PAUSED", 
							largetext) 
		TextRect.center = ( 
		(display_width/2), 
		(display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		# Create buttons for continue, restart, and main menu 
		button("CONTINUE", 150, 
			450, 150, 50, 
			green, bright_green, "unpause") 
		button("RESTART", 350, 
			450, 150, 50, 
			blue, bright_blue, "play") 
		button("MAIN MENU", 550, 
			450, 200, 50, 
			red, bright_red, "menu") 
		pygame.display.update() 
		clock.tick(30) 


def unpaused(): 
	global pause 
	pause = False

第 7 步:游戏倒计时系统

让我们制作一个记分牌,记录得分和躲避汽车的情况。除此之外,我们还可以在 countdown_background() 中设置暂停按钮。

def countdown_background(): 
	# Import the necessary modules and set up the game display 
	# Initialize the font for displaying text 
	font = pygame.font.SysFont(None, 25) 
	# Set the initial positions for the game objects 
	# (background, strips, car, and text) 
	x = (display_width*0.45) 
	y = (display_height*0.8) 
	# Draw the background images on the game display 
	gamedisplays.blit(backgroundpic, (0, 0)) 
	gamedisplays.blit(backgroundpic, (0, 200)) 
	gamedisplays.blit(backgroundpic, (0, 400)) 
	gamedisplays.blit(backgroundpic, (700, 0)) 
	gamedisplays.blit(backgroundpic, (700, 200)) 
	gamedisplays.blit(backgroundpic, (700, 400)) 
	# Draw the yellow strips on the game display 
	gamedisplays.blit(yellow_strip, (400, 100)) 
	gamedisplays.blit(yellow_strip, (400, 200)) 
	gamedisplays.blit(yellow_strip, (400, 300)) 
	gamedisplays.blit(yellow_strip, (400, 400)) 
	gamedisplays.blit(yellow_strip, (400, 100)) 
	gamedisplays.blit(yellow_strip, (400, 500)) 
	gamedisplays.blit(yellow_strip, (400, 0)) 
	gamedisplays.blit(yellow_strip, (400, 600)) 
	# Draw the side strips on the game display 
	gamedisplays.blit(strip, (120, 200)) 
	gamedisplays.blit(strip, (120, 0)) 
	gamedisplays.blit(strip, (120, 100)) 
	gamedisplays.blit(strip, (680, 100)) 
	gamedisplays.blit(strip, (680, 0)) 
	gamedisplays.blit(strip, (680, 200)) 
	# Draw the car on the game display 
	gamedisplays.blit(carimg, (x, y)) 
	# Draw the text for the score and number of dodged cars 
	text = font.render("DODGED: 0", True, black) 
	score = font.render("SCORE: 0", True, red) 
	gamedisplays.blit(text, (0, 50)) 
	gamedisplays.blit(score, (0, 30)) 
	# Draw the "PAUSE" button on the game display 
	button("PAUSE", 650, 0, 150, 50, blue, bright_blue, "pause") 

第 8 步:执行倒计时函数

只要游戏开始,我们的倒计时就会开启,因此我们要将布尔值 countdown 设为 true。现在循环直到倒计时为 true,并在循环中调用 countdown_background。此外,在倒计时期间,时钟应该每 1 秒滴答作响一次,因此设置 clock.tick(1)。每秒钟后,我们将更新显示内容。这个循环一直持续到倒计时布尔值变为 false。

	gamedisplay.fill(color) => 这将用给定的颜色显示游戏画面
	pygame.display.update() => 每次调用它都会更新整个游戏图形界面。
def countdown(): 
	# Initialize a boolean variable to indicate if countdown is i 
		# n progress 
	countdown = True
	# Continue looping until countdown is complete 
	while countdown: 
		# Check for events in the pygame event queue 
		for event in pygame.event.get(): 
			# If user closes the game window 
			if event.type == pygame.QUIT: 
				pygame.quit() # Quit pygame 
				quit() # Quit the game 
				sys.exit() # Exit the program 
		# Fill the game display with a gray color 
		gamedisplays.fill(gray) 
		# Call a function to display the countdown background 
		countdown_background() 

		# Display "3" in large font at the center of the screen 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("3", largetext) 
		TextRect.center = ((display_width/2), (display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) # Delay for 1 second 

		gamedisplays.fill(gray) 
		countdown_background() 

		# Display "2" in large font at the center of the screen 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("2", largetext) 
		TextRect.center = ((display_width/2), (display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) # Delay for 1 second 

		gamedisplays.fill(gray) 
		countdown_background() 

		# Display "1" in large font at the center of the screen 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("1", largetext) 
		TextRect.center = ((display_width/2), (display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) # Delay for 1 second 

		gamedisplays.fill(gray) 
		countdown_background() 

		# Display "GO!!!" in large font at the center of the screen 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("GO!!!", largetext) 
		TextRect.center = ((display_width/2), (display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) # Delay for 1 second 
		# Call the game loop function after the countdown is complete 
		game_loop() 

第 9 步:定义游戏中的障碍物

在赛车比赛中会有一些障碍物,比如对手的赛车,因此让我们来定义这些障碍物。要制作障碍物,我们需要它们的 x、y 和 obs id。获得这些信息后,我们就可以在游戏窗口中轻松加载这些障碍物了。

# Loading the obstacles 
def obstacle(obs_startx, obs_starty, obs): 
	if obs == 0: 
		obs_pic = pygame.image.load("car.jpg") 
	elif obs == 1: 
		obs_pic = pygame.image.load("car1.jpg") 
	elif obs == 2: 
		obs_pic = pygame.image.load("car2.jpg") 
	elif obs == 3: 
		obs_pic = pygame.image.load("car4.jpg") 
	elif obs == 4: 
		obs_pic = pygame.image.load("car5.jpg") 
	elif obs == 5: 
		obs_pic = pygame.image.load("car6.jpg") 
	elif obs == 6: 
		obs_pic = pygame.image.load("car7.jpg") 
	gamedisplays.blit(obs_pic, (obs_startx, obs_starty)) 

第 10 步: 实现得分系统

score_system()函数用于显示分数,在下面将要讨论的 game_loop 函数中使用。text_objects()函数用于在屏幕上渲染文本。

def score_system(passed, score): 
	# Create a font object with size 25 
	font = pygame.font.SysFont(None, 25) 
	# Render the "Passed" text with passed parameter 
	# and color black 
	text = font.render("Passed"+str(passed), True, black) 
	# Render the "Score" text with score parameter and color red 
	score = font.render("Score"+str(score), True, red) 
	# Draw the "Passed" text on the game display at (0, 50) 
	# coordinates 
	gamedisplays.blit(text, (0, 50)) 
	# Draw the "Score" text on the game display at (0, 30) 
	# coordinates 
	gamedisplays.blit(score, (0, 30)) 


def text_objects(text, font): 
	# Render the given text with the given font and color black 
	textsurface = font.render(text, True, black) 
	return textsurface, textsurface.get_rect() 


def message_display(text): 
	# Create a font object with size 80 
	largetext = pygame.font.Font("freesansbold.ttf", 80) 
	# Render the given text with the created font 
	textsurf, textrect = text_objects(text, largetext) 
	textrect.center = ((display_width/2), (display_height/2)) 
	# Draw the rendered text on the game display at the center of the 
	# screen 
	gamedisplays.blit(textsurf, textrect) 
	pygame.display.update() 
	time.sleep(3) 
	game_loop() 

第 11 步:后备逻辑

无论开发人员创建什么程序,都应该考虑到一些回退机制,即如果程序出错无法运行,用户应该知道发生了什么。在本例中,我们将在主屏幕上显示 “YOU CRASHED”(你崩溃了)的信息。

def crash(): 
	message_display("YOU CRASHED") 

第 12 步:屏幕上的游戏用户界面

对于赛车游戏来说,我们需要一个道路图像和一些背景场景地形。我们将在背景功能中制作该用户界面。黄色条纹是道路上的竖条纹,通常位于道路中间。

# on Screen UI 
def background(): 
	gamedisplays.blit(backgroundpic, (0, 0)) 
	gamedisplays.blit(backgroundpic, (0, 200)) 
	gamedisplays.blit(backgroundpic, (0, 400)) 
	gamedisplays.blit(backgroundpic, (700, 0)) 
	gamedisplays.blit(backgroundpic, (700, 200)) 
	gamedisplays.blit(backgroundpic, (700, 400)) 
	gamedisplays.blit(yellow_strip, (400, 0)) 
	gamedisplays.blit(yellow_strip, (400, 100)) 
	gamedisplays.blit(yellow_strip, (400, 200)) 
	gamedisplays.blit(yellow_strip, (400, 300)) 
	gamedisplays.blit(yellow_strip, (400, 400)) 
	gamedisplays.blit(yellow_strip, (400, 500)) 
	gamedisplays.blit(strip, (120, 0)) 
	gamedisplays.blit(strip, (120, 100)) 
	gamedisplays.blit(strip, (120, 200)) 
	gamedisplays.blit(strip, (680, 0)) 
	gamedisplays.blit(strip, (680, 100)) 
	gamedisplays.blit(strip, (680, 200)) 


def car(x, y): 
	gamedisplays.blit(carimg, (x, y)) 

第 13 步:运行游戏

初始化 game_loop()后,我们将检查布尔暂停是否为假,如果为假,则继续游戏。我们会将 obstacle_speed 设置为 9,你可以根据自己的需要更改速度。为了检查玩家是否撞到了汽车,我们将把布尔值 bumped 初始化为 false。除此以外,在 game_loop 函数中,我们还将配置玩家的控制、每一关后障碍物速度的增加以及记分牌的递增。

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

def game_loop(): 
	global pause 
	x = display_width * 0.45
	y = display_height * 0.8
	x_change = 0
	obstacle_speed = 9
	obs = 0
	y_change = 0
	obs_startx = random.randrange(200, display_width - 200) 
	obs_starty = -750
	obs_width = 56
	obs_height = 125
	passed = 0
	level = 0
	score = 0
	y2 = 7
	fps = 120

	# flag to indicate that the player has been crashed 

	bumped = False

	while not bumped: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 

			if event.type == pygame.KEYDOWN: 
				if event.key == pygame.K_LEFT: 
					x_change = -5
				if event.key == pygame.K_RIGHT: 
					x_change = 5
				if event.key == pygame.K_a: 
					obstacle_speed += 2
				if event.key == pygame.K_b: 
					obstacle_speed -= 2
			if event.type == pygame.KEYUP: 
				if event.key == pygame.K_LEFT: 
					x_change = 0
				if event.key == pygame.K_RIGHT: 
					x_change = 0

		# Update player's car position 

	x += x_change 

	# Set pause flag to True 

	pause = True

	# Fill the game display with gray color 

	gamedisplays.fill(gray) 

	# Update background position 

	rel_y = y2 % backgroundpic.get_rect().width 
	gamedisplays.blit(backgroundpic, (0, rel_y 
									- backgroundpic.get_rect().width)) 
	gamedisplays.blit(backgroundpic, (700, rel_y 
									- backgroundpic.get_rect().width)) 

	# Draw background strips 

	if rel_y < 800: 

		# Draw background strips 

		gamedisplays.blit(backgroundpic, (0, rel_y)) 
		gamedisplays.blit(backgroundpic, (700, rel_y)) 
		gamedisplays.blit(yellow_strip, (400, rel_y)) 
		gamedisplays.blit(yellow_strip, (400, rel_y + 100)) 

	# Update obstacle positions and display them 

	y2 += obstacle_speed 
	obs_starty -= obstacle_speed / 4
	obstacle(obs_startx, obs_starty, obs) 
	obs_starty += obstacle_speed 

	# Update player's car position and display it 

	car(x, y) 

	# Update score system and display score 

	score_system(passed, score) 

	# Check for collision with screen edges and call crash() 
	# function if collision occurs 

	if x > 690 - car_width or x < 110: 
		crash() 
	if x > display_width - (car_width + 110): 
		crash() 
	if x < 110: 
		crash() 

	# Update obstacle positions and display them 

	if obs_starty > display_height: 
		obs_starty = 0 - obs_height 
		obs_startx = random.randrange(170, display_width - 170) 
		obs = random.randrange(0, 7) 
		passed = passed + 1
		score = passed * 10

		# Check for level up and update obstacle speed, display 
		# level text, and pause for 3 seconds 

		if int(passed) % 10 == 0: 
			level = level + 1
			obstacle_speed += 2
			largetext = pygame.font.Font('freesansbold.ttf', 80) 
			(textsurf, textrect) = text_objects('LEVEL' + str(level), 
												largetext) 
			textrect.center = (display_width / 2, display_height / 2) 
			gamedisplays.blit(textsurf, textrect) 
			pygame.display.update() 
			time.sleep(3) 

	# Check for collision with obstacles and call crash() 
	# function if collision occurs 

	if y < obs_starty + obs_height: 
		if x > obs_startx and x < obs_startx + obs_width or x \ 
			+ car_width > obs_startx and x + car_width < obs_startx \ 
				+ obs_width: 
			crash() 

	# Draw pause button 

	button( 
		'Pause', 
		650, 
		0, 
		150, 
		50, 
		blue, 
		bright_blue, 
		'pause', 
	) 

	# Update game display and set frames per second to 60 

	pygame.display.update() 
	clock.tick(60) 

第 14 步:调用函数

现在让我们调用重要函数来启动游戏,即

  • intro_loop(): PLAY(播放)、QUIT(退出)和 INSTRUCTION(指导)按钮屏幕。
  • game_loop() : 游戏的逻辑: 用于退出游戏窗口
intro_loop() 
game_loop() 
pygame.quit() 
quit() 

第 15 步:Window.py 文件

现在,所有这些程序都需要窗口选项卡才能运行。因此,让我们在当前目录下创建一个新文件 window.py(快照附在下面),并复制以下代码,现在运行代码,你就可以玩游戏了。

# Importing the Pygame library for game development 
import pygame 

# Importing the Time module for handling 
# time-related operations 
import time 

# Initializing Pygame 
pygame.init() 

# Width of the game window 
display_width = 800

# Height of the game window 
display_height = 600

# Setting the display mode with specified width and height 
display = pygame.display.set_mode((display_width, 
								display_height)) 

# Updating the display 
pygame.display.update() 

# Setting the caption/title of the game window 
pygame.display.set_caption("Car Game") 

# Creating a Clock object to control game frame rate 
clock = pygame.time.Clock() 

# Flag to indicate if the car is bumped or not 
bumped = False

# Looping until the car is bumped 
while not bumped: 
	# Checking for events (e.g. key presses, mouse clicks) 
	for event in pygame.event.get(): 
		# If the QUIT event is triggered (user closes the game window) 
		if event.type == pygame.QUIT: 
			# Set the bumped flag to True to exit the game loop 
			bumped = True
			# Quitting the game and closing the game window 
			quit() 

完整代码片段

# code for developing car racing game in python 
import pygame 
import time 
import random 

# initialize pygame and set the colors 
pygame.init() 
gray = (119, 118, 110) 
black = (0, 0, 0) 
red = (255, 0, 0) 
green = (0, 200, 0) 
blue = (0, 0, 200) 
bright_red = (255, 0, 0) 
bright_green = (0, 255, 0) 
bright_blue = (0, 0, 255) 
display_width = 800
display_height = 600

gamedisplays = pygame.display.set_mode( 
	(display_width, display_height)) 
pygame.display.set_caption("car game") 
clock = pygame.time.Clock() 
carimg = pygame.image.load('car1.jpg') 
backgroundpic = pygame.image.load("download12.jpg") 
yellow_strip = pygame.image.load("yellow strip.jpg") 
strip = pygame.image.load("strip.jpg") 
intro_background = pygame.image.load("background.jpg") 
instruction_background = pygame.image.load("background2.jpg") 
car_width = 56
pause = False

# Intro screen 


def intro_loop(): 
	intro = True
	while intro: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 
				sys.exit() 
		gamedisplays.blit(intro_background, (0, 0)) 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("CAR GAME", largetext) 
		TextRect.center = (400, 100) 
		gamedisplays.blit(TextSurf, TextRect) 
		button("START", 150, 520, 100, 50, green, 
			bright_green, "play") 
		button("QUIT", 550, 520, 100, 
			50, 
			red, 
			bright_red, 
			"quit") 
		button("INSTRUCTION", 300, 520, 200, 
			50, blue, bright_blue, 
			"intro") 
		pygame.display.update() 
		clock.tick(50) 


def button(msg, x, y, w, h, ic, ac, action=None): 
	mouse = pygame.mouse.get_pos() 
	click = pygame.mouse.get_pressed() 
	if x+w > mouse[0] > x and y+h > mouse[1] > y: 
		pygame.draw.rect(gamedisplays, 
						ac, (x, y, w, h)) 
		if click[0] == 1 and action != None: 
			if action == "play": 
				countdown() 
			elif action == "quit": 
				pygame.quit() 
				quit() 
				sys.exit() 
			elif action == "intro": 
				introduction() 
			elif action == "menu": 
				intro_loop() 
			elif action == "pause": 
				paused() 
			elif action == "unpause": 
				unpaused() 

	else: 
		pygame.draw.rect(gamedisplays, 
						ic, 
						(x, y, w, h)) 
	smalltext = pygame.font.Font("freesansbold.ttf", 20) 
	textsurf, textrect = text_objects(msg, smalltext) 
	textrect.center = ((x+(w/2)), (y+(h/2))) 
	gamedisplays.blit(textsurf, textrect) 


def introduction(): 
	introduction = True
	while introduction: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 
				sys.exit() 
		gamedisplays.blit(instruction_background, (0, 0)) 
		largetext = pygame.font.Font('freesansbold.ttf', 80) 
		smalltext = pygame.font.Font('freesansbold.ttf', 20) 
		mediumtext = pygame.font.Font('freesansbold.ttf', 40) 
		textSurf, textRect = text_objects( 
			"This is an car game in which you" +
			"need dodge the coming cars", smalltext) 
		textRect.center = ((350), (200)) 
		TextSurf, TextRect = text_objects("INSTRUCTION", largetext) 
		TextRect.center = ((400), (100)) 
		gamedisplays.blit(TextSurf, TextRect) 
		gamedisplays.blit(textSurf, textRect) 
		stextSurf, stextRect = text_objects( 
			"ARROW LEFT : LEFT TURN", smalltext) 
		stextRect.center = ((150), (400)) 
		hTextSurf, hTextRect = text_objects( 
			"ARROW RIGHT : RIGHT TURN", smalltext) 
		hTextRect.center = ((150), (450)) 
		atextSurf, atextRect = text_objects("A : ACCELERATOR", smalltext) 
		atextRect.center = ((150), (500)) 
		rtextSurf, rtextRect = text_objects("B : BRAKE ", smalltext) 
		rtextRect.center = ((150), (550)) 
		ptextSurf, ptextRect = text_objects("P : PAUSE ", smalltext) 
		ptextRect.center = ((150), (350)) 
		sTextSurf, sTextRect = text_objects("CONTROLS", mediumtext) 
		sTextRect.center = ((350), (300)) 
		gamedisplays.blit(sTextSurf, sTextRect) 
		gamedisplays.blit(stextSurf, stextRect) 
		gamedisplays.blit(hTextSurf, hTextRect) 
		gamedisplays.blit(atextSurf, atextRect) 
		gamedisplays.blit(rtextSurf, rtextRect) 
		gamedisplays.blit(ptextSurf, ptextRect) 
		button("BACK", 600, 450, 100, 50, blue, 
			bright_blue, "menu") 
		pygame.display.update() 
		clock.tick(30) 


def paused(): 
	global pause 

	while pause: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 
				sys.exit() 
		gamedisplays.blit(instruction_background, (0, 0)) 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("PAUSED", largetext) 
		TextRect.center = ( 
			(display_width/2), 
			(display_height/2) 
		) 
		gamedisplays.blit(TextSurf, TextRect) 
		button("CONTINUE", 150, 450, 
			150, 50, green, 
			bright_green, "unpause") 
		button("RESTART", 350, 450, 150, 
			50, blue, bright_blue, 
			"play") 
		button("MAIN MENU", 550, 450, 
			200, 50, red, bright_red, 
			"menu") 
		pygame.display.update() 
		clock.tick(30) 


def unpaused(): 
	global pause 
	pause = False


def countdown_background(): 
	font = pygame.font.SysFont(None, 25) 
	x = (display_width*0.45) 
	y = (display_height*0.8) 
	gamedisplays.blit(backgroundpic, (0, 0)) 
	gamedisplays.blit(backgroundpic, (0, 200)) 
	gamedisplays.blit(backgroundpic, (0, 400)) 
	gamedisplays.blit(backgroundpic, (700, 0)) 
	gamedisplays.blit(backgroundpic, (700, 200)) 
	gamedisplays.blit(backgroundpic, (700, 400)) 
	gamedisplays.blit(yellow_strip, (400, 100)) 
	gamedisplays.blit(yellow_strip, (400, 200)) 
	gamedisplays.blit(yellow_strip, (400, 300)) 
	gamedisplays.blit(yellow_strip, (400, 400)) 
	gamedisplays.blit(yellow_strip, (400, 100)) 
	gamedisplays.blit(yellow_strip, (400, 500)) 
	gamedisplays.blit(yellow_strip, (400, 0)) 
	gamedisplays.blit(yellow_strip, (400, 600)) 
	gamedisplays.blit(strip, (120, 200)) 
	gamedisplays.blit(strip, (120, 0)) 
	gamedisplays.blit(strip, (120, 100)) 
	gamedisplays.blit(strip, (680, 100)) 
	gamedisplays.blit(strip, (680, 0)) 
	gamedisplays.blit(strip, (680, 200)) 
	gamedisplays.blit(carimg, (x, y)) 
	text = font.render("DODGED: 0", True, black) 
	score = font.render("SCORE: 0", True, red) 
	gamedisplays.blit(text, (0, 50)) 
	gamedisplays.blit(score, (0, 30)) 
	button("PAUSE", 650, 0, 150, 50, blue, bright_blue, "pause") 


def countdown(): 
	countdown = True

	while countdown: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 
				sys.exit() 
		gamedisplays.fill(gray) 
		countdown_background() 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("3", largetext) 
		TextRect.center = ( 
			(display_width/2), 
			(display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) 
		gamedisplays.fill(gray) 
		countdown_background() 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("2", largetext) 
		TextRect.center = ( 
			(display_width/2), 
			(display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) 
		gamedisplays.fill(gray) 
		countdown_background() 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("1", largetext) 
		TextRect.center = ( 
			(display_width/2), 
			(display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) 
		gamedisplays.fill(gray) 
		countdown_background() 
		largetext = pygame.font.Font('freesansbold.ttf', 115) 
		TextSurf, TextRect = text_objects("GO!!!", largetext) 
		TextRect.center = ( 
			(display_width/2), 
			(display_height/2)) 
		gamedisplays.blit(TextSurf, TextRect) 
		pygame.display.update() 
		clock.tick(1) 
		game_loop() 


def obstacle(obs_startx, obs_starty, obs): 
	if obs == 0: 
		obs_pic = pygame.image.load("car.jpg") 
	elif obs == 1: 
		obs_pic = pygame.image.load("car1.jpg") 
	elif obs == 2: 
		obs_pic = pygame.image.load("car2.jpg") 
	elif obs == 3: 
		obs_pic = pygame.image.load("car4.jpg") 
	elif obs == 4: 
		obs_pic = pygame.image.load("car5.jpg") 
	elif obs == 5: 
		obs_pic = pygame.image.load("car6.jpg") 
	elif obs == 6: 
		obs_pic = pygame.image.load("car7.jpg") 
	gamedisplays.blit(obs_pic, 
					(obs_startx, 
					obs_starty)) 


def score_system(passed, score): 
	font = pygame.font.SysFont(None, 25) 
	text = font.render("Passed"+str(passed), True, black) 
	score = font.render("Score"+str(score), True, red) 
	gamedisplays.blit(text, (0, 50)) 
	gamedisplays.blit(score, (0, 30)) 


def text_objects(text, font): 
	textsurface = font.render(text, True, black) 
	return textsurface, textsurface.get_rect() 


def message_display(text): 
	largetext = pygame.font.Font("freesansbold.ttf", 80) 
	textsurf, textrect = text_objects(text, largetext) 
	textrect.center = ( 
		(display_width/2), 
		(display_height/2)) 
	gamedisplays.blit(textsurf, textrect) 
	pygame.display.update() 
	time.sleep(3) 
	game_loop() 


def crash(): 
	message_display("YOU CRASHED") 


def background(): 
	gamedisplays.blit(backgroundpic, (0, 0)) 
	gamedisplays.blit(backgroundpic, (0, 200)) 
	gamedisplays.blit(backgroundpic, (0, 400)) 
	gamedisplays.blit(backgroundpic, (700, 0)) 
	gamedisplays.blit(backgroundpic, (700, 200)) 
	gamedisplays.blit(backgroundpic, (700, 400)) 
	gamedisplays.blit(yellow_strip, (400, 0)) 
	gamedisplays.blit(yellow_strip, (400, 100)) 
	gamedisplays.blit(yellow_strip, (400, 200)) 
	gamedisplays.blit(yellow_strip, (400, 300)) 
	gamedisplays.blit(yellow_strip, (400, 400)) 
	gamedisplays.blit(yellow_strip, (400, 500)) 
	gamedisplays.blit(strip, (120, 0)) 
	gamedisplays.blit(strip, (120, 100)) 
	gamedisplays.blit(strip, (120, 200)) 
	gamedisplays.blit(strip, (680, 0)) 
	gamedisplays.blit(strip, (680, 100)) 
	gamedisplays.blit(strip, (680, 200)) 


def car(x, y): 
	gamedisplays.blit(carimg, (x, y)) 


def game_loop(): 
	global pause 
	x = (display_width*0.45) 
	y = (display_height*0.8) 
	x_change = 0
	obstacle_speed = 9
	obs = 0
	y_change = 0
	obs_startx = random.randrange(200, 
								(display_width-200)) 
	obs_starty = -750
	obs_width = 56
	obs_height = 125
	passed = 0
	level = 0
	score = 0
	y2 = 7
	fps = 120

	bumped = False
	while not bumped: 
		for event in pygame.event.get(): 
			if event.type == pygame.QUIT: 
				pygame.quit() 
				quit() 

			if event.type == pygame.KEYDOWN: 
				if event.key == pygame.K_LEFT: 
					x_change = -5
				if event.key == pygame.K_RIGHT: 
					x_change = 5
				if event.key == pygame.K_a: 
					obstacle_speed += 2
				if event.key == pygame.K_b: 
					obstacle_speed -= 2
			if event.type == pygame.KEYUP: 
				if event.key == pygame.K_LEFT: 
					x_change = 0
				if event.key == pygame.K_RIGHT: 
					x_change = 0

		x += x_change 
		pause = True
		gamedisplays.fill(gray) 

		rel_y = y2 % backgroundpic.get_rect().width 
		gamedisplays.blit( 
			backgroundpic, (0, 
							rel_y-backgroundpic.get_rect().width)) 
		gamedisplays.blit(backgroundpic, 
						(700, rel_y -
						backgroundpic.get_rect().width)) 
		if rel_y < 800: 
			gamedisplays.blit(backgroundpic, (0, rel_y)) 
			gamedisplays.blit(backgroundpic, (700, rel_y)) 
			gamedisplays.blit(yellow_strip, (400, rel_y)) 
			gamedisplays.blit(yellow_strip, (400, rel_y+100)) 
			gamedisplays.blit(yellow_strip, (400, rel_y+200)) 
			gamedisplays.blit(yellow_strip, (400, rel_y+300)) 
			gamedisplays.blit(yellow_strip, (400, rel_y+400)) 
			gamedisplays.blit(yellow_strip, (400, rel_y+500)) 
			gamedisplays.blit(yellow_strip, (400, rel_y-100)) 
			gamedisplays.blit(strip, (120, rel_y-200)) 
			gamedisplays.blit(strip, (120, rel_y+20)) 
			gamedisplays.blit(strip, (120, rel_y+30)) 
			gamedisplays.blit(strip, (680, rel_y-100)) 
			gamedisplays.blit(strip, (680, rel_y+20)) 
			gamedisplays.blit(strip, (680, rel_y+30)) 

		y2 += obstacle_speed 

		obs_starty -= (obstacle_speed/4) 
		obstacle(obs_startx, obs_starty, obs) 
		obs_starty += obstacle_speed 
		car(x, y) 
		score_system(passed, score) 
		if x > 690-car_width or x < 110: 
			crash() 
		if x > display_width-(car_width+110) or x < 110: 
			crash() 
		if obs_starty > display_height: 
			obs_starty = 0-obs_height 
			obs_startx = random.randrange(170, 
										(display_width-170)) 
			obs = random.randrange(0, 7) 
			passed = passed+1
			score = passed*10
			if int(passed) % 10 == 0: 
				level = level+1
				obstacle_speed+2
				largetext = pygame.font.Font("freesansbold.ttf", 80) 
				textsurf, textrect = text_objects( 
					"LEVEL"+str(level), largetext) 
				textrect.center = ( 
					(display_width/2), (display_height/2)) 
				gamedisplays.blit(textsurf, textrect) 
				pygame.display.update() 
				time.sleep(3) 

		if y < obs_starty+obs_height: 
			if x > obs_startx and x < \ 
					obs_startx + obs_width or x+car_width > \ 
					(obs_startx and x+car_width < obs_startx+obs_width): 
				crash() 
		button("Pause", 650, 0, 150, 50, blue, bright_blue, "pause") 
		pygame.display.update() 
		clock.tick(60) 


intro_loop() 
game_loop() 
pygame.quit() 
quit() 

在这里插入图片描述

  • 24
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值